简体   繁体   中英

How to write a recursive function that returns a list of numbers that count down from n to 0?

I am having trouble with this seemingly simple function.

def countdown(n: int):
    """
    Write a simple recursive function that returns a list of numbers that count down from n.

    countdown(5) -> [5, 4, 3, 2, 1, 0]
    countdown(8) -> [8, 7, 6, 5, 4, 3, 2, 1, 0]
    countdown(-1) -> []

    :param n: start
    :return: countdown sequence
    """
    print([n])
    if n >= 1:
        countdown(n - 1)

  

My output:

[5]
[4]
[3]
[2]
[1]
[0]
None

Expected output:

[5, 4, 3, 2, 1, 0]

Is there a simple pythonic way to improve my solution, or should I start from scratch?

EDIT: Got it working, using a few bits from the answers below


def countdown(n: int, nums=None):
    """
    Write a simple recursive function that returns a list of numbers that count down from n.

    countdown(5) -> [5, 4, 3, 2, 1, 0]
    countdown(8) -> [8, 7, 6, 5, 4, 3, 2, 1, 0]
    countdown(-1) -> []

    :param n: start
    :return: countdown sequence
    """
    if nums is None:
        nums = []
    if n >= 0:
        nums.append(n)
        return countdown(n - 1, nums)
    else:
        return nums
def countdown(n:int):
    integers = []
    if n>=1:
        for i in range(n+1):
            integers.append(n-i)
    return integers

countdown(6)

Output: [6, 5, 4, 3, 2, 1, 0]

You are very nearly there. You are getting None because you don't return anything in the function. You can do something like this:

def countdown(n, nums=[]):
    nums = nums.copy()
    if n >= 0:
        nums.append(n)
        return countdown(n-1, nums)
    else:
        return nums

result = countdown(5) 

Which outputs:

[5,4,3,2,1,0]

As the comments noted, recursion is not encouraged here. A simpler alternative is simply just reversing a range, like so:

n=5
result = list(range(0,n+1))[::-1]

OR

n=5
result = list(range(0,n+1))
result.reverse()

Which outputs:

[5,4,3,2,1,0]

Recursive Solution

Given that the brief is

Write a simple recursive function that returns a list of numbers that count down from n.

The most obvious issue with your code is that you're not actually returning anything, you're simply printing each value counting down from n...0 in its own list with each call to countdown() . To remedy this you could use list.append() to add each value n...0 to an empty list passed to countdown() when it is first called.

def countdown(n: int, l: list):
    if n >= 0:
        l.append(n)
        countdown(n - 1, l)
    return(l)

print(countdown(5, []))
print(countdown(8, []))

Output

[5, 4, 3, 2, 1, 0]
[8, 7, 6, 5, 4, 3, 2, 1, 0]

If you absolutely must use recursion to write this function because this is a homework assignment or something similar, then the above solution provides the functionality that you're looking for using recursion.

Non-Recursive Solution

If solutions not using recursion are acceptable - which honestly they should be as this is not a strong practical case for using recursive functions - then the following provides the same output without relying on recursive calls to countdown() .

def countdown(n: int):
    return [i for i in range(n+1)][::-1] if n >= 0 else []

print(countdown(5))
print(countdown(8))

Output

[5, 4, 3, 2, 1, 0]
[8, 7, 6, 5, 4, 3, 2, 1, 0]

This is what I was looking for.

def countdown(n: int, nums=None):

    if nums is None:
        nums = []
    if n >= 0:
        nums.append(n)
        return countdown(n - 1, nums)
    else:
        return nums

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM