Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 68 lines (56 sloc) 2.2 KB
#!/usr/bin/python
import collections
import fileinput
taxed = collections.Counter()
untaxed = collections.Counter()
total_tax = 0
supplied_total = None
untaxed_marker = '!'
items = collections.defaultdict(collections.Counter)
longest_category_length = 0
for line in fileinput.input():
line_only = line.rstrip('\r\n')
amount, what = line_only.split(None, 1)
if what == 'tax':
total_tax += float(amount)
elif what == 'total':
supplied_total = float(amount)
else:
# Split out the item description, if present
remaining_terms = what.split(None, 1)
category = remaining_terms[0]
longest_category_length = max(longest_category_length, len(category))
if len(remaining_terms) > 1:
item = remaining_terms[1]
items[category].update({item})
if amount.endswith(untaxed_marker):
untaxed.update({category: float(amount[:-1])})
else:
taxed.update({category: float(amount)})
# If there is any leftover amount, make a category for it.
# (Obviously, this requires the user to have specified the 'total'.)
if supplied_total:
subtotal = sum(untaxed.values()) + sum(taxed.values()) + total_tax
leftover = supplied_total - subtotal
# We assume this "default" category gets taxed too.
# (If this isn't true, you have to enter it manually for now.)
taxed.update({'LEFTOVER': leftover})
# Distribute the tax amongst the tax categories.
tax_fractions = {k: taxed[k] / sum(taxed.values()) for k in taxed}
tax = {k: round(tax_fractions[k] * total_tax, 2) for k in tax_fractions}
# Make sure it adds up down to the penny!
tax[tax.keys()[0]] += (total_tax - sum(tax.values()))
total = untaxed + taxed
total.update(tax)
money_format = '{:8,.2f} '
format_string = money_format + '{:' + str(longest_category_length) + '} {}'
grand_total = 0
longest_string_length = 0
for category in total:
grand_total += total[category]
line = format_string.format(total[category], category,
', '.join(items[category].keys()))
print line
longest_string_length = max(longest_string_length, len(line))
print longest_string_length * '='
print (money_format + '{}').format(grand_total, 'GRAND TOTAL')