我对编程比较陌生,我正试图用这个公式生成一个数字列表。在
如果“i”是列表的索引,则公式为list[i]=list[i-2]+list[i-3]。如果从1,1,1开始,前几个数字应该是这样的。在
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37,49,65,86等。要得到每个数字(在1,1,1之后),你可以向后跳一个数字,然后取前两个数字的和,例如49是21和28的和。在
寻找这些数字的过程类似于斐波那契,但这些数字是世界上不同的。在
我的代码如下:
start = [1,1,1] #the list must start with three 1's
list1 = start #list1 starts with 'start'
newList = []
ammountOfNumbers = int(raw_input("Enter the ammount of numbers to be generated(n >= 3): "))# to dictate length of generated list
def generateList(newList, aList, ammountOfNumbers, *a):
while len(aList) <= ammountOfNumbers: #while length of list is less than or = size of list you want generated
for x in range((ammountOfNumbers-1)):
newList.append(x) #this puts value of x in index '0'
newList[x] = aList[len(aList)-1] + aList[len(aList)-2] # generate next number
aList += newList #add the next generated number to the list
x+=1
print
#print "Inside: ", aList #test
#print "Length inside: ",len(aList) #test
print
return aList
final = generateList(newList, list1, ammountOfNumbers) # equal to the value of list1
print"Final List: " , final
print
print"Length Outside: ", len(final) #wrong value
它现在显然不能正常工作。我希望能够生成一个大约500个这样的数字的列表。有人有什么建议吗? 谢谢!在
我会用发电机:
由于发电机将永远运行,因此您必须以某种方式停止它:
^{pr2}$或使用
itertools
:像这样:
输出:
^{pr2}$我会用发电机:
这将根据该递归关系生成一个无限序列。要截断它,我将使用
itertools.islice
。或者,您可以传入一个数字作为您想要的最大数量,并且只循环适当的次数。在要创建一个通用的递归关系函数,我可以做如下操作:
^{pr2}$为了解决您的问题,它看起来像:
我认为这结合了Blender提出的很好的“播种”能力和一个非常普遍的可伸缩形式,使用
deque
可以像我最初建议的那样。在相关问题 更多 >
编程相关推荐