您可以使用xrange
這一點,沒有一點使用遞歸除非它是一個編碼測試。
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
RESULT2是地方,你在這兒就不得不提到result2.extend(replicate_recur(倍 - 1,數據)) – Kajal
你可以簡單地通過使用result.extend(data * times)來實現這個 – Kajal
我得到了使用遞歸的指令 – Nix