嵌套循环斐波那契数列

时间:2018-09-28 17:18:36

标签: python nested-loops

我正在尝试编写一个程序,要求用户输入数字。然后,我需要验证它是否处于fib序列中

代码:

# asking the user to input number
number = int(input("Enter a number: "))

# creating empty list to be filled
sequence = [0, 1]

x = -2
y = -1


# append items to list
for i in range(number):
    x+=2
    y+=2
# this code will be executed 'length' times
    sequence.append(x+y)

# This should be somewhere in the loop: 
if number in sequence:
    print("The number is in the Fibonacci sequence")
else:
    print("The number is not in the Fibonacci sequence")

预期输出:

斐波那契数列= 0、1、1、2、3、5、8、13、21、34,...。

Enter a number: 5
>>> The number is in the Fibonacci sequence

5 个答案:

答案 0 :(得分:1)

您将需要进行一些迭代(或递归)才能找到斐波那契数列。这是使用while循环的一种方法:

number = int(input("Enter a number: "))

sequence = [0, 1]

i= 0
while True:
    new_item = sequence[i] + sequence[i+1]
    if new_item == number or number in [0,1]:
        print("The number is in the Fibonacci sequence")
        break
    elif new_item > number:
        print("The number is not in the Fibonacci sequence")
        break
    sequence.append(new_item)
    i+=1

请注意,您将迭代直到斐波那契数列中的新项目大于或等于用户输入的数字为止。

答案 1 :(得分:0)

序列没有位置x或y。附加到序列的行应显示为sequence.append(x+y)

答案 2 :(得分:0)

也许我在想这个太简单了,但是根据您的问题,这听起来像是向您提供了斐波那契数列。如果是这种情况,您可以只使用in,即

x = 5 # this will be user's input
fib = [0,1,1,2,3,5,8,13,21,34]
if x in fib:
    print('Number is in sequence')
else:
    print('Number is not in sequence')

如果必须生成自己的斐波那契数列,那么您可能需要考虑使用递归。

答案 3 :(得分:0)

或者,您可以只计算斐波那奇数词

def fibo(n):
    p = (1+5**.5)/2
    q = (1-5**.5)/2
    return int(1/5**.5*(p**n-q**n))

def fiba(num):
     count = 0
     while fibo(count) <= num:
             if fibo(count) == num:
                     return "YES!"
             count += 1
     return "NO!"

答案 4 :(得分:0)

一种方法是将fibonacci分解为一个生成器,然后对该生成器进行迭代,直到>= number,例如:

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a+b

In []    
number = 5 # int(input("Enter a number: "))

for f in fib():
    if f >= number:
        break

if number == f:
    print("The number is in the Fibonacci sequence")
else:
    print("The number is not in the Fibonacci sequence")

Out[]:
The number is in the Fibonacci sequence

您可以使用itertools.takewhile替换for循环,例如:

import itertools as it
from collections import deque

f = deque(it.takewhile(lambda n: n <= number, fib()), maxlen=1).pop()

...