代码不会继续循环

时间:2015-04-29 10:27:46

标签: loops python-3.x indexing

我需要编写一个函数has22(nums),该函数需要list的整数nums并返回True,如果该列表在某个地方的2旁边包含2。

我的方法:

def has22(nums):
    for i in range(len(nums)-1):
        if nums[i] == 2 and nums[i+1] == 2:
            return True
        else:
            return False

print(has22([1, 2, 2]))  **Should** evaluate to: True #Got: False

print(has22([1, 2, 21, 2])) evaluates to: False
print(has22([2, 1, 2])) evaluates to: False
print(has22([2, 2])) evaluates to: True
print(has22([4, 3, 2, 1])) evaluates to: False

我需要做什么才能让函数继续循环?

1 个答案:

答案 0 :(得分:1)

问题是你在第一对后立即返回False!相反,您只应在扫描整个列表后返回False

def has22(nums):
    for i in range(len(nums)-1):
        if nums[i] == 2 and nums[i+1] == 2:
            return True
    return False

或者,您也可以使用zip(nums, nums[1:])生成所有连续数字对:

def has22(nums):
    return (2, 2) in zip(nums, nums[1:])