Python Forum
python code snippet - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: python code snippet (/thread-16766.html)



python code snippet - chinna - Mar-13-2019

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.


RE: python code snippet - Shay - Mar-13-2019

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.


RE: python code snippet - chinna - Mar-13-2019

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.


RE: python code snippet - Shay - Mar-13-2019

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?


RE: python code snippet - chinna - Mar-15-2019

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.