Issue
I tried to solve this problem using two approaches. The first one calculates the rent from the bottom-up while the second one does it from the top-down. Unfortunately, I cannot identify what is causing them to return different outputs instead of the same one.
Here is the question: From a renter's monthly income, the landlord gets to keep 5% of the first $0 to $9999 + 10% of the remaining $10k to $19999 + 15% of the remaining $20k to $49999 + 20% of the remaining $50k to $99999 + 30% of the remaining $100000 and above. Find out how much rent the renter will have to pay this month if their monthly income was $23,000.
def calculate_rent_1(renter_salary):
rent = 0
if renter_salary > 0:
if renter_salary <= 9999:
return 0.05 * renter_salary
else:
rent += 0.05 * 9999
renter_salary -= 9999
if renter_salary > 9999:
if renter_salary <= 19999:
return rent + 0.1 * renter_salary
else:
rent += 0.1 * 9999
renter_salary -= 9999
if renter_salary > 19999:
if renter_salary <= 49999:
return rent + 0.15 * renter_salary
else:
rent += 0.15 * 29999
renter_salary -= 29999
if renter_salary > 49999:
if renter_salary <= 99999:
return rent + 0.2 * renter_salary
else:
rent += 0.2 * 49999
renter_salary -= 49999
if renter_salary > 99999:
return rent + 0.3 * renter_salary
def calculate_rent_2(renter_salary):
if not renter_salary: return 0
rent = 0
if 100000 <= renter_salary:
rent += 0.3 * (renter_salary - 100000)
renter_salary = 99999
if 50000 <= renter_salary:
rent += 0.2 * (renter_salary - 50000)
renter_salary = 49999
if 20000 <= renter_salary:
rent += 0.15 * (renter_salary - 20000)
renter_salary = 19999
if 10000 <= renter_salary:
rent += 0.1 * (renter_salary - 10000)
renter_salary = 9999
if 0 < renter_salary:
rent += 0.05 * renter_salary
return rent
print("Output from calculate_rent_1:", calculate_rent_1(23000)) # output: 1800.0500000000002
print("Output from calculate_rent_2:", calculate_rent_2(23000)) # output: 1949.8500000000001
Solution
I presume you realize the second function is the correct one. Your problem is in the first function:
rent = 0
if renter_salary > 0:
if renter_salary <= 9999:
return 0.05 * renter_salary
else:
rent += 0.05 * 9999
renter_salary -= 10000
print( rent, renter_salary)
if renter_salary > 9999:
if renter_salary <= 19999: ##<<<<<<
return rent + 0.1 * renter_salary
else:
rent += 0.1 * 9999
renter_salary -= 10000
In the marked line, you're checking for salary <= 19999, but by this time you have already subtracted off the initial 10,000. This needs to check for 9999. The same repeats in the other clauses.
Answered By - Tim Roberts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.