python - 带数学运算符的递归函数

标签 python python-3.x

我想构建一个函数,它接受两个自然数 n 和 m,并返回以 n 开头并以 m-1 结尾的所有自然数的平方元组。如果 m 小于 n,我可以决定函数是否应该返回,但它不应该崩溃或返回某种错误消息。所以 squares_tuple(3,7) 返回 (9,16,25,36) 而 rec_range(10,11) 返回 (100,)。另外,我不想使用 range()、map()、循环或列表。这是我目前所拥有的:

def squares_tuple(n,m):
"""takes two nat nums n and m and returns a tuple of the squares of all the
natural numbers starting with n and ending with m-1

nat, nat -> tuple of natural numbers"""
   if m >= 0:
       return 0
   else:
       return squares_tuple(n - 1, ) + (n**m, )

此时有点卡住...

最佳答案

def squares_tuple(n, m):
    return (n * n, ) + squares_tuple(n + 1, m) if n < m else ()

例子:

>>> squares_tuple(0, 6)
(0, 1, 4, 9, 16, 25)
>>> squares_tuple(3, 7)
(9, 16, 25, 36)

关于python - 带数学运算符的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265845/

相关文章:

python - 开发期间的 GTK 命名图标 : Load while running from source,

string - Python3 - "a bytes-like object is required, not ' str '"on object of type <class ' 字节'>

python-3.x - 如何用新的附加图片训练面部识别器?

如果两个列表中满足条件,python将跳过循环中的下一个索引

使用数学运算符的 Python For 循环

python - 来自 Python 服务的警报弹出窗口

python-3.x - cv2。错误:C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:325:错误:(-215)size.width> 0 && size.height> 0在函数cv::imshow中

python-3.x - Graph Factory 找不到 gremlin.graph 属性配置

python - 有没有办法从终端关闭使用 matplotlib 创建的绘图(无需用鼠标关闭窗口)

java - 如何将Apach AVRO IDL编译成java?