高阶函数 Python(永无止境?)
Higher Order Function Python (never ending?)
我有一个代码在输入递增的值(如“123”)时有效,但在下一个字符小于前一个字符(例如“132”)时无效,如果有相同的数字,则递归永不停止(例如“122”)
请指出我的代码中的问题,将不胜感激。
def sum(term, a, next, b):
if (a > b):
return 0
else:
print (term(a), a, next(a), b)
return term(a) + sum(term, next(a), next, b)
def knocked_down(game):
t1 = lambda x:int(game[x])
t2 = 0
t3 = lambda x: int(game[x])
t4 = len(game)-1
return sum(t1, t2, t3, t4)
results=knocked_down("123")
print('---')
print(results)
在sum
函数中,参数可能表示
term
:通过索引取值的函数
a
: 起始索引
next
: 获取下一个索引的函数
b
: 最后索引
OP 说:
The sum()
function wasn't written by me. I was tasked to use it and I'm not allowed to change the code.
所以我没有接触 sum
函数。
您可以将 t3
更改为 lambda x: x + 1
.
def sum(term, a, next, b):
if (a > b):
return 0
else:
print(term(a), a, next(a), b)
return term(a) + sum(term, next(a), next, b)
def knocked_down(game):
t1 = lambda x: int(game[x])
t2 = 0
t3 = lambda x: x + 1
t4 = len(game) - 1
return sum(t1, t2, t3, t4)
results = knocked_down("132")
print('---')
print(results)
输出:
1 0 1 2
3 1 2 2
2 2 3 2
---
6
我有一个代码在输入递增的值(如“123”)时有效,但在下一个字符小于前一个字符(例如“132”)时无效,如果有相同的数字,则递归永不停止(例如“122”)
请指出我的代码中的问题,将不胜感激。
def sum(term, a, next, b):
if (a > b):
return 0
else:
print (term(a), a, next(a), b)
return term(a) + sum(term, next(a), next, b)
def knocked_down(game):
t1 = lambda x:int(game[x])
t2 = 0
t3 = lambda x: int(game[x])
t4 = len(game)-1
return sum(t1, t2, t3, t4)
results=knocked_down("123")
print('---')
print(results)
在sum
函数中,参数可能表示
term
:通过索引取值的函数a
: 起始索引next
: 获取下一个索引的函数b
: 最后索引
OP 说:
The
sum()
function wasn't written by me. I was tasked to use it and I'm not allowed to change the code.
所以我没有接触 sum
函数。
您可以将 t3
更改为 lambda x: x + 1
.
def sum(term, a, next, b):
if (a > b):
return 0
else:
print(term(a), a, next(a), b)
return term(a) + sum(term, next(a), next, b)
def knocked_down(game):
t1 = lambda x: int(game[x])
t2 = 0
t3 = lambda x: x + 1
t4 = len(game) - 1
return sum(t1, t2, t3, t4)
results = knocked_down("132")
print('---')
print(results)
输出:
1 0 1 2
3 1 2 2
2 2 3 2
---
6