Skip to content

Commit

Permalink
Iterators Tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
CoreyMSchafer committed Oct 23, 2018
1 parent 9e4da1f commit 588f067
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
41 changes: 41 additions & 0 deletions Python/Iterators-Coding-Problem/iter-demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

class Sentence:

def __init__(self, sentence):
self.sentence = sentence
self.index = 0
self.words = self.sentence.split()

def __iter__(self):
return self

def __next__(self):
if self.index >= len(self.words):
raise StopIteration
index = self.index
self.index += 1
return self.words[index]


def sentence(sentence):
for word in sentence.split():
yield word


my_sentence = sentence('This is a test')

# for word in my_sentence:
# print(word)

print(next(my_sentence))
print(next(my_sentence))
print(next(my_sentence))
print(next(my_sentence))
print(next(my_sentence))


# This should have the following output:
# This
# is
# a
# test
29 changes: 29 additions & 0 deletions Python/Iterators/iter-demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

class MyRange:

def __init__(self, start, end):
self.value = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current


def my_range(start):
current = start
while True:
yield current
current += 1


nums = my_range(1)

for num in nums:
print(num)

0 comments on commit 588f067

Please sign in to comment.