Skip to content Skip to sidebar Skip to footer

Exponential Sum Using Recursion.python

I need to write a function using recursion that accepts the following variables: n: int x: real and returns the exponential sum function: I can't use loops at all, only recursion

Solution 1:

you've made a typo in:

defsum_exp(n):
    if n == 0:
        return0return n + sum(n - 1)
               ^^^

where you use the global function sum() which takes an iterable and returns the sum of its elements. Thus:

>>> sum(42)
TypeError: 'int'objectisnot iterable

whereas

>>>sum([42])
42

so your fix is straightforward:

def sum_exp(n):
    if n == 0:
        return0return n + sum_exp(n - 1)

N.B.: This answer is only meant to fix your issue with the TypeError, and get you going to the next error you'll hit, which is an infinite recursion. As an advice you should double check your stop condition and recursion step.

Post a Comment for "Exponential Sum Using Recursion.python"