Return True if array contains a 2 or a 3
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs
--
Chapters
00:00 Question
00:43 Accepted answer (Score 7)
01:35 Answer 2 (Score 0)
02:58 Answer 3 (Score 0)
03:15 Thank you
--
Full question
https://stackoverflow.com/questions/1558...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python27
#avk47
ACCEPTED ANSWER
Score 7
Your first one doesn't work because the for loop in Python isn't the same as the for loop in other languages. Instead of iterating over the indices, it iterates over the actual elements.
for item in nums is roughly equivalent to:
for (int i = 0; i < nums.length; i++) {
int item = nums[i];
...
}
Your second one doesn't work because it returns False too soon. If the loop encounters a value that isn't 2 or 3, it returns False and doesn't loop through any other elements.
Change your loop to this:
def has23(nums):
for i in nums:
if i == 2 or i == 3:
return True # Only return `True` if the value is 2 or 3
return False # The `for` loop ended, so there are no 2s or 3s in the list.
Or just use in:
def has23(nums):
return 2 in nums or 3 in nums
ANSWER 2
Score 0
Another way to do the above using index A variation for learning purpose
def has23(nums):
try :
alpha = nums.index(2)
return True
except:
try:
beta = nums.index(3)
return True
except:
return False
ANSWER 3
Score 0
Old post, I know, but for future readers:
Regarding the for loop, I think it's worth mentioning another option: using the range() function.
Instead of
for i in nums:
You can switch the for loop to look like so:
for i in range(len(nums)):
This will iterate over integers, the same as other languages do.
Then using nums[i] will get the value of the index.
However, I notice another problem with your code and its stated objectives: within the for loop, all execution paths return a variable. It will only go through the for loop once, regardless of the length of the array, because after the first execution it returns, ending the function's execution. If the first value is false, the function will return false.
Instead, you would want to end the execution within the loop only if the statement is true. If the loop goes through all posibilities and nothing is false, then return false:
def has23(nums):
for i in range(len(nums)): # iterate over the range of values
if nums[i]==2 or nums[i]==3:# get values via index
return true # return true as soon as a true statement is found
return false # if a true statement is never found, return false