Python递归挑战

编程入门 行业动态 更新时间:2024-10-08 02:18:43
本文介绍了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递归挑战

本文发布于:2023-11-30 18:44:25,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!