def replicate(times, data):
result2 = []
for i in xrange(times):
result2.append(data)
return result2
同样的函数可以用如下递归方式编写:
def replicate_recur(times, data, listTest=None):
# If a list has not been passed as argument create an empty one
if(listTest == None):
listTest = []
# Return the list if we need to replicate 0 more times
if times == 0:
return listTest
# If we reach here at least we have to replicate once
listTest.append(data)
# Recursive call to replicate more times, if needed and return the result
replicate_recur(times-1, data, listTest)
return listTest
def replicate_recur(times, data, result=None):
if result is None: # create a new result if no intermediate was given
result = []
if times == 1:
result.append(data)
else:
result.append(data)
replicate_recur(times - 1, data, result) # also pass in the "result"
return result
您可以使用
xrange
进行此操作,除非是编码测试,否则没有必要使用递归。同样的函数可以用如下递归方式编写:
可以在每个递归调用中使用要附加到的中间列表。这样可以避免当前遇到的这些重新定义问题:
调用时:
要使代码正常工作,您需要在当前执行中使用下一个递归调用的输出
extend
列表。此外,递归的最低深度应该由times = 1
定义:另一方面,您可以简单地复制列表:
相关问题 更多 >
编程相关推荐