这是一个代码破坏问题的解决方案,但我没有得到解决方案。
SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order
def spy_game(nums):
code = [0,0,7,'x']
for num in nums:
if num == code[0]:
code.pop(0) # code.remove(num) also works
return len(code) == 1
这个 for 循环如何检查每个索引号,尽管它特别指出索引 0?
最佳答案
由于执行了 code.pop(0)
,您将从列表 code
中删除索引 0 处的元素。当您使用 [0, 0, 7]
调用函数时,将进行以下循环迭代:
nums = [0, 0, 7]
code = [0, 0, 7, 'x']
# First iteration
num = 0 (first element of nums)
num == code[0] is true
code[0] is removed
code = [0, 7, 'x']
# Second iteration
num = 0 (second element of nums)
num == code[0] is true
code[0] is removed
code = [7, 'x']
# Third iteration
num = 7 (third element of nums)
num == code[0] is true
code[0] is removed
code = ['x']
# End of the loop
All elements of nums have been iterated, so the loop is over
code = ['x']
len(code) == 1 is true
True is returned
关于python - 这个 for 循环如何检查每个索引号,即使它特别指出索引 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53988901/