CoCalc Public Filesprojects_F20 / rec_Proj6 / recursion.ipynb
Author: Julia Burnside
Views : 30
Compute Environment: Ubuntu 20.04 (Default)

## Recursive Conversion from List to Integers

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

The function $rec\_int$ takes a single parameter, $list$. First, the function evaluates the length of $list$. If the length is $1$, meaning there is only a single value in the array, then the function returns that value at $list[0]$. Otherwise, the function will take the value at $list[0]$ and multiply it by $10$ to the power of the length of the array, minus $1$. So, for example, if the array is of length $3$ and the first value is $2$, this process will yield $2*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:]$. This precludes the first value of the array and also appends the length of $list$. The function will continue to iterate through this process until the length of $list=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