Created
December 17, 2017 10:44
-
-
Save AnjaneyuluBatta505/5fdacf76f52672afb4b32e7011c1567a to your computer and use it in GitHub Desktop.
Custom python iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fibonacci: | |
def __init__(self, limit): | |
self.limit = limit | |
self.counter = 0 | |
self.fib_data = [] | |
def __iter__(self): | |
return self | |
def next(self): | |
self.counter += 1 | |
if self.counter > self.limit: | |
raise StopIteration | |
if len(self.fib_data) < 2: | |
self.fib_data.append(1) | |
else: | |
self.fib_data = [ | |
self.fib_data[-1], self.fib_data[-1] + self.fib_data[-2] | |
] | |
return self.fib_data[-1] | |
# Case1 | |
for i in Fibonacci(3): | |
print(i) | |
# Output: | |
# 1 | |
# 1 | |
# 2 | |
# Case2 | |
iter_obj = Fibonacci(3) | |
print(next(iter_obj)) | |
print(next(iter_obj)) | |
print(next(iter_obj)) | |
print(next(iter_obj)) | |
# Output: | |
# 1 | |
# 1 | |
# 2 | |
# Traceback (most recent call last): | |
# File "fibonacci.py", line 30, in <module> | |
# print next(iter_obj) | |
# StopIteration |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment