Python 范围函数本身
Python range function in terms of itself
我正在尝试递归地编写 python 函数 range 而不是实际使用 range 函数,所以如果我有一个函数 Range(lo,hi),Range (3,7) 将 return [3,4,5,6]
我目前拥有的:
def Range(lo,hi):
if hi <= lo:
return []
else:
return Range(lo - 1) + ([hi - 1,])
我知道这是完全错误的,但我也有:
def Range2(lo,hi):
if hi <=lo :
return []
else:
return [Range(lo,hi-1)]
试试这个:
def Range(lo,hi):
if hi <= lo:
return []
return [lo] + Range(lo + 1,hi)
您忘记将递归的当前 lo
编号添加到列表中
在您的第一次尝试中,您忘记将 两个 参数传递给递归调用。此外,您不需要在 hi - 1
之后使用逗号,也不需要在列表周围使用括号。
在第二次尝试中,您忘记将 hi - 1
附加到递归调用返回的列表中。
def Range(lo,hi):
if hi <= lo:
return []
else:
return Range(lo, hi - 1) + [hi - 1]
嗨!
有趣的问题!我想到了两个解决方案:
def myRange1(start, stop, step=1, ans=None):
assert step >= 0;
ans = ans or [];
if (start >= stop):
return ans;
# Otherwise...
ans.append(start);
return myRange1(start + step, stop, step, ans);
def myRange2(start, stop, step=1):
assert step >= 0;
if (start >= stop):
return [];
# Otherwise...
return [start] + myRange2(start + step, stop, step);
在类似 Lisp 的术语中,myRange1
是迭代的,而 myRange2
是递归的。
当然,每个函数都会调用自己,从这个意义上讲,它是递归的。
希望对您有所帮助。
我正在尝试递归地编写 python 函数 range 而不是实际使用 range 函数,所以如果我有一个函数 Range(lo,hi),Range (3,7) 将 return [3,4,5,6]
我目前拥有的:
def Range(lo,hi):
if hi <= lo:
return []
else:
return Range(lo - 1) + ([hi - 1,])
我知道这是完全错误的,但我也有:
def Range2(lo,hi):
if hi <=lo :
return []
else:
return [Range(lo,hi-1)]
试试这个:
def Range(lo,hi):
if hi <= lo:
return []
return [lo] + Range(lo + 1,hi)
您忘记将递归的当前 lo
编号添加到列表中
在您的第一次尝试中,您忘记将 两个 参数传递给递归调用。此外,您不需要在 hi - 1
之后使用逗号,也不需要在列表周围使用括号。
在第二次尝试中,您忘记将 hi - 1
附加到递归调用返回的列表中。
def Range(lo,hi):
if hi <= lo:
return []
else:
return Range(lo, hi - 1) + [hi - 1]
嗨!
有趣的问题!我想到了两个解决方案:
def myRange1(start, stop, step=1, ans=None):
assert step >= 0;
ans = ans or [];
if (start >= stop):
return ans;
# Otherwise...
ans.append(start);
return myRange1(start + step, stop, step, ans);
def myRange2(start, stop, step=1):
assert step >= 0;
if (start >= stop):
return [];
# Otherwise...
return [start] + myRange2(start + step, stop, step);
在类似 Lisp 的术语中,myRange1
是迭代的,而 myRange2
是递归的。
当然,每个函数都会调用自己,从这个意义上讲,它是递归的。
希望对您有所帮助。