i am making a function that inputs weight and returns cost. My code is correct and I did my math but the cost being returned isn't making any sense
def cost_check(weight):
if weight <= 2:
cost = (weight * 1.50) + 20.00
elif weight > 2:
cost = (weight * 3.00) + 20.00
elif weight > 6:
cost = (weight * 4.00) + 20.00
else:
cost = (weight * 4.75) + 20.00
return cost
print(cost_check(8.4))
when I call the function it is supposed to return 53.60. BUT instead it returns 45.2 for some reason, it is really frustrating
This can not work because these statements will never be reached:
elif weight > 6:
cost = (weight * 4.00) + 20.00
else:
cost = (weight * 4.75) + 20.00
Suppose you have weight = 3. Then it will match the statement
elif weight > 2:
cost = (weight * 3.00) + 20.00
Because the next statements are elif and else they will be skipped
ok so i changed it to:
def cost_check(weight):
cost = 0
if weight <= 2:
cost = (weight * 1.50) + 20.00
elif weight > 2 and weight <= 6:
cost = (weight * 3.00) + 20.00
elif weight > 6 and weight <= 10:
cost = (weight * 4.00) + 20.00
else:
cost = (weight * 4.75) + 20.00
return(cost)
and it worked as it was supposed to, thanks anyways for the help guys!
Related
I'm trying to create a program utilizing the Bisection Method (there are quite a lot of unused variables and confusing comments, so just ignore those). The value being outputted is fine, except it's getting stuck in an infinite loop and printing an infinite number of floating point digits. Isn't the epsilon supposed to stop this from happening? Here's my code:
total_cost = 1000000
downpayment = 0.25
amount_needed = total_cost * downpayment
annual_salary = int(input("Enter the starting salary: "))
monthly_salary = annual_salary / 12
num_of_months = 36
#needs changing
epsilon = .01
num_of_guesses = 0
low = 0
high = 100
ans = (high + low) / 2.0
ans = round(ans, 2)
#might need changing
while (num_of_months * (monthly_salary * (ans / 100)))**2 - amount_needed >= epsilon:
print("Low:", low, "High:", high, "Answer:", ans)
num_of_guesses = num_of_guesses + 1
if num_of_months * (monthly_salary * (ans / 100)) < amount_needed:
low = ans
elif num_of_months * (monthly_salary * (ans / 100)) > amount_needed:
high = ans
ans = (high + low) / 2.0
ans = round(ans, 2)
print("Number Of Guesses: ", num_of_guesses)
It's probably something really stupid but I honestly don't know what's going on XD
I'm trying to write a program that uses bisection to find a fixed monthly rate that will pay off a balance with a month. This is what I have at the moment and what I get is an infinite loop but I'm not sure why.
balance = 3329
tempB = balance
annualInterestRate = 0.2
monthlyIntrestRate = (annualInterestRate/12)
low = balance / 12
high = (balance * (1 + monthlyIntrestRate)**12)/12
avg = (high + low)/2
epsilon = 0.01
while abs(balance - epsilon) >= 0.01:
avg = (high + low)/2
for i in range(12):
monthlyUnpaidBalance = balance - avg
updatedBalanceMonth = monthlyUnpaidBalance + (monthlyIntrestRate * monthlyUnpaidBalance)
balance = updatedBalanceMonth
if abs(balance - epsilon) <= 0.01:
print(avg)
break
else:
balance = tempB
if abs(updatedBalanceMonth) > epsilon:
low = avg
elif abs(updatedBalanceMonth) < epsilon:
high = avg
I have a much simpler code that does the same thing but it is inefficient the code to it is
MinPay = 10
balance = 3329
tempB = balance
annualInterestRate = 0.2
monthlyIntrestRate = (annualInterestRate/12)
while balance >= 0:
for i in range(12):
monthlyUnpaidBalance = balance - MinPay
updatedBalanceMonth = monthlyUnpaidBalance + (monthlyIntrestRate * monthlyUnpaidBalance)
balance = updatedBalanceMonth
if balance <= 0:
print(MinPay)
break
else:
MinPay += 10
balance = tempB
In general, if you have infinite loop, I would suggest you run your code under pdb and do step trace to find why the loop doesn't end.
In your case, I think the issue is on these lines:
if abs(updatedBalanceMonth) > epsilon:
low = avg
elif abs(updatedBalanceMonth) < epsilon:
high = avg
which abs() should generally be greater than epsilon. I see your intention is that if your monthly pay is too much so the resulting balance is negative then you should set high to avg so you try with a lower pay on next search iteration. So you should remove abs() in these conditions.
But I would suggest you make your code easier to read as follows, especially that's intended for finance application:
balance = 3329
rate = 0.2 # 20% p.a.
lopay = 1
hipay = balance
epsilon = 0.01
monthly = 100 # search start
pv = sum([monthly/((1+rate/12)**i) for i in range(1,13)])
while abs(balance - pv) >= epsilon:
if pv > balance:
hipay = monthly
else:
lopay = monthly
monthly = (hipay + lopay) / 2
pv = sum([monthly/((1+rate/12)**i) for i in range(1,13)])
which you simply compute the present value of the 12 monthly payments and compare that to the starting balance.
It gets stuck an infinite loop because your expression:
abs(balance - episolon)
when it is evaluated in the while loop exit condition never actually changes.
If you get stuck in a while loop, you can try little modifications to code like this:
balance = 3329
tempB = balance
annualInterestRate = 0.2
monthlyIntrestRate = (annualInterestRate/12)
low = balance / 12
high = (balance * (1 + monthlyIntrestRate)**12)/12
avg = (high + low)/2
epsilon = 0.01
count = 1
while abs(balance - epsilon) >= 0.01 and count <= 100:
print(abs(balance - epsilon))
avg = (high + low)/2
for i in range(12):
monthlyUnpaidBalance = balance - avg
updatedBalanceMonth = monthlyUnpaidBalance + (monthlyIntrestRate * monthlyUnpaidBalance)
balance = updatedBalanceMonth
if abs(balance - epsilon) <= 0.01:
print(avg)
break
else:
balance = tempB
if abs(updatedBalanceMonth) > epsilon:
low = avg
elif abs(updatedBalanceMonth) < epsilon:
high = avg
count += 1
In this case, the iterations are capped and you can see the value that you are evaluating in your exit condition as:
3328.99
3328.99
3328.99
3328.99
3328.99
3328.99
3328.99
3328.99
3328.99
3328.99
(continuing)
Your going to need to refine your logic so that you can actually hit an exit condition.
I am not sure what to do in order to update the assigned variable cost in reference to the if statements
Ive tried multiple things such as indentation, elif statements, adding additional BASE_RATE + BASE_RATE variables
BASE_RATE = 75
cost = BASE_RATE
if sex == 'M': # add another equal sign
cost = BASE_RATE + (BASE_RATE * .25)
if state == 'OH' or state == 'MO':
cost = BASE_RATE + (BASE_RATE * .10)
if age < 21 or age > 70:
cost = BASE_RATE + (BASE_RATE * .05)
No error messages, need to carry over the new assigned values to cost if sex == M is true and state == OH is true but age is between 21 and 69
you must be new to Python. You can update the value and increment it with the base rate:
BASE_RATE = 75
cost = BASE_RATE
if sex == 'M': # add another equal sign
cost += (BASE_RATE * .25)
if state == 'OH' or state == 'MO':
cost += (BASE_RATE * .10)
if 21 < age < 70:
cost += (BASE_RATE * .05)
I'm new to stackoverflow and I originally posted this as a comment here because it was related but it was suggested I make it a new post so here it is:
My attempt to solve the lesson looks similar to OP's but a cursory look has given me some ideas to fix it which I want to try before posing here. However, I looked at the help video and they solve the problem by beginning their code with
def print_cheapest_shipping_method(weight):
print(
"The cheapest option available is $%.2f with %s shipping")
I kind of understand that the code goes on to define those as variables, but if someone could explain it to me a little more clearly? There hasn't been anything like the %.2f and %s so far in the lessons and I'd like to understand better how the lecturer came to those figures.
Edited to add: my solution is this below
Edited again, here's the entire page
def ground_ship(weight):
if weight >= 10:
cost = 4.75
elif weight >= 6:
cost = 4
elif weight >= 2:
cost = 3
elif weight >= 0:
cost = 1.50
print(weight * cost + 20)
premium_ship = 125
def drone_ship(weight):
if weight >= 10:
cost = 14.25
elif weight >= 6:
cost = 12
elif weight >= 2:
cost = 9
elif weight >= 0:
cost = 4.5
print(weight * cost)
ground_ship(10)
drone_ship(1.5)
def best_deal(weight):
if ground_ship < drone_ship and ground_ship < drone:
method = "standard ground"
cost = ground_ship
elif premium_ship < drone_ship and premium_ship < ground_ship:
method = "premium"
cost = premium_ship
else:
method = "drone"
cost = drone_ship
print("The cheapest option for your package is " + method + " shipping and the cost will be $" + str(cost))
best_deal(10)
Everything checks without an error until I tried to print with best_deal(10) which then returned
Traceback (most recent call last):
File "script.py", line 41, in <module>
best_deal(10)
File "script.py", line 29, in best_deal
if ground_ship < drone_ship and ground_ship < drone:
TypeError: unorderable types: function() < function()
Disregard the line # this code starts on line 28
You comparison statement is effectively comparing functions, hence the error. What you intended to do is compare the result of each function calculations. For that, you would need to change a little each function, so that they return the calculated cost. Printing it is not enough. So, with that in mind, here what a working version of the code looks like. I'll add comments in a moment.
def print_cheapest_shipping_method(weight):
print("The cheapest option available is $%.2f with %s shipping")
def ground_ship(weight):
if weight >= 10:
cost = 4.75
elif weight >= 6:
cost = 4
elif weight >= 2:
cost = 3
elif weight >= 0:
cost = 1.50
total_cost = weight * cost + 20
print(total_cost)
return(total_cost) # have the function return the calculated value
premium_ship = 125
def drone_ship(weight):
if weight >= 10:
cost = 14.25
elif weight >= 6:
cost = 12
elif weight >= 2:
cost = 9
elif weight >= 0:
cost = 4.5
total_cost = weight * cost
print(total_cost)
return(total_cost) # have the function return the calculated value
ground_ship(10)
drone_ship(1.5)
def best_deal(weight):
# now you can compare values, by calling each function with the given 'weight'
if ground_ship(weight) < drone_ship(weight) and ground_ship(weight) < premium_ship:
method = "standard ground"
cost = ground_ship(weight) # get the cost from the function calculation
elif premium_ship < drone_ship(weight) and premium_ship < ground_ship(weight):
method = "premium"
cost = premium_ship # in this case, premium_ship is a value
else:
method = "drone"
cost = drone_ship(weight) # get the cost from the function calculation
print("The cheapest option for your package is " + method + " shipping and the cost will be $" + str(cost))
best_deal(10)
Also see it in action here: https://eval.in/1116417
I've been looking at this program for a while now and I can't seem to find what is wrong with the code. I've checked the numbers and they are fine. I almost think its a quotes or parentheses. I would appreciate the help. Here's the code:
# step 1: get the input
timbitsLeft = int(input())
# step 2: initialize the total cost
totalCost = 0
# step 3: buy as many large boxes as you can
bigBoxes = int(timbitsLeft / 40)
totalCost = totalCost + bigBoxes * 6.19 # update the total price
timbitsLeft = timbitsLeft - 40 * bigBoxes # calculate timbits still needed
# step 4, can we buy a medium box?
if timbitsLeft >= 20:
totalCost = totalCost + 3.39
timbitsLeft = timbitsLeft - 20
if timbitsLeft > 10: # step 5, can we buy a small box?
totalCost = totalCost + 1.99
timbitsLeft = timbitsLeft - 20
# step 6
totalCost = totalCost + timbitsLeft * 20
print(totalCost)
This is the error I get:
Did not pass tests. Please check details below and try again.
Results for test case 1 out of 11
Input:
10
Program executed without crashing.
Program output:
200.0
Expected this correct output:
1.99
Result of grading: Output line 1, value 200.0, did not match expected value 1.99
You are getting an output of 200 because you do not have enough money to buy a large box or medium box. You then check to see if you can buy a small box, but you only have 10 timbits, so the if statement, if timbitsLeft > 10: # step 5, can we buy a small box?, is not true so you cannot buy a small box either. Then you do the calculation totalCost = totalCost + timbitsLeft * 20 which gives you a value of 200.
Well, looks like your mistake is
if timbitsLeft > 10:
Your input is 10 so you have 10 timbits left,
but you need more than 10 to go further into the if statement,
therefore its not doing anything except:
totalCost = totalCost + timbitsLeft * 20
and thats basically
totalCost = 0 + 10 * 20
and that is indeed 200
you might need
if timbitsLeft >= 10:
You didn't read all of the information given to you.
The numbers are wrong for the small box and the price of 1 box.
if timbitsLeft > 10: # step 5, can we buy a small box?
totalCost = totalCost + 1.99
timbitsLeft = timbitsLeft - 20 (<---- the problem. it should be: - 10)
-10 is the amount of small boxes.
totalCost = totalCost + timbitsLeft * 20 (<---- the problem. it should be: *.2)
print(totalCost)
.2 is the price of a single box.
here is the solution to the cscircles "Coding Exercise: Timbits"
timbitsLeft = int(input()) # step 1: get the input
totalCost = 0 # step 2: initialize the total cost
# step 3: buy as many large boxes as you can
if timbitsLeft >=40:
bigBoxes = int(timbitsLeft / 40)
totalCost = totalCost + bigBoxes * 6.19 # update the total price
timbitsLeft = timbitsLeft - 40 * bigBoxes # calculate timbits still needed
if timbitsLeft >= 20: # step 4, can we buy a medium box?
mediumBoxes = int(timbitsLeft / 20)
totalCost = totalCost + mediumBoxes * 3.39
timbitsLeft = timbitsLeft - 20 * mediumBoxes
if timbitsLeft >= 10: # step 5, can we buy a small box?
smallBoxes = int(timbitsLeft / 10)
totalCost = totalCost + smallBoxes*1.99
timbitsLeft = timbitsLeft - smallBoxes*10
totalCost = totalCost + timbitsLeft * 0.2 # step 6
print(totalCost) # step 7