【问题标题】:fibnoacci test case issue- Python斐波那契测试用例问题 - Python
【发布时间】:2020-10-05 02:05:18
【问题描述】:

为了运行,4的测试代码,每个leet代码的答案应该是3。 Per algoexpert.io 显示输出为 2,因为它在测试代码上是正确的。哪一个是正确的?如果是,请解释并修正算法。

n = 4
    
def getNthFib(n):
    lastTwo = [0 , 1]
    counter = 3
    while counter <= n:
        nextFib = lastTwo[0] + lastTwo[1]
        lastTwo[0] = lastTwo[1]
        lastTwo[1] = nextFib
        counter += 1
    return lastTwo[1] if n > 1 else lastTwo[0]


if __name__ == "__main__":
    getNthFib(n)
    print(getNthFib(n))

谢谢

【问题讨论】:

  • 你的问题是“什么是第四个斐波那契数”?为什么不看维基百科?
  • @kaya3 这不是我问的。

标签: python algorithm fibonacci


【解决方案1】:

两者都是正确的。答案取决于序列的开始。如果以0,1开头,则第4项为2,以1,1开头,则第4项为3。

编辑:

我对您的代码做了一些小改动:

def getNthFib(n):
  if n==0: return 0
  lastTwo = [1 , 1]
  counter = 3
  while counter <= n:
    nextFib = lastTwo[0] + lastTwo[1]
    lastTwo[0] = lastTwo[1]
    lastTwo[1] = nextFib
    counter += 1
  return lastTwo[1] if n > 1 else lastTwo[0]

【讨论】:

  • Leet 代码不接受从 1,1 开始的代码,因为他们的测试代码包含 0 并且代码失败。 @Aniket Tiratkar
  • 在这种情况下,序列从0,1,1 开始,它们的索引从0 开始。这与以1,1 开始序列并从1 开始索引相同。唯一的区别是您必须为n=0 添加条件。检查我编辑的答案以获得解决方案。
猜你喜欢
  • 2010-11-24
  • 2014-05-23
  • 2013-02-24
  • 1970-01-01
  • 2013-08-03
  • 2013-02-24
  • 1970-01-01
  • 2011-05-19
  • 2017-11-18
相关资源
最近更新 更多