Python Forum

Full Version: python code snippet
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
Im new to Python and trying to understand some existing code.
Can some one please explain the below code snippet and its function.

 
f = lambda x : (
            [L[i] 
            for i in range(2) 
            if x >= 10 and x < 20]
            [0])
        
        return np.vectorize(f, otypes=[np.uint32])(Array)
Thanks in advance.
Doesn't do much. Assuming this is inside a function that takes a sequence L of at least two items and a sequence Array.

For L = [1, 2] and Array = [10, 11, 21], this will yeild [1, 1, ... then fail with an IndexError.

For Array[0] = 10, 10 >=10 and < 20, so yields -> [1, 2][0] = 1
For Array[1] = 11, 11 >=10 and < 20, so yields -> [1, 2][0] = 1
For Array[2] = 21, 21 NOT >=10 and < 20, so raises an IndexError

Breaking it down,
f = lambda x: [L[i] for i in range(2) if x >= 10 and x < 20][0]
This defines a function that takes x. If x >= 10 and < 20, builds a list of the first two items of L, then takes the first item only. If x NOT >=10 and < 20, raises an IndexError.

np.vectorize(f, otypes=[np.uint32])(Array)
Given a function (here, that's f) that takes one argument and returns one value, creates a function that takes a sequence of arguments and returns a sequence of values. Then passes Array (a sequence of arguments) to that function.
Thanks Shay for your quick help.
Im able to understand now about this part of code.
But if the "if" condition is modified and it also depends on 'i'
as shown below,
 
f = lambda x : (
            [L[i] 
            for i in range(2) 
            if x >= M[i] and x < M[i+1]]
            [0])
        
        return np.vectorize(f, otypes=[np.uint32])(Array)
Will it behave the same.
That will behave *almost* the same unless you're modifying M somewhere. Otherwise, you're just replacing x >= 10 with x >= M[i], which will always be M[0] or M[1]. You still have a huge potential for an index error.

If
[L[i] for i in range(2) if x >= M[i] and x < M[i+1]]
creates an empty list, then there won't be an item to index at [0].

What are you trying to accomplish?
Thanks Shay for your inputs.
Actually, I need to convert python code into C/C++.
I am not sure what exactly they are doing in it.
So, going through the code to understand the python script.