[英]recursive functions returning tuples python
I want to build a RECURSIVE function that takes a natural number n and returns a tuple of numbers starting with 0 and ending before n. 我想构建一个RECURSIVE函数,该函数采用自然数n并返回以0开头并在n之前结束的数字元组。 So rec_range(5) returns (0,1,2,3,4) and rec_range(1) returns (0, ). 因此rec_range(5)返回(0,1,2,3,4),rec_range(1)返回(0,)。
This is what I have so far: 这是我到目前为止的内容:
def rec_range(n):
"""returns a tuple of numbers starting with 0 and ending before n
natural number -> tuple of numbers"""
if n = 0:
return 0
else:
return rec_range(0, n)
I'm not sure what to do next. 我不确定下一步该怎么做。 Also, it should be noticed that I could not test this function because there was an invalid syntax error. 另外,应该注意,由于存在无效的语法错误,我无法测试此功能。
In python you can concatenate tuples with +
. 在python中,您可以用+
连接元组。
def rec_range(n):
if n == 0:
return (0,)
else:
return rec_range(n - 1) + (n,)
Define rec_range(n) as returning a tuple of counts < n, in increasing order. 将rec_range(n)定义为以递增顺序返回计数<n的元组。 This mimics the set theory definition of the natural numbers. 这模仿了自然数的集合论定义。 Unless an instructor mandates differently, rec_range(0) should (logically) be an empty tuple (). 除非讲师的命令有所不同,否则rec_range(0)(在逻辑上)应为空元组()。
Repeated concatention of tuples turns what should be an O(n) function (appending to a list) into an O(n*n) function. 元组的重复并置会使应为O(n)的函数(附加到列表)变成O(n * n)的函数。 If a tuple rather than list is required, the conversion to tuple can be the last step. 如果需要元组而不是列表,则转换为元组可以是最后一步。 Here is an O(n) tail_recursive solution. 这是O(n)tail_recursive解。
def rec_range(n, answer=None):
if answer is None:
answer = []
if n > 0:
n -= 1
answer.append(n)
return rec_range(n, answer)
else:
return tuple(reversed(answer))
print(rec_range(0), rec_range(1), rec_range(10))
#() (0,) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.