[英]Why is my python function returning multiple brackets?
I'm somewhat of a noob to python but I'm trying to create a recursive function which works just like the built in range function: 我对python有点陌生,但我试图创建一个与内置范围函数一样工作的递归函数:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo, Range (lo+1,hi)]
but its returning multiple lists. 但返回多个列表。
Instead of [3,4,5,6]
, which is what I want, its returning [3,[4,[5,[6,[]]]]]
Why is this and how do I fix it? 而不是我想要的
[3,4,5,6]
,而是返回的[3,[4,[5,[6,[]]]]]
这是为什么,我该如何解决?
When you recurse like that, Range
returns a list each time: 像这样递归时,
Range
每次都会返回一个列表:
Range(3,7)
# translates to
[3, Range(4,7)]
# which translates to
[3, [4, Range(5,7)]]
# etc.
In order to avoid this, add your lists together: 为了避免这种情况,请将您的列表一起添加:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo] + Range(lo+1, hi)
EDIT: 编辑:
As @delnan points out, this function is very inefficient - it both recurses in a language without tail-call optimization * and it generates two (possibly three ) new lists for each level of recursion. 作为@delnan指出,这个功能是非常低效的-它没有尾巴调用优化*语言都递归和它的递归的每一层产生两个(可能是三个 )新的列表。 @mipadi's answer is more performant because it creates only one list (the
acc
or accumulator
argument) and passes it as it recurses. @mipadi的答案更高效,因为它仅创建一个列表(
acc
或accumulator
参数)并在递归时将其传递。
* This may not be true for the Python language, but I'm 99% sure it is true for the most common implementation of Python, namely CPython. *这可能不适用于Python语言,但我99%的肯定适用于最常见的Python实现,即CPython。
Your Range
function returns a list, so in your last line you are returning a list within a list. 您的
Range
函数将返回一个列表,因此在最后一行中,您将返回列表中的一个列表。 What you probably should do is maintain an accumulator and add values to that: 您可能应该做的是维护一个累加器并为其添加值:
def Range(lo, hi, acc=None):
if acc is None:
acc = []
if lo >= hi:
return acc
else:
acc.append(lo)
return Range(lo+1, hi, acc)
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo] + Range (lo+1, hi)
but you might get StackOverflow 但是你可能会得到StackOverflow
Each recursion into Range returns a list, which is the second element in the list for the previous recursion. 每次递归到Range都会返回一个列表,该列表是上一个递归的列表中的第二个元素。 Of course Python has a built-in function for this , but if you want to build it yourself, you probably just want to end with
当然, Python为此提供了一个内置函数 ,但是如果您想自己构建它,则可能只想以
return [lo] + Range(lo+1, hi)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.