I’ve been doing the Weekly
Challenges. The
latest
involved light parsing and tax bracket calculations. (Note that this
ends today.)
Task 1: Increment Decrement
You are given a list of operations.
Write a script to return the final value after performing the given operations in order. The initial value is always 0.
Possible Operations: ++x or x++: increment by 1 --x or x--: decrement by 1
From which I observe that the parsing can be reduced to a single
question: "is the second character a '+'?" Or, for the regex-heavy
languages, "does the string contain a '+'?" In Raku:
sub incrementdecrement(@operations) {
my $p = 0;
for @operations -> $s {
if ($s ~~ /\+/) {
$p++;
} else {
$p--;
}
}
$p;
}
Meanwhile in PostScript:
/incrementdecrement {
0 exch
{
1 get 43 eq {
1 add
} {
1 sub
} ifelse
} forall
} bind def
Task 2: Tax Amount
You are given an income amount and tax brackets.
Write a script to calculate the total tax amount.
The brackets are specified as an upper bound and a rate, with the
lower bound being the upper bound of the previous bracket (or zero).
Python:
def taxamount(income, brackets):
Set up the tax accumulator, and the upper bound of the previous
bracket.
tax = 0
lastbracket = 0
Iterate over brackets.
for bracket in brackets:
If this bracket is at all relevant to us,
if income > lastbracket:
The tax contribution is the lower of total income and upper bound,
minus the lower bound, multiplied by the tax rate/
tax += (min(income, bracket[0]) - lastbracket) * bracket[1]
If the lower bound was more than our income, since the brackets are in
order, we can bail out here.
else:
break
Set our upper bound as the lower bound of the next bracket.
lastbracket = bracket[0]
For languages which support it, I've been doing all this in integers,
but I have to return the result as a float.
return tax / 100
Full code on
github.