我知道如何在列表中添加数字递归减法(名单)递归在Python 3
def mysum(L):
if not L:
return 0
else:
return L[0] + mysum(L[1:])
你能帮我递归构建减法以同样的方式(只有一个输入 - 列表)。
mydiff([10,1,2,3])
非常感谢
我知道如何在列表中添加数字递归减法(名单)递归在Python 3
def mysum(L):
if not L:
return 0
else:
return L[0] + mysum(L[1:])
你能帮我递归构建减法以同样的方式(只有一个输入 - 列表)。
mydiff([10,1,2,3])
非常感谢
如果序列为(3,2,1)
,结果为0,但减法会在相反的方向,即2 -1
比3 - (2-1)
如果使用return L[0] - mysum(L[1:])
。
所以我们必须使用一个累加器来保持序列的第一个和第二个元素的差异。
def mydiff(L, acc=None):
if not L:
return acc
else:
if acc is None:
acc = L[0] - L[1]
L = L[2:]
else:
acc -= L[0]
L = L[1:]
return mydiff(L, acc)
更简单一个;
def mysub(seq, acc=None):
seq = iter(seq)
if acc is None:
item = next(seq, None)
if item is None:
return acc
acc = item
item = next(seq, None)
if item is None:
return acc
return mysub(seq, acc - item)
的计算做是
>>> 10-(1+(2+(3+0)))
4
所以第一操作是减法,但这些操作的其余部分保持加法。我认为你需要使用一个内部函数,如果你不允许第二个参数添加到主要功能:
def mydiff(L):
def sub(L, first=False):
if not L:
return 0
else:
if first:
return L[0] - sub(L[1:])
else:
return L[0] + sub(L[1:])
return sub(L, True)
测试:
>>> mydiff([10,1,2,3])
4
代码很清楚,但不会返回结果 –
@DanielYefimov您可以在我的示例中看到它确实会返回结果。你为什么认为它不? – uselpa
我刚才穿上它,但我错了打印结果。 如果mydiff([10,1,2,3])显示为8,但应该是4 –
您是否允许使用内部函数,即在'mydiff'内定义函数? – uselpa