【问题标题】:Formula to Generate List of Specific Numbers生成特定数字列表的公式
【发布时间】:2013-04-28 23:20:21
【问题描述】:

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

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

【问题讨论】:

  • 这里有很多问题,但对于初学者来说,将你的 return 语句移到 while 循环之外。

标签: python list loops sequence fibonacci


【解决方案1】:

我会使用生成器:

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。或者,您可以传入一个数字作为您想要的最大数字,并且只循环适当的次数。


要创建一个通用的递归关系函数,我会这样做:

def recurrence_relation(seed,func):
    seed = list(seed)
    que = deque(seed,len(seed))
    for x in seed:
        yield seed
    while True:
        out = func(que)
        yield out
        queue.append(out)

要使用它来解决您的问题,它看起来像:

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

我认为这结合了 Blender 提出的很好的“播种”能力和一个非常普遍可扩展的形式,使用 deque 允许正如我最初提出的那样。

【讨论】:

    【解决方案2】:

    我会使用生成器:

    def sequence(start):
        a, b, c = start
    
        yield a
        yield b
    
        while True:
            yield c
            a, b, c = b, c, a + b
    

    由于生成器将永远运行,您将不得不以某种方式停止它:

    for i, n in enumerate(sequence([1, 1, 1])):
        if i > 100:
            break
    
        print n
    

    或者itertools:

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

    【讨论】:

    • +1 -- 我喜欢这个。巧妙利用拆包。当递归关系中包含更多项目时,它的扩展性不会很好......但我见过的大多数递归关系只需要几个术语。
    • @mgilson:是的,您的双端队列解决方案更加通用。我会将种子放在一个参数中,然后将其放在 yield 中,这样您就可以在匿名函数中定义递归关系。
    • 是的,我就是这么想的。
    • 生成器不会将信息存储在内存中,对吧?所以说我想打印所有完美正方形/立方体或所有偶数的列表。这还有可能吗?
    • @AndrewRyanKaplan:当然,您可以通过 list(islice(sequence([1, 1, 1]), 100)) 将生成器转换为列表。
    【解决方案3】:

    类似这样的:

    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)    
    

    输出:

    [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151]
    

    【讨论】:

    • FWIW,这将在内存中保留一个大小为 n 的列表。 (它还会在您开始使用之前构建整个列表)。
    • @Ashwini Chaudhary:谢谢,太好了。我将尝试这样做,并使用生成器。
    猜你喜欢
    • 2012-08-15
    • 1970-01-01
    • 2012-12-28
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多