Last active
December 31, 2019 07:29
-
-
Save lamchau/3e927fad81ff29719b38d74d8778cfb6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import math | |
from prettytable import PrettyTable | |
def main(): | |
params = { | |
'amount': 12.34, | |
'split': 1 | |
} | |
render_table(**params) | |
class TipTable(PrettyTable): | |
def __init__(self, field_names=None, **kwargs): | |
filtered = TipTable.filter_list(field_names) | |
super().__init__(filtered, **kwargs) | |
self.float_format = '0.2' | |
self.align = 'r' | |
def add_row(self, row): | |
filtered = TipTable.filter_list(row) | |
return super().add_row(filtered) | |
@staticmethod | |
def filter_list(array): | |
if not array: | |
return [] | |
return list(filter(lambda x: x is not None, array)) | |
def render_table(amount, split=1): | |
tip_amounts = [0.15, 0.18, 0.20, 0.25, 0.30] | |
split = max(split, 1) | |
amount = abs(amount) | |
def show_value(value): | |
return value if split > 1 else None | |
headers = [ | |
'%', | |
'Tip', | |
show_value('Each (%s)' % split), | |
show_value('Split'), | |
'Total' | |
] | |
table = TipTable(headers) | |
table_rounded = TipTable(headers) | |
for percentage in tip_amounts: | |
tip = (amount * (1 + percentage)) - amount | |
total = amount + tip | |
row = [ | |
percentage, | |
tip, | |
show_value(tip / split), | |
show_value((total / split)), | |
total | |
] | |
table.add_row(row) | |
# create rounded tips table | |
total_rounded = float(math.ceil(total)) | |
tip_rounded = total_rounded - total + tip | |
row_rounded = [ | |
percentage, | |
tip_rounded, | |
show_value(tip_rounded / split), | |
show_value(total_rounded / split), | |
total_rounded | |
] | |
table_rounded.add_row(row_rounded) | |
print('Amount: %s' % amount) | |
print('Exact:') | |
print(table) | |
print('') | |
print('Rounded:') | |
print(table_rounded) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment