Home > Mobile >  Using recursion to convert list members into an integer value
Using recursion to convert list members into an integer value

Time:11-10

I cannot get listA as integer 2345 with this recursion function. I want to convert [2,3,4,5] to 2345.

    listA = [2,3,4,5]
n = len(listA)

def fun(n):
    
    if(n == 0):
        return listA[n]
    else:
        return fun((listA[n])   (10**n))
        
fun(listA)

CodePudding user response:

You can don't actually need to get the length of the list beforehand. Instead you can get the length as you go.

l1 = [2,3,4,5]
def fun(l):
    if l1:
        return l1.pop(0)*(10**len(l1))   fun(l)
    return 0
print(fun(l1))

Output:

2345

CodePudding user response:

listA = [2,3,4,5]


def turnLstToInt(lst):
    return turnLstToIntHelper(lst,0)

def turnLstToIntHelper(lst,index):
    if index>len(lst)-1: # if greater than list return 0
        return 0
    power = len(lst)-1-index # find 10's power of digit
    placeVal = lst[index]*(10**power) # get value of digit at power level
    return placeVal   turnLstToIntHelper(lst,index 1)


print(turnLstToInt(listA))

CodePudding user response:

You've got the right idea, but you have some issues.

  1. You aren't going through the list but rather running the recursion on the "n-th" element of the list (which isn't even a valid index).
  2. You have no "quit" condition.
  3. You aren't concatenating the list together, but concatenating the length of the list together.

You will find that the following code solves these issues.

    def fun(listA):

        n = len(listA)

        if n == 0:
            return
        elif n == 1:
            return listA[0]
        else:
            return int(str(listA[0])   str(fun(listA[1:])))

    listA = [2,3,4,5]
    fun(listA)

If you aren't comfortable with type-casting, you can change the final return statement:

return (10**(n-1))*listA[0]   fun(listA[1:])

CodePudding user response:

Without len() and powers of 10:

def conv(lst):
    return 10*conv(lst[:-1])   lst[-1] if lst else 0

print(conv([2,3,4,5])) # 2345
  • Related