Skip to content

Instantly share code, notes, and snippets.

@AnjaneyuluBatta505
Created December 17, 2017 10:44
Show Gist options
  • Save AnjaneyuluBatta505/5fdacf76f52672afb4b32e7011c1567a to your computer and use it in GitHub Desktop.
Save AnjaneyuluBatta505/5fdacf76f52672afb4b32e7011c1567a to your computer and use it in GitHub Desktop.
Custom python iterator
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