Python Forum
i need someone's opinion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: i need someone's opinion (/thread-42132.html)



i need someone's opinion - wynand - May-16-2024

i am busy making my tax calculator global, the following is my code to calculate rebates, i want to use the min function and run a running balance.
it should check in what bracket the user's age is and then add the results to get the total rebate/benefit amount. i am still a beginner at coding and don't understand the concept 100%. the -1 is for if age is more than 75. and i am using a dictionary called rebate_table


rebate_table = {65: 17235, 75: 9444, -1: 3145}

def calculate_tax_benifits(age, rebate_table):
    total_tax_benefits = 0

    # Check if age is less than the minimum age threshold in rebate_table
    min_age = min(rebate_table.keys())
    if age < min_age:
        total_tax_benefits += rebate_table[min_age]
    else:
        # Iterate through each benefit data
        for benefit_age_threshold, benefit_amount in rebate_table.items():
            # Check if age is less than the current threshold
            if age < benefit_age_threshold:
                total_tax_benefits += benefit_amount
                break  # Break the loop, found the applicable rebate
            elif benefit_age_threshold == -1:  # Special case for age > 75
                total_tax_benefits += benefit_amount
            else:
                total_tax_benefits += benefit_amount

    print(total_tax_benefits)
    return total_tax_benefits



RE: i need someone's opinion - deanhystad - May-16-2024

In the fairly recent past your code wouldn't work at all because dictionaries were not ordered. Now you can loop through dictionary keys with confidence that they are in the same order they were added to the dictionary. But why use a dictionary when you don't look anything up? I would use a list or tuple.
rebate_table = ((65, 17235), (75, 9444), (76, 3145))


def rebate(age, table):
    """Return rebate for age."""
    for cutoff, rebate in table:
        if age < cutoff:
            break
    return rebate


for age in (-100, 64, 65, 66, 74, 75, 76, 100, 1000):
    print(age, "=", rebate(age, rebate_table))
This is called "binning". We determine which "bin" contains age and return the corresponding rebate. We have a default bin to catch all ages that don't fit into one of the other bins. I set the age for the default bin to 76. Since this is the last bin, any age greater than the age of the second to last bin will work. 75, 76, 1000, infinity all get the last rebate in the table,