'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
Solution 1:[1]
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)
Solution 2:[2]
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
Solution 3:[3]
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
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | E. Mancebo |
Solution 2 | Muhammad Dyas Yaskur |
Solution 3 | |
Solution 4 | Anshu Kumar Ranjan |