0

Hey guys,..someone help with a code that generates a Fibonacci sequence,in Python syntax

Fibonacci sequence

30th Nov 2018, 7:07 AM
David Arumba
David Arumba - avatar
6 Respuestas
+ 3
Oh, you were so close, my friend! Just a small change makes it work: def fib(a,b): for i in range(0,10): print(a) temp = a a = b b = temp + b fib(0,1) The reason your code failed is that when you are doing a=b, the code forgets the previous value of a, and it holds the value of b. Then b = b+a is the same as b=b+b, or b = 2*b. So you're just getting doubles of previous numbers. That's why I stored the old value of a in the "temp" variable and did b = temp + b. A fancier way of doing the same is with tuple unpacking, which looks even closer to your original code: def fib(a,b): for i in range(0,10): print(a) a, b = b, a+b fib(0,1) Let me know if it all makes sense.
30th Nov 2018, 7:46 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
What have you tried so far?
30th Nov 2018, 7:10 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
Davido ArumbaTheemperor , you're welcome! And in future, please always try to post your attempt, no matter how bad it looks to you. We can help you better if we know where you stand. And we usually don't appreciate it if people just want a solution to their homework without even trying anything. Hope you understand. Regarding tuple unpacking, I Googled and found this site: https://treyhunner.com/2018/03/tuple-unpacking-improves-JUMP_LINK__&&__python__&&__JUMP_LINK-code-readability/ I didn't read everything, but just the first part should give you a good idea about why a, b = b, a+b works. If you still have questions, I'd be happy to assist you further! Happy learning! 😊
30th Nov 2018, 8:28 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
Kishalaya Saha I tried writing the following code but seems I'm still poor def fib(a,b): for i in range(0,10): print(a) a=b b=a+b fib(0,1)
30th Nov 2018, 7:05 PM
David Arumba
David Arumba - avatar
+ 1
Kishalaya Saha Thanks for your explanation,your code worked. I have never known if a=b b=a+b is different from a,b=b,a+b Perhaps any site i would read about tuple unpacking?
30th Nov 2018, 7:57 PM
David Arumba
David Arumba - avatar
+ 1
Kishalaya Saha Thank you.
1st Dec 2018, 9:35 AM
David Arumba
David Arumba - avatar