In [2]:
!cat some_birds.txt
In [5]:
def read_observations(filename):
'''Read data, returning [(date, time, bird)...].'''
reader = open(filename, 'r')
result = []
for line in reader:
fields = line.split('#')[0].strip().split()
assert len(fields) == 3, 'Bad line "%s"' % line
result.append(fields)
return result
In [6]:
def earliest_observation(data):
'''How early did we see each bird?'''
result = {}
for (date, time, bird) in data:
if bird not in result:
result[bird] = time
else:
result[bird] = min(result[bird], time)
return result
In [7]:
entries = read_observations('some_birds.txt')
result = earliest_observation(entries)
print result
In [8]:
def birds_by_date(data):
'''Which birds were seen on each day?'''
result = {}
for (date, time, bird) in data:
if date not in result:
result[date] = {bird}
else:
result[date].add(bird)
return result
print birds_by_date(entries)
least
least
to None
and handle its replacement as a special case
In [9]:
def least_common_birds(data):
'''Which bird or birds have been seen least frequently?'''
counts = count_by_bird(data) # need to write this
least = min(counts.values())
result = set()
for bird in counts:
if counts[bird] == least:
result.add(bird)
return result
# Helper function.
def count_by_bird(data):
'''How many times was each bird seen?'''
result = {}
for (date, time, bird) in data:
if bird not in result:
result[bird] = 0
result[bird] += 1
return result
# Test.
print least_common_birds(entries)