CoCalc Public Filesprojects_F20 / rec_Proj6 / recursion.ipynbOpen with one click!
Author: Julia Burnside
Views : 30
Compute Environment: Ubuntu 20.04 (Default)

Recursive Conversion from List to Integers

An empty array called listlist is declared. The user is prompted to enter a sequence of single digit integers between 11 and 99. Each integer entered will append the length of listlist and be added to the array. 1-1 is assigned as the command value to quit the process and proceed to converting the values in listlist to an integer.

The function rec_intrec\_int takes a single parameter, listlist. First, the function evaluates the length of listlist. If the length is 11, meaning there is only a single value in the array, then the function returns that value at list[0]list[0]. Otherwise, the function will take the value at list[0]list[0] and multiply it by 1010 to the power of the length of the array, minus 11. So, for example, if the array is of length 33 and the first value is 22, this process will yield 21031=2102=2100=2002*10^{3-1}=2*10^2=2*100=200. To add the remaining values in the array, the function is then called recursively with the appendment of slicing the array to list[1:]list[1:]. This precludes the first value of the array and also appends the length of listlist. The function will continue to iterate through this process until the length of list=1list=1, which will then yield the final value of the list transformed into an integer.

In [8]:
list=[] print("Enter a list of single digit integers, or -1 to quit and proceed to conversion", '\n') x=int(input()) while (x!=-1): if (x<0 or x>9): print("invalid entry. Enter a single digit integer", '\n') else: list.append(x) x=int(input()) def rec_int(list): if len(list) == 1: return list[0] else: return list[0]*(10**(len(list)-1))+(rec_int(list[1:])) print(rec_int(list))
Enter a list of single digit integers, or -1 to quit and proceed to conversion