pythonrecursionfunctional-programming

Python recursion challenge


I am currently in an introduction 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 arbitrary values together. Each value to be added must be written as a separate call. 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. It's the only problem I couldn't get on the test!


Solution

  • Try this:

    def multiadder(n):
      assert n > 0
      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