Create a class that will return the Fibonacci numbers sequentially everytime it is called using __iter__()
Question
Create a class that will return the Fibonacci numbers sequentially every time it is called using __iter__()
Solution
Sure, here is a Python class that uses the __iter__()
method to generate Fibonacci numbers sequentially:
class Fibonacci:
def __init__(self):
self.prev = 0
self.curr = 1
def __iter__(self):
# This method makes our class iterable
return self
def __next__(self):
# This method should be implemented by an iterator
value = self.curr
self.curr += self.prev
self.prev = value
return value
You can use this class as follows:
fib = Fibonacci()
for _ in range(10):
print(next(fib))
This will print the first 10 Fibonacci numbers.
Similar Questions
Generate the Fibonacci sequence up to the 10th term and calculate the value of the 10th term.
create a C program to print Fibonacci series upto a specified number N using while loop.
What correction should be made to the following code to calculate the Fibonacci number correctly?def fib(n): return fib(n-1) + fib(n-2)
Write a C program to print the Fibonacci series using recursion and without using recursion.
Suppose the first fibonnaci number is 0 and the second is 1. What is the sixth fibonnaci number? ans. 5 6 7 8
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.