How to make a list of functions in python? [duplicate] - python

This question already has answers here:
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
Closed 5 years ago.
I tried to achieve something like this
list1 = [lambda x: x+0, lambda x: x+1]
by doing this
list2 = [lambda x: x+n for n in range(2)]
But it doesn't work! (Why not?)
How do I create a list of functions programmatically?

n is reassigned by the for expression, so after the for expression is completed both will see value of n being 1.
More typical example of this problem can be visible without list expression:
list3 = []
for n in range(2):
def f(x):
return x + n
list3.append(f)
Here also all created function objects will refer to the same variable n and it will be assigned value 1 and both function objects will work as lambda x: x + 1.
You can deal with it by creating additional scope with a variable for each created function:
a = [(lambda n: lambda x: x+n)(n) for n in range(2)]

Related

Function that appends to list of choice [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 4 years ago.
I'm trying to create a function with two inputs that can append a value into a list of choice. I'm starting of with two lists to get the code working before I build up.
a = []
b = []
def func(z,x):
if z == a:
a.append(x)
elif z == b:
b.append(x)
print(a,b)
For some reason it appends to the first list, then the second, no matter which I select. I've only just started to learn python, so I may have missed something basic.
== when comparing two lists sees if they contain the same items. An empty list is equivalent to another empty list, so the first time that function is called, it will always append to a. What you could use instead is is (if z is a:), but a much better way is to ignore a and b, and just use z directly:
def func(z, x):
z.append(x)
print(a, b)
which brings up doubts as to why this function is needed...

and() and any() with custom condition [duplicate]

This question already has answers here:
How to achieve python's any() with a custom predicate?
(2 answers)
Closed 6 years ago.
I am trying to find out if there are any built-in tools in Python that work the same way any() and all() are implemented, but instead of checking if each element is truthy or falsy, you can pass your own boolean-evaluating function or lambda, sort of like you can do with the map() function.
So what I'm asking is if there are any built-in functions where you could do something like:
from random import randint
lst = [randint(1, 100) for _ in range(1000000)]
has_even = any(lambda x: not x % 2, lst)
or
has_even = any(has_even_fn, lst)
where has_even_fn would be a function that checked if an integer is even.
You can still use any() to check if lst has evens:
has_even = any([not x % 2 for x in lst])
But of course this is strictly O(n) because the entire boolean list has to be built first, while the function I am asking for would only be O(n) in the worst case, and potentially O(1) in the best case.
As already stated in the comments, you can just remove the [ ] to get a lazy-evaluating generator expression instead of an eager list comprehension:
contains_one_or_more_even = any(x % 2 == 0 for x in lst)
or
contains_only_even = all(x % 2 == 0 for x in lst)

Understanding how Lambda function works [duplicate]

This question already has answers here:
How are lambdas useful? [closed]
(26 answers)
Closed 6 years ago.
Help me understand Lambda functions, I checked a lot of codes but I still can't manage to understand it. Maybe with a simple example, thanks in advance.
Suppose you want to square in value in a list , foo = [1,2,3,4,5]
for i in range(len(a)):
a[i] = a[i] * a[i]
You could use lambda and write
map(lambda x: x * x, foo)
if you want only elements divisible by 3, then
filter(lambda x: x % 3 == 0, foo)
Basically it save you from writing a for loop or to put it better write it in an efficient way.

Python array algorithm [duplicate]

This question already has answers here:
How to find the cumulative sum of numbers in a list?
(25 answers)
Closed 6 years ago.
I'm working on writing a function where an array is given:
arrayA = [2,3,1]
The function needs to return a new array where:
newArray = [2,5,6]
This is almost like a Fibonacci function.
newArray[0] = arrayA[0]
newArray[1] = arrayA[0] + arrayA[1]
newArray[2] = arrayA[1] + arrayA[2] + arrayA[3]
Heres my code so far, but always end up with a empty list. arrayA is passed in as parameter.
def generateNewArray(A):
A=[]
newArray=[]
for i in range(len(A)):
newArray[i]=A[i]+A(i+1)
return newArray
print [sum(A[:i]) for i in range(1,len(A)+1)]
I guess ... I think theres actually a cumulative sum builtin somewhere ... or maybe its in numpy
numpy.cumsum(A)
You can also use a functional programming pattern:
Try this:
def generateNewArray(inputArray):
return map(lambda x: sum(inputArray[:x]), xrange(1, len(inputArray) + 1))
For example:
In [7]: generateNewArray([2, 3, 1])
Out[7]: [2, 5, 6]

Python: Append lambda functions to list [duplicate]

This question already has answers here:
What do lambda function closures capture?
(7 answers)
Closed 9 years ago.
Can anyone do sanity check?
I'm trying to make functions in for-loop.
The point I can't understand is summarized in the following code:
f_list = []
for i in range(10):
f = lambda j : i
f_list.append(f)
Then,
>>> f_list[0](0)
9 #I hope this is 0.
>>> f_list[1](0)
9 #I hope this is 1.
Why is this happen??
Edit: Almost the same problem is already discussed in Stackoverflow, here.
This is because of the closure property of python. To get what you actually need, you need to do like this
f = lambda j, i = i : i
So, the output of this program becomes like this
f_list = []
for i in range(5):
f = lambda j, i = i : i
f_list.append(f)
for i in range(5):
print f_list[i](0)
Output
0
1
2
3
4

Categories