简体   繁体   中英

Why this loop doesn't work while the similar one works?

This function should return True if the list "nums" contains a 3 next to a 3 somewhere.

The function "has_33" should accept a list argument, so this loop works perfectly :-

def has_33(nums):
    for i in range(0, len(nums)-1):

        if nums[i:i+2] == [3,3]:
            return True  

    return False

But when I do it in this form :-

def has_33(nums):
    for i in range(0,len(nums)-1):  

        if nums[i:i+2] == [3,3]:
            return print("True")
        else:
            if i == len(nums)-1:
                return print("False")

it fails to print "False" if the array doesn't include the condition.

So why the first loop works while the second loop doesn't work although they are the same?

You should not put this condition:

if i == len(nums)-1:

inside your function. And even if you do, use:

if i == len(nums)-2:

because i will never become len(nums)-1 (see the loop condition above)

num == len(nums)-1 never evaluates True , because num is a list, not an integer.

The bigger issue at hand is though, that this whole else clause is unnecessary, as you can just let python exit the loop, and then print("False"). Additionally,'i suggest the following solution:

from itertools import tee


def has_33(nums):
    num1, num2 = tee(nums)
    next(num2)
    for a, b in zip(num1, num2):
        if [a, b] == [3, 3]:
            print("True")
            return
    print("False")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM