【问题标题】:Verify whether s list of number is part of the fibonacci series验证 s 数字列表是否是斐波那契数列的一部分
【发布时间】:2019-02-23 12:38:06
【问题描述】:

我已经做了一个函数,它接受一个列表作为输入并返回一个列表。

例如输入是[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;

【问题讨论】:

  • 您到底面临什么问题?
  • 行尾不需要分号。
  • 我有一个函数,它将输入作为数字列表并且应该返回输出也是列表,input1=[4,6,8,10,12] 它应该返回 [0,0 ,1,0,0] 因为 8 属于 fib 系列,其余不属于
  • 这里是你的代码的一个工作更短的版本:phi=0.5+0.5*math.sqrt(5.0) 然后out = [1 if abs(round(phi*i) - phi*i) &lt; (1/i) else 0 for i in input1] 使用列表理解。我将a 替换为phi*i。如果有不清楚的地方,请随时询问
  • 只返回 0 0 0 0 0

标签: python list function fibonacci


【解决方案1】:

这将起作用:

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

【讨论】:

  • 打印出来并将其与 OP 所需的输出进行比较。你得到相同格式的输出吗?我没有
  • 你能不能为了 OP 把它设为 0 和 1
  • @MahinMalhotra:在上面的 cmets 中尝试我的答案
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    我猜这应该可以解决

    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]
    

    【讨论】:

      【解决方案4】:

      这就是你想要的

      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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 2015-06-05
        • 2011-01-26
        • 2017-07-08
        • 2020-01-18
        相关资源
        最近更新 更多