Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python code snippet
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 : (
            for i in range(2) 
            if x >= 10 and x < 20]
        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 : (
            for i in range(2) 
            if x >= M[i] and x < M[i+1]]
        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.

[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.

Possibly Related Threads…
Thread Author Replies Views Last Post
  English interpretation of the following file handing snippet mortch 5 909 May-30-2019, 08:10 AM
Last Post: mortch
  Unable to read csv file inside full code snippet, at the same time its working seprat sreeraj 2 1,475 Jan-28-2018, 07:25 PM
Last Post: sreeraj

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020