1

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.

3
  • I wasn't able to reproduce your error, however you might want to modify your return statement for the else case in the exp_n_x function. Namely, when you divide to integers the result gets truncated... You can fix this by changing (1/factorial(n)) to (1.0/factorial(n)). Commented Dec 24, 2016 at 11:19
  • 1
    Your sum_exp function isn't recursive. It calls sum, not itself. Commented Dec 24, 2016 at 11:20
  • 1
    Your problem can be reduced to sum(0). Same error. Commented Dec 24, 2016 at 11:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.