0

Решаю питон задачку. Условие:

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

Я пробовал решить так:

def sum_positive_numbers(n):
  for i in range(n):
     n += i
  return n
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

Всё решается так, как нужно и вывод тот же.. Но мне выходила ошибка: Here is your output: 6, 15. Not quite. While the result can be achieved without recursion, we want to use recursion for this exercise. Я не понимаю как построить тут рекурсивное решение.

1

3 ответа 3

2

Во-первых, цикл должен стартовать с единицы и заканчиваться n for i in range(1, n):, во-вторых, это совсем не рекурсивное решение

Можно, например, так:

def sum_positive_numbers(n):
   return 1 if n == 1 else n + sum_positive_numbers(n-1) 
1

примерно вот так

def sum_positive_numbers(n):
    if n == 1:
        return 1
    else:
        return sum_positive_numbers(n - 1) + n
0
def sum_positive_numbers(n, s=0):

    if n == 0:

        return s

    s += n

    n -= 1

    return sum_positive_numbers(n, s)

print(sum_positive_numbers(6))
1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.