Python Forum
Functions: Recursion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Functions: Recursion (/thread-34878.html)



Functions: Recursion - OmegaRed94 - Sep-10-2021

Good day, Dear Pythonistas
I have the following problem:

Write a function sequence(n) that will print out a sequence of numbers without using a for / while loop. If the number n is given, print the next sequence of numbers without using a loop. We decrease the number n by 5 until we reach a negative number or 0.

Examples:
sequence(16)
[16, 11, 6, 1, -4]
sequence(10)
[10, 5, 0]

I tried to use an empty list and method "append" inside of a recursive function, but it doesn't work. I had a look at the following similar problem: https://www.geeksforgeeks.org/print-a-pattern-without-using-any-loop/, but it only works if we use print(). Could you help me?

My code is:
def sequence(n):
    empty_list=[]
    if (n == 0 or n < 0):
        #print(n)
        empty_list.append(n)
        return 
    else:
        empty_list.append(n)
        #print(n,end=", ")
        sequence(n-5)
    return empty_list



RE: Functions: Recursion - deanhystad - Sep-10-2021

The instructions say print. Why are you using a list?

Your recursive function creates a list each time it is called. You append one value and return the list. The return value is not used. See the problem? You never grow the list because each time the function is called you make a new list. You need to make one list that is used for all function calls.


RE: Functions: Recursion - naughtyCat - Sep-10-2021

def sequence(n: int):
    print(n)
    if n <= 0: return
    sequence(n-5)

sequence(16)
Output:
16 11 6 1 -4
OR

def sequence(n: int, arr = None):
    if not arr:
        arr = []
    arr.append(n)
    if n <= 0: return arr
    return sequence(n-5, arr)

print(*sequence(16))
Output:
16 11 6 1 -4



RE: Functions: Recursion - OmegaRed94 - Sep-10-2021

(Sep-10-2021, 12:52 PM)deanhystad Wrote: The instructions say print. Why are you using a list?

Your recursive function creates a list each time it is called. You append one value and return the list. The return value is not used. See the problem? You never grow the list because each time the function is called you make a new list. You need to make one list that is used for all function calls.
Thanks


RE: Functions: Recursion - OmegaRed94 - Sep-10-2021

(Sep-10-2021, 03:18 PM)naughtyCat Wrote:
def sequence(n: int):
    print(n)
    if n <= 0: return
    sequence(n-5)

sequence(16)
Output:
16 11 6 1 -4
OR

def sequence(n: int, arr = None):
    if not arr:
        arr = []
    arr.append(n)
    if n <= 0: return arr
    return sequence(n-5, arr)

print(*sequence(16))
Output:
16 11 6 1 -4

Thank you very much, naughtyCat, I understood my mistake