Reputation: 61
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?
Upvotes: -1
Views: 79
Reputation: 108
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")
Upvotes: 1
Reputation: 23498
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)
Upvotes: 2