Skip to content

Instantly share code, notes, and snippets.

@joetsoi
Created September 22, 2011 15:36
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 joetsoi/1235081 to your computer and use it in GitHub Desktop.
Save joetsoi/1235081 to your computer and use it in GitHub Desktop.
functional programming python
from itertools import takewhile, dropwhile
from functools import partial
#... some other imports
def some_table(context, series, format_string):
table_options = format_string.split()
is_same_date = lambda date, i: i.datestamp > date
is_same_week = partial(is_same_date, context['date'] - timedelta(weeks=1))
is_same_month = partial(is_same_date, context['date'] - timedelta(weeks=4))
is_same_year = partial(is_same_date, context['date'] - timedelta(weeks=52))
function_dict = {
'd' : lambda series: series[0].price - series[1].price,
'w' : lambda series: series[0].price - dropwhile(is_same_week, series).next().price,
'm' : lambda series: series[0].price - dropwhile(is_same_month, series).next().price,
'y' : lambda series: low_high(i.price for i in takewhile(is_same_year, series)),
}
table = []
for series_name, series in series_set.items():
try:
row = dict([ (option, function_dict[option](series['list'])) for option in table_options ])
except KeyError:
raise template.TemplateSyntaxError("some_table has wrong arguments")
except IndexError:
raise template.TemplateSyntaxError("some_table : series does not contain enough data")
row.update({
'name' : series_name,
'price' : series['list'][0].price,
})
table.append(row)
return {
'table': table,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment