Py学习  »  Python

Python:查找给定数字列表中的每个Fibonacci序列

RazorWrecktor • 4 年前 • 627 次点击  

一种程序,它从用户那里获取一个用“,”分隔的数字表,并从中提取和打印出每个斐波那契数列。

In: 5,6,9,3,0,1,1,2,3,8,2,9,3,0,1,1,2,3,5,98
Out: 
[0,1,1,2,3]
[0,1,1,2,3,5]

我试图使用“for”循环来查找第一个0并在它之后处理程序。就像它检查并跟踪fibonacci序列的列表,直到它脱离序列,打印列表,然后查找下一个0。 我写了代码中获取输入的部分,但我不知道如何完成其余部分

numbers = input("Enter your numbers list and use comma to seperate them: ")
numlist = numbers.split(",")
numlist = [int(x) for x in numlist]
result = []

我希望我的解释清楚。有人能帮忙吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53023
 
627 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Vulpex
Reply   •   1 楼
Vulpex    5 年前
FIB = [0,1,1,2,3,5,8,13]

def checkSequence(numArr):
    i = 0
    while i < len(numArr):
        if FIB[i] == int(numArr[i]):
            i += 1
        else:
            return i

numbers = input("Enter your numbers list and use comma to seperate them: ")
numlist = numbers.split(",")
answer = list()
i = 0
while i < len(numlist):
    if int(numlist[i]) == 0:
        ret = checkSequence(numlist[i:])
        answer.append(numlist[i:i+ret])
    i += 1

如您所见,您可以很容易地使用check squence方法检查数组拼接的squence并返回找到的条目数。使用检查序列中的答案,然后可以为您的答案列表创建一个拼接。这将产生您在问题中指定的结果。

mad_
Reply   •   2 楼
mad_    5 年前

Idea与@Vuplex非常相似,但是可以使用os.path.commonprefix删除额外的代码来比较两个系列

import os
numlist = list(map(int,input.split(',')))
answer = []
fib_series = [0,1,1,2,3,5,8,13]
answer = []
i = 0
while i < len(numlist):
    if not numlist[i]:
        answer.append(os.path.commonprefix([fib_series,numlist[i:]]))
    i += 1
print(answer) #[[0, 1, 1, 2, 3], [0, 1, 1, 2, 3, 5]]
Makarand Bauskar
Reply   •   3 楼
Makarand Bauskar    5 年前

下面的程序应该可以工作,它将检查数字列表中的fibbonaci系列

numbers = [5,6,9,3,0,1,1,2,3,8,2,9,3,0,1,1,2,3,5,98]

first = numbers[0]
second = numbers[1]

fibbonacci = []
result = []

for number in numbers[2:]:
    if first + second == number:
        if not fibbonacci:
            fibbonacci.extend([first, second, number])
        else:
            fibbonacci.append(number)
    elif fibbonacci:
        result.append(fibbonacci)
        fibbonacci = []
    first = second
    second = number

print(result)