Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Functions: Recursion
#1
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-pa...-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
Reply
#2
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.
Reply
#3
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
Yoriz write Sep-10-2021, 03:36 PM:
This looks like a homework thread, please be aware of Homework and No Effort Questions
Reply
#4
(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
Reply
#5
(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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020