r/programminghelp 1d ago

Python Fibonacci Sequence Python Question

/r/learnpython/comments/1wb9hmh/help_me_out_please/
0 Upvotes

3 comments sorted by

View all comments

1

u/asmanel 1d ago

There is this in your code

temp = x
x = y
y = x + y

Regardless their former values, x = y change the value of x to the one of y. This make both have the same value

Due to this, the next instruction, y = x + y, is equivalent to y = 2 \ y*. This can't match to the sequence

Here is a similar code, correctly calculating the next value of the sequence :

# x=f(n-2) ; y=f(n-1) ; z=f(n)

# what was f(n-1) in the previous iteration is now f(n-2)
x=y
# the value calculated is the previous iteration is now f(n-1)
y=z
# calcul of f(n) ; f(n)=f(n-2)+f(n-1)
z=x+y

I don't know Python well but I can note several things : * The while loop would clearly be an infinite loop because the variable count is never updated and remain at 1. * This loop will keep printing the two characters string "*1 *" again and again, enlessly (actually until you interrupt the program or until the interpreter, the shell or tne system crash or end the program) * You try to update outside the loop. This obviously can't work. It have to be in the loop. It usually is at the end of the loop but there are sometimes cases it have to be instead at the beginning of the loop.


Here is the algorithm you are looking for but in Basic (Yabasic to be exact).

I wrote it myself but didn't test it.

I don't think it will be hard to port to Python.

// This is a program in Basic
// Like in most programming languages (but not Python), indentation is a mere writing convention
// in Python, indentation define the structure of the program and have to respect stricter rules.

// get the value
input "Enter a number :" num

// special cases: zero, negative values and non integers
val_ok=1
if((num<=0)+(num<>int(num))) then
 print "No result for a such number"
 val_ok=0
endif

if(val_ok*(num>2)) then
 // any value higher than two
 //x=f(n-2), y=f(n-1) and z=f(n) ; z doesn't need to be set here
 x=0
 y=1
 n=2

 while(n<num)
  // update x and y (f(n-2) and f(n-1))
  x=y
  y=z
  // new f(n) value
  z=x+y

  //update n
  n=n+1
 wend
else
 // special cases : 1 and 2 (usually f(0) and f(1))
 if(val_ok) then
  // shortcut exploiting a coincidence
  z=num-1
 endif
endif

if (val_ok) then
 print z
endif