对于循环评估value是否在列表中,不确定为什么返回true / false值

时间:2019-04-30 21:49:07

标签: python python-3.x

我刚进入python大约只有4天。我正在经历的这门课程提供了一些要解决的问题。它给出了正确或错误的正确答案,我只是不确定如何知道应该正确还是错误。

任何解释将不胜感激。

SPY GAME:编写一个函数,该函数接受一个整数列表,如果顺序包含007,则返回True。

def spy_game(nums):
    vals = [0,0,7,'x']
    for num in nums:
        if num == vals[0]:
            vals.pop(0)
    return len(vals) == 1

输出

spy_game([1,2,4,0,0,7,5])
>>True

2 个答案:

答案 0 :(得分:0)

添加了一些注释,以使事情有所清除。

def spy_game(nums):
    vals = [0,0,7,'x']
    #iterates through every number in the list in this case it's called nums 
    for num in nums:
    #checks if num is equal to the first index in vals
        if num == values[0]:
    #if the previous check is true it deletes the first element from the vals list and this means we know that this list contains a 0 so vlas would be [0,7,'x']

            vals.pop(0)
    # the for loop continues until it iterates through all num in nums.
    #becasue 'x' is not number the previous conidition in the for loop will never be True for 'x' will never be deleted
    #if the sequence of vals is in the nums list , that means only 'x' left in vals list =, which makes the next statement True otherwise it will return False
    return len(vals) == 1

Output

spy_game([1,2,4,0,0,7,5])
>>True

希望我对你更清楚。

答案 1 :(得分:0)

每次vals的第一个值在nums中时,都会将其从vals中删除。这意味着第二个现在是第一个。现在,它将根据下一个值nums进行检查。因此,如果nums的值以与vals的值相同的顺序显示,则除"x"以外的所有val值都将被删除。如果vals中的项目数量为1(是否只剩下"x"),则最后一行返回,这对应于是否存在相同顺序的相同数字。 / p>