0
Can someone please help me with the Tax Code Coach challenge in Python? I passed 5/6 cases, but can't figure out the last one.
input = input() purchase = input.split(',') taxed = [] untaxed =[] for i in range(0, len(purchase)): purchase[i] = float(purchase[i]) if purchase[i] < 20: taxed.append(purchase[i]) taxed_sum = (sum(taxed) * 1.07) elif purchase[i] >= 20: untaxed.append(purchase[i]) untaxed_sum = sum(untaxed) total = taxed_sum + untaxed_sum print(round(total, 2))
7 Respostas
+ 4
# Hi, linda !
# Just declare the variables taxed_sum and untaxed_sum before you start use them,
# and the code will work, like this:
purchase = input().split(",")
taxed, untaxed = [], []
taxed_sum = untaxed_sum = 0
for i in range(len(purchase)):
purchase[i] = float(purchase[i])
if purchase[i] < 20:
taxed.append(purchase[i])
taxed_sum = sum(taxed) * 1.07
elif purchase[i] >= 20:
untaxed.append(purchase[i])
untaxed_sum = sum(untaxed)
total = taxed_sum + untaxed_sum
print(round(total, 2))
# - - - - -
# Also avoid call the variable input the same as the built-in function input, like input = input().
# (For example inp = input() is better) Otherwise it is, or can be, confusing.
+ 2
# Hi, linda !
# Yes, it is.
# Maybe the code below is more easy to understand. f-string formating is good
# for formting outputs. You can compare the 0.2f after the colon with
# round(total, 2).
# List comprehension is a compact way create lists and handle nestle lops
# and conditions. But they are not good if the become to complex.
# in costs I hadle both cases at the same time: if x < 20 then add taxes,
# otherwise not. This makes the code more compact.
inp = input().split(',')
purchases = [float(x) for x in inp]
costs = [(x*1.07 if x < 20 else x) for x in purchases]
total = sum(costs)
print(f"{total:0.2f}")!
+ 1
Oh wow, thank you so much for the tips!
+ 1
# Hi, linda ! Or as a oneliner:
print(f"{sum(x*1.07 if x < 20 else x for x in (float(s) for s in input().split(','))):.2f}")
+ 1
THANK YOU!
0
Here is the Coach Coach question, I couldn't fit it above.
You are shopping at a store that is having a special where you do not have to pay the tax on anything that costs 20 dollars or more!
If you have a list of prices for all of your items, what is your total once the tax is added in? Tax is 7% on the items that you would still need to pay tax on.
Task:
Determine the total cost once you include tax of 7% on the items that are still taxed.
Input Format:
A string of numbers, separated by commas, that represent to price of each item that you are going to buy.
Output Format:
A number, rounded to two decimal places, of the total for your purchase once tax is included on items under 20 dollars.
Sample Input:
5,18,25,34
Sample Output:
83.61
0
Per Bratthammar I want to learn how to write shorter code. Is this F-Strings and list comprehension?