The Weekly Challenge 323

Arithmetic Operations & Progressive Tax Brackets!

Original Challenge Link

Task 1: Increment Decrement

"Stateful Strings: Tracking Value Through Operations!"

Given a list of operations in C-style syntax (++x, x++, --x, x--), calculate the final value starting from zero.

The Strategy: Initialize a variable value to zero. Iterate through the list of operation strings. Since the task specifies only increment and decrement operations, we can simply check if the string contains the substring "++" or "--". Adjust the counter accordingly and return the final result.
Perl Implementation
sub final_value {
    my (@ops) = @_;
    my $value = 0;
    for my $op (@ops) {
        if ($op =~ /\+\+/) {
            $value++;
        } elsif ($op =~ /--/) {
            $value--;
        }
    }
    return $value;
}
Python Implementation
def final_value(ops: list[str]) -> int:
    value = 0
    for op in ops:
        if "++" in op:
            value += 1
        elif "--" in op:
            value -= 1
    return value

Task 2: Tax Amount

"Progressive Math: Calculating Owed Tax Across Brackets!"

Calculate total tax for a given income based on a sequence of upper limits and percentages.

The Strategy: Maintain a prev_limit (initially 0) and a total_tax. Iterate through the tax brackets. For each bracket, determine how much of the income falls between the previous limit and the current limit. Multiply this taxable amount by the bracket's percentage (converted to a decimal) and add it to the total. Stop when the income is fully covered.
Perl Implementation
sub tax_amount {
    my ($income, @tax_brackets) = @_;
    my ($prev, $total) = (0, 0);
    for my $bracket (@tax_brackets) {
        my ($upper, $percent) = @$bracket;
        last if $income <= $prev;
        my $taxable = ($income < $upper ? $income : $upper) - $prev;
        $total += $taxable * ($percent / 100);
        $prev = $upper;
    }
    return $total;
}
Python Implementation
def tax_amount(income: int, brackets: list[tuple[int, int]]) -> float:
    total = 0.0
    prev = 0
    for upper, percent in brackets:
        if income <= prev:
            break
        taxable = min(income, upper) - prev
        total += taxable * (percent / 100)
        prev = upper
    return total