Last active
December 31, 2022 03:45
-
-
Save ayubmetah/73a70790581564cd0fd2de7a2e6afb79 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#using recursion | |
def sum_positive_numbers(n): | |
if n <= 1: | |
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 | |
#using normal functions | |
def sum_positive_numbers(n): | |
sums = 0 | |
for v in range(1,n+1): | |
sums += v | |
return sums | |
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 1
return n + sum_positive_numbers(n-1)
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
use this
def sum_positive_numbers(n):
if n < 1:
return 0
else:
return n + sum_positive_numbers(n - 1)
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15