0

I wrote code to write the fibonacci sequence till the elements did not exceed 40. But when I run it, it displays nothing and keeps running forever. Also when I run it, my laptop's temperature rises to 90 degree Celsius and when I stop running it, the temperature falls back to normal. (I have Nitro Sense.)

Here is the code:

    x=0
    while x <= 40:
        m = [1, 2]
        x = m[-1] + m[-2]
        m.append(x)
    print(m)
alani
  • 11,960
  • 2
  • 10
  • 22

5 Answers5

3

You need to declare

m = [1, 2]

outside the loop. Your code adds the calculated x = 1+2 to m - then it resets m = [1,2] so x is calculated as 1+2 again:

x=0
while x <= 40:      # x is 0, then 3 ... again and again
    m = [1, 2]           # m = [1,2] ... again and again
    x = m[-1] + m[-2]    # x = 3     ... again and again     
    m.append(x)          # m = [1,2,3]
print(m)  # never hit

Fix:

x=0
m = [1, 2]
while x <= 40:
    x = m[-1] + m[-2]
    m.append(x)
print(m)

More efficient implementation to get the n-th fibonacci: Efficient Pythonic generator of the Fibonacci sequence

Patrick Artner
  • 48,339
  • 8
  • 43
  • 63
1

You're setting m in the while loop each time. Instead do this.

x=0
m = [1, 2]
while x <= 40:
    x = m[-1] + m[-2]
    m.append(x)
    print(m)
Dominic D
  • 1,780
  • 2
  • 4
  • 12
1

Please move the initialization m = [1, 2] outside the for loop before it.

x=0
m = [1, 2]
while x <= 40:
    x = m[-1] + m[-2]
    m.append(x)
    print(m)
Chintan Rajvir
  • 639
  • 6
  • 18
1

The problem is you are assigning a same value to the variable 'm' every time while loop runs so ,m is never increment and I goes on

To fix it ,remove " m =[1,2]"out of while loop

1

As others have pointed out, your initialisation should be moved to before the loop.

Also if the requirement is only to print the values not exceeding 40, then you need to adjust this slightly in order not to print the value 55 (the first Fibonacci number greater than 40) after it is encountered. Here is an example of how this can be done:

m = [1]
x = 2
while x <= 40:
    m.append(x)
    x = m[-1] + m[-2]
print(m)

This way, each new value is tested before appending it to m if it is not more than 40.

Note: the first two numbers of the Fibonacci sequence are actually defined to be 0 and 1 (it starts 0, 1, 1, 2, ... -- see https://en.wikipedia.org/wiki/Fibonacci_number) so what this code actually produces is a sequence of values from the Fibonacci sequence but missing out its first 2 values.

alani
  • 11,960
  • 2
  • 10
  • 22