Adamso
Adamso

Reputation: 107

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: The function

I can't use loops at all, only recursion.

I started by writing two recursive functions for sum and factorial but when I tried to combine the two of them I got the error message:

TypeError: 'int' object is not iterable

I don't quite understand what it means because I didn't use loops, only recursion. Here is my code:

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


def factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1)


def exp_n_x(n, x):
    if n == 0:
        return 1
    else:
        return sum_exp(x*(1/factorial(n)))
print(exp_n_x(10, 10))

I would love to get some help with this. Thanks a lot in advance.

Upvotes: 1

Views: 2776

Answers (1)

zmo
zmo

Reputation: 24812

you've made a typo in:

def sum_exp(n):
    if n == 0:
        return 0
    return 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' object is not iterable

whereas

>>> sum([42])
42

so your fix is straightforward:

def sum_exp(n):
    if n == 0:
        return 0
    return 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.

Upvotes: 2

Related Questions