'I can't understand why it won't return True always, since the ''return True'' statement is outside the loop
Assuming played_chicket and winning_chicket are 2 random lists wiht 4 elements each, what does this loop returns? I can't understand the logic behind it. Won't it return True always because the ''return True'' statement is outside the loop? I know it will return false if any of the elements are different but i can't see why. Can someone please, explain it to me?
def check_ticket(played_ticket, winning_ticket):
# Check all elements in the played ticket. If any are not in the
# winning ticket, return False.
for element in played_ticket:
if element not in winning_ticket:
return False
# We must have a winning ticket!
return True
Solution 1:[1]
This is most likely because the first element in played_ticket is not in winning_ticket
Consider played_ticket = [0,1,2] and winning_ticket = [1,2]
Your first iteration will look like this:
for element in played_ticket:
# element = 0
if element not in winning_ticket:
# 0 is not in winning_ticket, so it will return false immediately
return False
Your function as is will always return False or nothing (becomes None). You will need to edit the function to have a fallback return True:
def check_ticket(played_ticket, winning_ticket):
# Check all elements in the played ticket. If any are not in the
# winning ticket, return False.
for element in played_ticket:
if element not in winning_ticket:
return False
# Here
return True
So if every element is in the other list, it will return True
See this discussion if you would like to simplify your function
Solution 2:[2]
by turning winning ticket into a list you could invert the process checking if the element is True, return False if nothing is True:
def check_ticket(played_ticket, winning_ticket):
# Check all elements in the played ticket. If any are not in the
# winning ticket, return False.
if any(element in winning_ticket for element in played_ticket):
return True
return False
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | structure |
