斐波那契测试用例问题- Python

fibnoacci test case issue- Python

对于运行,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))

谢谢

两者都是正确的。答案取决于序列的开始。如果以 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]