Skip to content

Instantly share code, notes, and snippets.

@giwa
Created March 7, 2016 05:45
Show Gist options
  • Save giwa/704e743ce0e64c17d888 to your computer and use it in GitHub Desktop.
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
def index_words(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ' ':
result.append(index + 1)
return result
address = 'Four score and seven years ago...'
result = index_words(address)
print(result[:3])
[0, 5, 11]
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
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