[Python] How to fix the fibonacci code without using recursion? [closed]

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to understand how to write the Fibonacci sequence.

    def fibonacci(n):
    if not isinstance(n, int):
    return None
    if n < 0:
    return None

    if n == 0:#F_0
    return 0
    elif n == 1 or n == 2: #F_1 and F_2
    return 1

    a, b = 1, 1 #F_3
    for i in range(3,n + 1):
    a, b = a + b, a
    return a


    Basically, if I calculate it by hand, I get the correct values, but the unit test gives an error.

    #Test

    import unittest

    class Test(unittest.TestCase):

    def test(self):
    self.assertEqual(fibonacci(1), 1, "Program is calculating the wrong value!")
    self.assertEqual(fibonacci(2), 1, "Program is calculating the wrong value!")
    self.assertEqual(fibonacci(3), 2, "Program is calculating the wrong value!")
    self.assertEqual(fibonacci(4), 3, "Program is calculating the wrong value!")
    self.assertEqual(fibonacci(5), 5, "Program is calculating the wrong value!")

    def test_errors(self):
    self.assertEqual(fibonacci(-1), None, "Program is calculating the wrong value!")
    self.assertEqual(fibonacci(-1.0), None, "Program is calculating the wrong value!")
    self.assertEqual(fibonacci(1.0), None, "Program is calculating the wrong value!")
    self.assertEqual(fibonacci("Hallo"), None, "Program is calculating the wrong value!")


    if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)


    For example, a, b = 1, 1, which I think should be correct, gives the error:

    self.assertEqual(fibonacci(4), 3, "Program is calculating the wrong value!")
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    AssertionError: 2 != 3 : Program is calculating the wrong value!

    and a, b = 1, 0 self.assertEqual(fibonacci(3), 2, "Program is calculating the wrong value!")
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    AssertionError: 1 != 2 : Program is calculating the wrong value!

    Continue reading...

Compartilhe esta Página