forked from CoreyMSchafer/code_snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9e4da1f
commit 588f067
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
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
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 |
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
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) |