[英]Python - Recursive Function does not work with len() despite the returned value being a list
So I want to create a recursive function that functions in a use-it or lose-it sense, where it uses an unlimited number of coins by a list, and counts the number that are needed. 所以我想创建一个递归函数,它在一个use-it或lost-it意义上起作用,它在列表中使用无限数量的硬币,并计算所需的数量。
So say you have: change(48, [1, 5, 10, 25, 50]) it would return 6, because it would use 25x1, 10x2 and 1x3, totalling 6 coins. 所以说你有:改变(48,[1,5,10,25,50])它将返回6,因为它将使用25x1,10x2和1x3,共计6个硬币。
def change(value, L):
if not L:
return L
if L[-1] > value:
return change(value, L[:-1])
else:
useIt = [L[-1]] + change(value - L[-1], L)
return useIt
This returns the list of the coins used, however if I return len(useIt), I get this error: 这将返回使用的硬币列表,但是如果我返回len(useIt),我会收到此错误:
TypeError: can only concatenate list (not "int") to list TypeError:只能将列表(不是“int”)连接到列表
However, this would return the right value: 但是,这将返回正确的值:
print(len(change(48, [1, 5, 10, 25, 50])))
How do I return the length of the list without doing this? 如何在不执行此操作的情况下返回列表的长度? And no loops please, only recursion, this is review for an exam.
请不要循环,只有递归,这是考试的复习。
You have done excellent work, just place 1
in place of [L[-1]]
in else part and return 0 in the base case and you are done. 你已经完成了出色的工作,只需将
1
替换为[L[-1]]
in else part并在基本情况下返回0并完成。
def change(value, L):
if not L:
return 0
if L[-1] > value:
return change(value, L[:-1])
else:
useIt = 1 + change(value - L[-1], L)
return useIt
print(change(48, [1, 5, 10, 25, 50]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.