-1
num_length = int(input('Enter the length of the sequence:\n'))

nomlist=[]
count = 0
for i in range (num_length):
num = int(input('Enter number '+str(i+1)+ ':\n'))
nomlist.append(num)

this is a part of the solution for my homework, but now I need to rewrite it in a recursive form and I am not sure how I am supposed to change the above code in a recursive function. The above code basically asks the user to input a number and based on that number the program repeatedly asks the user for input and appends it into the list. Please help me.

Neddy
  • 5
  • 4
  • 3
    It is encouraged to show your best try, too. :) – dibery Jun 08 '21 at 08:37
  • 3
    Are you able to write *any* recursive function? Have you studied any examples? If you are "not sure" how to do it, did you *try something*? If not, what exactly are you afraid of? – Karl Knechtel Jun 08 '21 at 08:39

2 Answers2

1
num_length = int(input('Enter the length of the sequence:\n'))

nomlist=[]

def rec(l, count, num_length):
    if count <= 0:
        return
    else:
        num = int(input('Enter number '+str(num_length-count+1)+ ':\n'))
        l.append(num)
        rec(l, count-1, num_length)

rec(nomlist, num_length, num_length)
print(nomlist)
0

Here's a recursive function that makes use of default parameter values and conditional expressions to minimize the amount of code required:

def get_nums(length, numbers=None, entry=1):
    numbers = [] if not numbers else numbers
    numbers.append(input(f'  Enter number {entry}: '))
    return numbers if entry == length else get_nums(length, numbers, entry+1)

length = int(input('Enter the length of the sequence: '))
nomlist = get_nums(length)
print(nomlist)
martineau
  • 119,623
  • 25
  • 170
  • 301