<pre><code>len(list_of_players)
</code></pre>
<p>不会等于总数,因为</p>
^{pr2}$
<p>将创建一个从<code>0</code>到<code>len(list_of_players)</code><strong>互斥的</strong>范围,因此最后一个元素将等于<code>len(list_of_players) - 1</code>。因为在循环的每个迭代中,<code>1</code>添加到<code>total</code>中,<code>total</code>只会到达<code>len(list_of_players) - 1</code>,而你的{<cd8>}条件永远不会得到满足。在</p>
<p>但是,您也没有检查它是否是一个链,在示例<code>4</code>->;<code>6</code>->;<code>1</code>->;<code>3</code>->;<code>2</code>->;<code>0</code>->;<code>0</code>->;<code>4</code>是一个有效的链,您需要对此进行检查。
选择任何索引开始。保留一组你已经看到的项目,如果你在到达起始元素之前遇到了一个你已经看到的项目,那么这个链是不连续的。在</p>
<pre><code>total=0
list_of_players=[]
player=raw_input("Enter a player (end to stop): ")
while player !="end":
list_of_players.append(int(player))
player=raw_input("Enter a player (end to stop): ")
seen = set() # this could also be seen = [] but sets are faster
i = 0 # index to start at
# we should be able to go through len(list_of_players)
# before reaching the start player
for x in range(len(list_of_players)):
if i in seen:
print "the game is not valid. "
break
seen.add(i)
i = list_of_players[i]
else: # successful completion, no breaks
print "The game is valid. "
</code></pre>