[英]Alternating sum of integers in Python using lambda
I need to write a simple function in Python that calculates the alternating sum of a list of integers. 我需要在Python中编写一个简单的函数,用于计算整数列表的交替和。
Example: [ a1, a2, a3, ...] will be [a1 - a2 + a3 - a4...] 例如:[a1,a2,a3,...]将为[a1-a2 + a3-a4 ...]
I need to use a lambda function to implement this. 我需要使用lambda函数来实现这一点。
So far I have 到目前为止,我有
print reduce(lambda a,b : ((-a) + b), [10, 20, 30, 40])
which prints out 20; 打印出20; but it should print -20.
但应打印-20。
What am I doing wrong? 我究竟做错了什么?
In the case of your lambda function, reduce
works like this: 在使用lambda函数的情况下,
reduce
工作如下:
def myReduce(f, L):
arg1 = L[0]
for arg2 in L[1:]:
arg1 = f(arg1, arg2)
return arg1
As you can see, this will negate the running total every time: 如您所见,这每次都会抵消运行总计:
In the first iteration, it computes -10 + 20 = 10
, which then gets stored as arg1
. 在第一次迭代中,它计算
-10 + 20 = 10
,然后将其存储为arg1
。 Then, your lambda is called with the arguments 10
and 30
, which makes it compute -10 + 30 = 20
; 然后,使用参数
10
和30
调用您的lambda,这将使其计算-10 + 30 = 20
; so now arg1
takes the value 20
. 所以现在
arg1
取值20
。 Finally, the lambda is called with 20
and 40
, which makes it compute -20 + 40 = 20
. 最后,用
20
和40
调用lambda,这使它计算-20 + 40 = 20
。
See the problem? 看到问题了吗?
There are several ways by which you can solve this. 有几种解决方法。 Here are a few:
这里有一些:
L = [10, 20, 30, 40]
sum(map(lambda t : t[0]-t[1], zip(L[::2], L[1::2])))
Or 要么
answer = 0
for i,elem in enumerate(L):
mult = [1,-1][i%2]
answer += elem * mult
Or 要么
mults = itertools.cycle([1,-1])
answer = 0
for elem, mult in zip(L, mults):
answer += elem, mult
It's possible to include the cycle in a lambda like this 可以将循环包含在这样的lambda中
>>> from itertools import cycle
>>> reduce(lambda a, b, c=cycle((-1, 1)) : a + next(c) * b, [10, 20, 30, 40])
-20
The trick here is that reduce
only passes values to a
and b
. 这里的窍门是
reduce
只将值传递给a
和b
。 c
is assigned the cycle just once when the function is created 创建函数时,仅给
c
分配一次循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.