【问题标题】:Why does my python Fibonacci Sequence algorithm not run properly?为什么我的 python 斐波那契数列算法无法正常运行?
【发布时间】:2021-11-20 11:04:18
【问题描述】:

编写一个程序,打印从序列的第 5 个到第 15 个元素的斐波那契数列。 我应该如何从第 5 个开始,即“3”?这是我的代码

def fibonacci_nums(n):
    if n <= 0:
        return [0]
    sequence = [0, 1]
    while len(sequence) <= n:
        next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
        sequence.append(next_value)
      

return sequence

print("First 15 Fibonacci numbers:")
print(fibonacci_nums(15))

【问题讨论】:

  • 选择不同的开始顺序怎么样? sequence = [2, 3]
  • 斐波那契数列的第五个元素不是3,尤其不是'3'
  • 哦,原来如此 -> 返回序列[4:]
  • @KlausD。这取决于您是否考虑fib(0)=0fib(0)=1 这不是一个长远的假设,如果您对此有特别强烈的看法,它可能属于这里:stackoverflow.com/questions/1451170/…
  • @j__carlson 虽然您可以对其进行修改并对斐波那契数列进行理论化,但我认为如果这个自然生长的示例从 0 对兔子开始,它永远不会出现在任何数学书籍中。

标签: python python-3.x python-2.7


【解决方案1】:
def fibonacci_nums(n):
  if n <= 0:
    return [0]
  sequence = [0, 1]
  while len(sequence) <= n:
    next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
    sequence.append(next_value)
  return sequence[4:]
print("Fibonacci numbers from 5th to 15th number:")
print(fibonacci_nums(14))

【讨论】:

    【解决方案2】:

    这是你需要的吗:

    def fibonacci_nums(n):
      if n <= 0:
        return [0]
      sequence = [0, 1]
      while len(sequence) <= n:
        next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
        sequence.append(next_value)
      return sequence
    print("First 15 Fibonacci numbers:")
    print(fibonacci_nums(15)[4:])    # Print elements from 4th index
    

    输出:

    First 15 Fibonacci numbers:
    [3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
    

    【讨论】:

      【解决方案3】:

      试试这个:

      def fibonacci_nums(n, k):
          fib=[0,1]
          for f in range(k-1):
              fib.append(fib[f]+fib[f+1])
          return fib[n-1:k]
      
      fibonacci_nums(5, 15)
      

      输出:

      [3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-18
        • 2010-11-26
        • 2013-04-29
        • 2012-12-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-28
        • 1970-01-01
        相关资源
        最近更新 更多