In this video, Josh McQuiston demonstrates his solution for the fibonacci sequence programming challenge. Explore just one of the many possible solutions to this challenge. Josh will explain his approach to solving this challenge, by explaining his code line-by-line. Compare his solution to your own.
- [Instructor] Let's take a look…at my solution to the challenge.…Your solution may not be identical…but it should output the same thing.…Since each number in the Fibonacci Sequence…is the sum of the previous two,…we will always need to keep the state of the previous two.…In this function, lead is defined to be one…so that is the first number yielded.…Each time it yields a number,…trailing moves up to be whatever value lead was.…At the same time lead adds trailing to itself.…So they both move in a synchronized fashion…up through the Fibonacci Sequence.…
Generators are suited to this problem well…because they are able to hold state.…To produce this sequence,…the only information needed at any given time…is the two consecutive numbers of wherever you are.…A generator can pause at each point and yield a number…and continue on right where it left off.…I'll open up a shell and demonstrate this for you.…First, I'll call fibonacci_gen…and assign it to the variable fib.…I'll yield the first value manually by calling next.…
Share this video
Embed this video
Video: Solution: Fibonacci sequence fenerator