Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reassigning values in list

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading