Skip to content

Instantly share code, notes, and snippets.

@giwa
Created March 11, 2016 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giwa/d64bd2c605a5005e7f41 to your computer and use it in GitHub Desktop.
Save giwa/d64bd2c605a5005e7f41 to your computer and use it in GitHub Desktop.
EP 17 Be Defensive When Iterating Over Arguments ref: http://qiita.com/giwa/items/3c386c906472c7d54f24
def normalize(numbers):
total = sum(numbers)
result = []
for value in numbers:
percent = 100 * value / total
result.append(percent)
return result
>>> visits = [15, 35, 80]
>>> percentage = normalize(visits)
>>> percentage
[11.538461538461538, 26.923076923076923, 61.53846153846154]
def read_visits(data_path):
with open(data_path) as f:
for line in f:
yield int(line)
>>> it = read_visits('data')
>>> percentage = normalize(it)
>>> percentage
[]
it = read_visits('data')
list(it)
[15, 35, 80]
list(it)
[]
def normalize(numbers):
numbers = list(numbers) # Copy the iterator
total = sum(numbers)
result = []
for value in numbers:
percent = 100 * value / total
result.append(percent)
return result
def normalize_func(get_iter):
total = sum(get_iter()) # New Iterator
result = []
for value in get_iter(): # New Iterator
percent = 100 * value / total
result.append(percent)
return result
precentage = normalize_func(lambda: read_visits(path))
class ReadVisits:
def __init__(self, data_path):
self.data_path = data_path
def __iter__(self):
with open(self.data_path) as f:
for line in f:
yield int(line)
def normalize(numbers):
if iter(numbers) is iter(numbers):
raise TypeError("Must supply a container")
total = sum(numbers)
result = []
for value in numbers:
percent = 100 * value / total
result.append(percent)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment