<p>永远不要离开检查列表的<code>while</code>循环。<code>break</code>语句只留下<code>for</code>循环(设置<code>total_seq = 3</code>)-您的<code>while</code>循环,直到<code>total_seq</code>大于</em>然后3->;<strong>无限循环</strong>:</p>
<blockquote>
<pre><code>while total_seq <= 3: # this is never been left because <= 3
check1 = "heads" # ^^ smaller equal
check2= "tails"
for toss in cointosses:
if toss == check1:
seq_counter1 +=1
seq_counter2 = 0
if seq_counter1 == 3:
total_seq = 3
break # breaks out of the for but total_seq = 3 so in while
if toss == check2:
seq_counter1 = 0
seq_counter2 +=1
if seq_counter2 == 3:
total_seq = 3
break # breaks out of the for but total_seq = 3 so in while
</code></pre>
</blockquote>
<hr/>
<p>只需添加到列表并检查<em>最后3个元素是否相等</em>而不是每次检查整个列表</em>,就可以简化代码:</p>
<pre><code>import random
def toss():
"""Return randomly 'heads' or 'tails'."""
return "heads" if (random.randint(1,2) == 1) else "tails"
# need at least 3 tosses to finish
cointosses = []
for _ in range(3):
cointosses.append(toss())
print(cointosses)
# repeat until the set(..) of the last 3 elements contains exactly 1 item
while not len(set(cointosses[-3:]))==1:
cointosses.append(toss())
print(cointosses)
print(f"It took {len(cointosses)} tosses to get 3 equal ones.")
</code></pre>
<p>输出2运行:</p>
<pre><code>['tails']
['tails', 'tails']
['tails', 'tails', 'heads']
['tails', 'tails', 'heads', 'heads']
['tails', 'tails', 'heads', 'heads', 'heads']
It took 5 tosses to get 3 equal ones.
['tails']
['tails', 'tails']
['tails', 'tails', 'heads']
['tails', 'tails', 'heads', 'heads']
['tails', 'tails', 'heads', 'heads', 'tails']
['tails', 'tails', 'heads', 'heads', 'tails', 'heads']
['tails', 'tails', 'heads', 'heads', 'tails', 'heads', 'tails']
['tails', 'tails', 'heads', 'heads', 'tails', 'heads', 'tails', 'tails']
['tails', 'tails', 'heads', 'heads', 'tails', 'heads', 'tails', 'tails', 'heads']
['tails', 'tails', 'heads', 'heads', 'tails', 'heads', 'tails', 'tails', 'heads', 'heads']
['tails', 'tails', 'heads', 'heads', ... snipp ..., 'tails', 'heads', 'heads', 'tails']
['tails', 'tails', 'heads', 'heads', ... snipp ..., 'heads', 'heads', 'tails', 'tails']
['tails', 'tails', 'heads', 'heads', ... snipp ..., 'heads', 'tails', 'tails', 'tails']
It took 13 tosses to get 3 equal ones.
</code></pre>
<p>如果您不喜欢<code>set()</code>,还可以检查:</p>
<pre><code>while not all(i == cointosses[-1] for i in cointosses[-3:-1]):
# rest identical
</code></pre>
<p>独行:</p>
<ul>
<li><a href="https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset" rel="nofollow noreferrer">set() and frozenset()</a></li>
<li><a href="https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation">Understanding Python's slice notation</a></li>
<li><a href="https://docs.python.org/3/library/functions.html" rel="nofollow noreferrer">python built in functions</a>-概述,备用方法使用<a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow noreferrer">all()</a></li>
</ul>