Python递归挑战 [英] Python recursion challenge

查看:114
本文介绍了Python递归挑战的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在对Python和计算理论课进行介绍,最近有一个中期问题难以解决,我根本无法解决。它涉及为添加数字的程序编写代码。我相信这个问题应该使用递归。我不记得问题的具体含义,但这里有一个基本的想法。



执行 multiadder(n)函数,该函数接受一个非负整数 n 并将 n 任意值加在一起。每个要添加的值都必须作为单独的调用写入。例如:

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

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





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

我们在课上讨论的主题是高阶函数,递归,lambdas和控制语句。我们不允许使用列表和集合等数据结构,也不允许导入任何内容。



有人请帮忙。

解决方案

试试这个:


$这是我无法测试的唯一问题! b $ b

  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))

对于 n == 1 ,结果必须是一个返回输入的函数。 p>

对于 n> 1 ,通过添加输入来包装 n-1 的结果。





 >>>也可以连接字符串和其他累积操作。 multiadder(3)('p')('q')('r')
pqr


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!

解决方案

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

这篇关于Python递归挑战的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆