简体   繁体   中英

Recursively Converting a List of Digits to a Number

I did it with a for loop.

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM