生成特定数字列表的公式

2024-10-04 09:18:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程比较陌生,我正试图用这个公式生成一个数字列表。在

如果“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个这样的数字的列表。有人有什么建议吗? 谢谢!在


Tags: oftheto列表lenvalue数字start
3条回答

我会用发电机:

def sequence(start):
    a, b, c = start

    yield a
    yield b

    while True:
        yield c
        a, b, c = b, c, a + b

由于发电机将永远运行,因此您必须以某种方式停止它:

^{pr2}$

或使用itertools

from itertools import islice:

for n in islice(sequence([1, 1, 1]), 100):
    print n

像这样:

def solve(n):
    lis=[1,1,1]
    if n<=3:
        return lis[:n]
    while len(lis)!=n:
        lis.append(lis[-2]+lis[-3])
    return lis

print solve(20)    

输出:

^{pr2}$

我会用发电机:

from collections import deque
def generate_list():
    que = deque([1,1,1],3)
    yield 1
    yield 1
    yield 1
    while True:
        out = que[-3]+que[-2]
        yield out
        que.append(out)

这将根据该递归关系生成一个无限序列。要截断它,我将使用itertools.islice。或者,您可以传入一个数字作为您想要的最大数量,并且只循环适当的次数。在


要创建一个通用的递归关系函数,我可以做如下操作:

^{pr2}$

为了解决您的问题,它看起来像:

series = recurrence_relation([1,1,1],lambda x:x[-3] + x[-2])
for item in islice(series,0,500):
    #do something

我认为这结合了Blender提出的很好的“播种”能力和一个非常普遍的可伸缩形式,使用deque可以像我最初建议的那样。在

相关问题 更多 >