Will Wang Will Wang - 2 months ago 10
Python Question

Python Recursion Challenge

I am currently in an intro to python and computational theory class, and there was recently a difficult question on the midterm that I simply was not able to solve. It involves writing code for a program that adds numbers. I believe the question is supposed to use recursion. I don't remember how exactly the question was worded but here is the basic idea.

Implement the

multiadder(n)
function, which takes in a nonnegative integer
n
and adds
n
integers together. Each integer to be added must be written as a separate parameter. For example:

>>> multi_three = multiadder(3)
>>> multi_three(1)(2)(3)
6

>>> multiadder(5)(1)(2)(3)(4)(5)
15


The code must be written by filling in the blanks.

def multiadder(n):
assert n > 0
if _________________________ :
return _________________________
else:
return _________________________


The topics we have covered in class are higher order functions, recursion, lambdas, and control statements. We are not allowed to use data structure like lists and sets, nor are we allowed to import anything.

Someone please help. Its the only problem I couldn't get on the test!

Answer

Try this:

def multiadder(n):
  if n <= 1:
    return lambda t: t
  else:
    return lambda a: lambda b: multiadder(n-1)(a+b)

if __name__ == '__main__':
  print(multiadder(5)(1)(2)(3)(4)(5))

For n == 1, the result must be a function returning the input.

For n > 1, wrap the result of n-1, by adding input.

This also works for concatenating strings, and other accumulating operations:

>>> multiadder(3)('p')('q')('r')
pqr
Comments