验证数字列表是否是斐波那契数列的一部分

Verify whether s list of number is part of the fibonacci series

我制作了一个将列表作为输入的函数,returns 也是一个列表。

例如输入是 [4,6,8,10,12] 输出应该是 [0,0,1,0,0]

因为 8 属于斐波那契数列

我的密码是

for i in input1:
    phi=0.5+0.5*math.sqrt(5.0)
    a=phi*i
    out =[ i == 0 or abs(round(a) - a) < 1.0 / i];
    return out;

我认为最好的方法可能是编写一个名为 is_fibonacci 的函数,它接受一个数字输入和 returns True 如果输入是斐波那契数,否则 False。然后你可以在你的初始列表 input1: return [1 if is_fibonacci(num) else 0 for num in input1] 上做一个列表理解。 (当然,is_fibonacci 可以自动 return 10 而不是布尔值,在这种情况下列表理解甚至更简单。)

编写 is_fibonacci 函数是一个有趣的练习,我将留给您 :)(但如果您遇到困难,我很乐意提供帮助。)

这会起作用:

input1 = [4,6,8,10,12]
out=[]
for i in input1:
    phi=0.5+0.5*math.sqrt(5.0)
    a=phi*i
    out.append(i == 0 or abs(round(a) - a) < 1.0 / i);

将 bool 转换为 int

import numpy
y=numpy.array(out)
new_output = y*1

我想这应该可以解决

import math


# A function that returns true if x is perfect square
def isPerfectSquare(x):
    s = int(math.sqrt(x))
    return s * s == x


# Returns true if n is a Fibinacci Number, else false

def isFibonacci(n):
    return isPerfectSquare(5 * n * n + 4) or isPerfectSquare(5 * n * n - 4)


i = [4, 6, 8, 10, 12]
print(i)
j = []
# A utility function to test above functions
for item in i:
    if (isFibonacci(item) == True):
        j.append(1)

    else:
        j.append(0)
print(j)

输出:

[4, 6, 8, 10, 12] 
[0, 0, 1, 0, 0]

这就是你想要的

def isFibonaccy(inputList):
    out = []
    for i in inputList:
        phi = 0.5 + 0.5 * math.sqrt(5.0)
        a = phi * i
        out.append(int(i == 0 or abs(round(a) - a) < 1.0 / i))

    return out

print(isFibonaccy([4, 6, 8, 10, 12])) # -> [0, 0, 1, 0, 0]