diff options
| author | Packy Anderson <packy@cpan.org> | 2025-05-29 21:31:12 -0400 |
|---|---|---|
| committer | Packy Anderson <packy@cpan.org> | 2025-05-29 21:31:12 -0400 |
| commit | f8eeff1f9b16a0c7913cbcb0112cbf61259d574f (patch) | |
| tree | 23e3c5c280b96b08aeeff97e0059d8f5bd1d5722 /challenge-323/packy-anderson/python/ch-2.py | |
| parent | 6baf6eb311334b1ba4dd3101f7ba1d27120989db (diff) | |
| download | perlweeklychallenge-club-f8eeff1f9b16a0c7913cbcb0112cbf61259d574f.tar.gz perlweeklychallenge-club-f8eeff1f9b16a0c7913cbcb0112cbf61259d574f.tar.bz2 perlweeklychallenge-club-f8eeff1f9b16a0c7913cbcb0112cbf61259d574f.zip | |
Challenge 323 solutions by Packy Anderson
* Raku that maybe looks like Raku, but mostly like Perl
* Perl
* Python that definitely looks like Perl
* Elixir that looks kinda like Elixir
1 blog post
Diffstat (limited to 'challenge-323/packy-anderson/python/ch-2.py')
| -rwxr-xr-x | challenge-323/packy-anderson/python/ch-2.py | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/challenge-323/packy-anderson/python/ch-2.py b/challenge-323/packy-anderson/python/ch-2.py new file mode 100755 index 0000000000..c5c646192d --- /dev/null +++ b/challenge-323/packy-anderson/python/ch-2.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +def fmt(num): + if num > 0: + # display to 100ths place + return '{:0.2f}'.format(num) + else: + # format it as a string + return f"{int(num)}" + +def taxAmt(income, tax): + if income == 0: + return 0, "" # special case + + last_max = 0 + total = 0 + operations = [] + subtotals = [] + for max_income, rate in tax: + # adjust the maximum amount at this rate + # to be relative to the last rate + max_income -= last_max + # the amount to be taxed at this rate + amt = min(income, max_income) + tax = amt * rate/100 + total += tax + # make sure we display to 100ths place + # if we hace a non-zero tax amount + tax = fmt(tax) + # save the steps so we can display them at the end + operations.append(f"({amt} * {rate}/100)") + subtotals.append(tax) + # we've just taxed $amt, so remove it from $income + income -= amt + # adjust the last rate for the next loop + last_max += max_income + # bail if there's no more income + if income <= 0: break + + return ( + total, + "Total Tax => " + ' + '.join(operations) + "\n" + + " => " + ' + '.join(subtotals) + "\n" + + " => " + fmt(total) + ) + +def solution(income, tax): + brackets = [ f"[{t[0]},{t[1]}]" for t in tax ] + display = ", ".join(brackets) + print(f'Input: $income = {income}, @tax = ({display})') + output, explain = taxAmt(income, tax) + print(f'Output: {output}\n\n{explain}') + + +print('Example 1:') +solution(10, [[3, 50], [7, 10], [12,25]]) + +print('\nExample 2:') +solution(2, [[1, 0], [4, 25], [5,50]]) + +print('\nExample 3:') +solution(0, [[2, 50],]) |
