Created
March 7, 2016 05:45
-
-
Save giwa/704e743ce0e64c17d888 to your computer and use it in GitHub Desktop.
EP 16 Consider Generator Instead of Returning Lists ref: http://qiita.com/giwa/items/e20a575a0b3e6028d532
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
def index_words(text): | |
result = [] | |
if text: | |
result.append(0) | |
for index, letter in enumerate(text): | |
if letter == ' ': | |
result.append(index + 1) | |
return result | |
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
address = 'Four score and seven years ago...' | |
result = index_words(address) | |
print(result[:3]) | |
[0, 5, 11] |
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
def index_words_iter(text): | |
if text: | |
yield 0 | |
for index, letter in enumerate(text): | |
if letter == ' ': | |
yield index + 1 | |
def index_file(handle): | |
offset = 0 | |
for line in handle: | |
if line: | |
yield offset | |
for letter in line: | |
offset += 1 | |
if letter == '': | |
yield offset | |
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
from itertools import islice | |
with open('/tmpaddress.txt') as f: | |
it = index_file(f) | |
result = islice(it, 0, 3) | |
print(list(result)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment