简体   繁体   中英

Python Iteration Efficiency

How do I make this code more efficient? I don't want to keep repeating the if statement for each state and just want one function or chunk of code. In the beginning of this code I have a dictionary array with a key and value pairing of each of the 50 states with their corresponding sales tax. How can I make a function that pulls from each key?

if state == 'Alabama':
    state = state_taxes['Alabama']
    tax = state * meal
    total = meal + tax + tip
    print "Your total is: $" + "%.2f" % total
elif state == 'Alaska':
    state = state_taxes['Alaska']
    tax = 0
    total = meal + tax + tip
    print "Your total is: $" + "%.2f" % total
elif state == 'Arizona':
    state = state_taxes['Arizona']
    tax = state * meal
    total = meal + tax + tip
    print "Your total is: $" + "%.2f" % total

etc., etc., etc..........

Why the if statements at all? Can't you just do:

state_tax = state_taxes[state]
tax = state_tax * meal
total = meal + tax + tip
print "Your total is: $" + "%.2f" % total

Many states have complex tax rates. Some have higher alcohol tax for example.

You can have a nested dict of dicts for multiple data items:

>>> state_taxes={
...     'Alabama': {"Rate": 0.04}, # etc
...     'Alaska': {"Food Rate": 0.08, "Alcohol Rate": 0.21}
...     # etc...
... }

Then access hierarchically:

>>> state_taxes['Alabama']['Rate']
0.04

So you can do:

tax=(state_taxes['Alaska']['Food Rate']*food_cost + 
     state_taxes['Alaska']['Alcohol Rate'] * drink_cost)

I'm assuming your state_taxes dictionary contains floats that align with the tax for each state (for example in your code you have 'Alaska' returning 0 for tax rather than computing it with what is presumably a state tax of 0 for Alaska from the state_taxes dictionary). From there you don't need to use the if statement at all, you can simply look up the value of the tax. Note that is also best practice to not overwrite your state variable with a different type of value (in your example you first use state to represent the name of the state, then use state to the tax for that state).

state = 'Alabama' #or 'Alaska', or whatever you set this to
state_tax = state_taxes[state]
tax = state_tax * meal
total = meal + tax + tip
print "Your total is: $" + "%.2f" % total

Note that this assumes your state will always be in your state_taxes dictionary. You will want to add some error handling if there is any chance your state variable will have a value that is not in the keys of state taxes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM