Home > Net >  Reassigning values in list
Reassigning values in list

Time:11-30

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.

CodePudding user response:

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

CodePudding user response:

First thing don't write on the input L, create a different list. secondly when looping like this:

for num in L:

num is the value and not the index in each position.

Here is the 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]
    """
    lst = []
    for num in L:
        if num > thresh:
            lst.append(True)
        else:
            lst.append(False)
    return lst

And output:

[False, False, True, True]
  • Related