Home>

### how to write a python program for the fibonacci sequence

An algorithm that finds the number of terms in the Fibonacci sequence value that exceeds 200 for the first time.

I wanted to create such a program without using modules, but I had a hard time thinking about what approach to write the source code from. I would appreciate it if you could tell me the idea and an actual program example.

• Answer # 1

Is it because the Fibonacci sequence is often used in the explanation of recursive functions and is often represented by recursive functions as a means of implementation?

As you can see in the question column, you can do it in a loop without much pain, but for the time being, just a hint

Somehow I'll keep the last two values. Tuples, a and b, the last two in the list, and so on.

Add the last two to generate a new value.

Update the two numbers you are holding

It's like that. However, if it is left as it is, it will be calculated infinitely, so it is necessary to put in a mechanism to end it somewhere.

• Answer # 2

``````>>>fibo = (0,1)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(1, 1)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(1, 2)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(twenty three)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(3, 5)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(5, 8)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(8, 13)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(13, 21)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(21, 34)
>>>fibo = (fibo , fibo  + fibo );print (fibo)
(34, 55)
...``````

... So, repeat until fibo  exceeds 200.

[Addition] There was no need to use tuple (although it is tuple internally)

``````>>>f0, f1 = 0,1
>>>f0, f1 = f1, f0 + f1;print (f0)
1
>>>f0, f1 = f1, f0 + f1;print (f0)
1
>>>f0, f1 = f1, f0 + f1;print (f0)
2
>>>f0, f1 = f1, f0 + f1;print (f0)
3
>>>f0, f1 = f1, f0 + f1;print (f0)
Five
>>>f0, f1 = f1, f0 + f1;print (f0)
8
>>>f0, f1 = f1, f0 + f1;print (f0)
13
>>>f0, f1 = f1, f0 + f1;print (f0)
twenty one
>>>f0, f1 = f1, f0 + f1;print (f0)
34``````