【发布时间】:2023-03-09 07:55:01
【问题描述】:
这段简单的代码运行良好。我要问的完全没有必要;但是,我正在尝试更多地了解函数式编程方法。
p=[0, 1, 0, 0, 0]
pHit = 0.6
pMiss = 0.2
pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1
def move(p, U):
q = []
# A functional approach could be used here as well, but focusing on the outer loop at the moment.
for i in range(len(p)):
s = pExact * p[(i-U) % len(p)]
s = s + pOvershoot * p[(i-U-1) % len(p)]
s = s + pUndershoot * p[(i-U+1) % len(p)]
q.append(s)
return q
#Instead of this for loop here, is there a more functional approach to doing the same thing?
for i in range(0,1000):
p = move(p,1)
print move(p,1)
这个人问了一个类似的问题,但不同之处在于他/她将递归函数应用于被迭代的实际对象。 Using recursion with map in python
我的情况似乎不同,因为我没有迭代我正在应用递归函数的对象(列表“p”)。 “for循环”处理得很好,因为我想做递归操作范围(0,1000)次,但我已经看到这个问题出现了几次,我对看到函数式编程非常感兴趣解决这个问题。
我尝试使用reduce() 几次,但我发现很难将 X 迭代的输出传递给 X+1 迭代。
【问题讨论】:
-
reduce的整点就是将x次迭代的结果传递给x+1次迭代。我建议再次查看减少,添加它们可能非常有用。 -
您完全正确,但我看到的 reduce() 示例正在迭代执行操作的对象。我见过一些 reduce() 和 map() 的组合,但它们并不完全适用于这种情况。
-
即使您不关心正在迭代的集合中的项目,也可以使用缩减。减少
range可用于反复多次应用减少。考虑reduce(lambda acc n: return acc + 1), range(100), 0)。抱歉,如果有任何语法错误。我已经有一段时间没有写 Python 了。
标签: python recursion functional-programming