I was solving Kaggle list & comprehensions module and got the wrong answer for the following code:
def elementwise_greater_than(L, thresh):
"""Return a list with the same length as L, where the value at index i is
True if L[i] is greater than thresh, and False otherwise.
>>> elementwise_greater_than([1, 2, 3, 4], 2)
[False, False, True, True]
"""
for num in L:
if L[num] > thresh:
L[num] = True
else:
L[num] = False
return L
pass
It gives the following output: [False, False, 3, True]
There’s a mistake in if L[num]>thresh but I can’t understand what is it.
>Solution :
In python the in operator iterates over the values not the keys(as opposed to javascript) so L[num] will give you nonsense values.
try getting the length and using a regular for
def elementwise_greater_than(L, thresh):
"""Return a list with the same length as L, where the value at index i is
True if L[i] is greater than thresh, and False otherwise.
>>> elementwise_greater_than([1, 2, 3, 4], 2)
[False, False, True, True]
"""
count = len(L)
for num in range(0,count):
if L[num] > thresh:
L[num] = True
else:
L[num] = False
return L