简体   繁体   中英

Recursion - Python question, return value question

**I am having a problem with solving the question below.

Implement the sum_positive_numbers function, as a recursive function that returns the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15.**

def sum_positive_numbers(n):
    return 0

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

Remember always to add a breaking condition. The zero evaluation in this case

def sum_positive_numbers(n):
    if n == 0:
        return n
    return n + sum_positive_numbers(n - 1)
def sum_positive_numbers(n):
    # The base case is n being smaller than 1
    if n < 1:
        return n


    return n + sum_positive_numbers(n - 1)
    # What got me was n - 1. I was using + until I went to the below website to see visualize it

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

This is the website I use to visualize code that helps me solve the problem(s). It forces me not to just get an answer from google search, but work through each error, and learn as I go: Python Visualizer

def sum_positive_numbers(n):

if n == 0:
    return n
return n + sum_positive_numbers(n - 1)

print(sum_positive_numbers(3)) # Should be 6

print(sum_positive_numbers(5)) # Should be 15

def sum_positive_numbers(n):
    if n < 1:
        return 0

    return n + sum_positive_numbers(n - 1)

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