Recursion – Python question, return value question

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
Asked By: Takomochi

||

Answers:

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)
Answered By: E. Mancebo
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

Answered By: JQTs

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

Answered By: Anshu Kumar Ranjan

My best suggestion

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

    return n + sum_positive_numbers(n-1)

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15
Answered By: Gokma
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
Answered By: Marwan M. Mekhamer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.