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.
Related
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...
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)]
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)
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]
This question already has answers here:
In Python what's some other ways to write a if x==1 or x==5 or x==10...?
(3 answers)
Closed 9 years ago.
Take for example this code:
if int(str(x)[len(str(x)) - 1]) == 0 or int(str(x)[len(str(x)) - 1]) == 5:
return False
Supposing I have even a bigger list of or's, is there an easier way of doing this?
Ok, now that I know to use if x in ( , , , etc), how do I implement this into this:
filter(lambda x: int(str(x)[len(str(x)) - 1]) in (0, 5), range(1000)) Got it, wrong parenthesis, bad python programmer.
The simplest way is like this:
if x in (2,3):
....
If you have a large number of candidate values, then this will result in a linear search which could be expensive. If that matters then a set could result in better performance:
if x in set((2,3)):
....
Note that any performance benefit from using a set could only come if the set could be instantiated once, but tested for membership multiple times.
myset = set((2,3))
....
if x in myset:
....
It looks to me that you are actually testing divisibility by 5 which can be done like this:
if x % 5 == 0:
....
Use the ´in´ operator:
if x in (2, 3):
pass
Does this work?
if int(str(x)[-1]) in (0,5):
return False
Note that some_array[-1] returns the last element in some_array so that you don't have to do some_array[len(sum_array) - 1]