Skip to content

Instantly share code, notes, and snippets.

@axelarge
Last active August 29, 2015 13:56
Show Gist options
  • Save axelarge/9298599 to your computer and use it in GitHub Desktop.
Save axelarge/9298599 to your computer and use it in GitHub Desktop.
from itertools import groupby, izip
from operator import itemgetter
DATA = [
{"service_date": "2013-10-28", "odometer": "115379"},
{"service_date": "2013-10-11", "odometer": "115050"},
{"service_date": "2013-09-27", "odometer": "114410"},
{"service_date": "2013-05-15", "odometer": "107936"},
{"service_date": "2013-05-09", "odometer": "107534"},
{"service_date": "2012-10-16", "odometer": "101089"},
{"service_date": "2012-09-17", "odometer": "100316"},
{"service_date": "2012-05-10", "odometer": "96505"},
{"service_date": "2011-03-14", "odometer": "71449"},
{"service_date": "2010-05-06", "odometer": "60300"},
{"service_date": "2009-09-16", "odometer": "52572"},
{"service_date": "2009-03-01", "odometer": "52815"},
{"service_date": "2009-01-27", "odometer": "44982"},
{"service_date": "2008-07-21", "odometer": "37534"},
{"service_date": "2008-03-18", "odometer": "30331"},
{"service_date": "2007-11-27", "odometer": "28836"},
{"service_date": "2007-05-09", "odometer": "18726"},
{"service_date": "2006-07-26", "odometer": "8122"},
]
def get_year(service_entry):
# return service_entry["service_date"].getYear()
return service_entry["service_date"][:4]
def get_odometer(service_entry):
return int(service_entry["odometer"])
def max_odo(services):
return get_odometer(services[-1])
def km_per_year(data):
sorted_data = sorted(data, key=operator.itemgetter("service_date"))
by_year = list((year, max_odo(list(services))) for year, services in groupby(sorted_data, get_year))
zero = ("0000", 0)
zipped = izip([zero] + by_year, by_year)
return [(year_hi, max_hi - max_lo) for (year_lo, max_lo), (year_hi, max_hi) in zipped]
>>> km_per_year(DATA)
[('2006', 8122), ('2007', 20714), ('2008', 8698), ('2009', 15038), ('2010', 7728), ('2011', 11149), ('2012', 29640), ('2013', 14290)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment