python - Python求和高阶函数
问题描述
我正在写一个求和的迭代解决方案,它似乎给出了正确的答案。但是我的导师告诉我,它给出了错误的结果non-commutative combine operations
。我去了谷歌,但我仍然不确定它到底是什么意思......
这是我写的递归代码:
def sum(term, a, next, b):
# First recursive version
if a > b:
return 0
else:
return term(a) + sum(term, next(a), next, b)
def accumulate(combiner, base, term, a, next, b):
# Improved version
if a > b:
return base
else:
return combiner(term(a), accumulate(combiner, base, term, next(a), next, b))
print(sum(lambda x: x, 1, lambda x: x, 5))
print(accumulate(lambda x,y: x+y, 0, lambda x: x, 1, lambda x: x, 5))
# Both solution equate to - 1 + 2 + 3 + 4 + 5
这是我写的迭代版本,它给出了错误的结果non-commutative combine operations
- 编辑:当lambda x,y: x- y
用于组合器时,accumulate_iter 给出了错误的结果
def accumulate_iter(combiner, null_value, term, a, next, b):
while a <= b:
null_value = combiner(term(a), null_value)
a = next(a)
return null_value
希望有人可以为这个迭代版本提供解决方案accumulate
解决方案
当组合器是可交换的时你accumulate_iter
工作得很好,但是当组合器是非交换的时它会给出不同的结果。那是因为递归accumulate
组合元素从后到前,但迭代版本将它们从前到后组合。
所以我们需要做的是accumulate_iter
从后面进行组合,下面是一个重写的accumulate_iter
:
def accumulate_iter(a, b, base, combiner, next, term):
# we want to combine from behind,
# but it's hard to do that since we are iterate from ahead
# here we first go through the process,
# and store the elements encounted into a list
l = []
while a <= b:
l.append(term(a))
a = next(a)
l.append(base)
print(l)
# now we can combine from behind!
while len(l)>1:
l[-2] = combiner(l[-2], l[-1])
l.pop()
return l[0]
推荐阅读
- javascript - 如何使用 javascript 更改网格的列样式
- angular7 - 通过单击角度 7 中的一行来显示和隐藏组件
- php - nextcloud 问题:重复上游“php-handler”
- python - Twython - 我怎样才能加快获得用户的关注者?
- java - 如何创建可执行的可执行 jar (Maven-Jfoenix-Hibernate-IntelliJ) __ 有人可以解决/关闭该主题吗
- jmeter - 需要通过 JMeter 发送多个 PUT 请求
- php - PHP mail()函数不发送特定文本
- c# - 如何处理 Swashbuckle 中的路径/路由参数?
- javascript - 获取另一个页面的 DOM,不同的服务器
- reactjs - 如何在 react.js 中使用(graphql query + relay)获取所有数据?