[英]Recursively Converting a List of Digits to a Number
I did it with a for loop. 我做了一个for循环。
def base2dec(nums, base):
adding = []
power = -1
for num in nums[::-1]:
power+=1
adding.append(num*pow(base, power))
return sum(adding)
But the tutorial exercise requires that I do it using recursion. 但是本教程练习要求我使用递归进行。 Which I don't quite understand. 我不太了解。 The function base2dec(nums,base)
takes a list of integers ( nums
) in the given base
and returns the corresponding base 10 number. 函数base2dec(nums,base)
接受给定base
的整数列表( nums
),并返回相应的以10为底的数字。 Can you guys show me how to do it with recursion? 你们可以告诉我如何进行递归吗? I really don't know how. 我真的不知道
The key point here is to split the list to one element and the rest, and pass the rest recursively: 这里的关键点是将列表分为一个元素和其余元素,然后递归传递其余元素:
def base2dec(nums, base):
if len(nums) == 1:
return nums[0]
else:
return nums[-1] + base * base2dec(nums[:-1], base)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.