What is wrong with calculating total charges thru out my program - python

Hello my program can count how many customers and tell the customer their price based on the amount of hours but cannot add the total charges to save my life
Here’s my code
count = 1
total_charge = 0
total = 0
hours_parked = 0
ask = 1
standardRate = 2.00
FEE = .50
def calculate_charges(x, f, sr, t):
if x <= 3:
sr = 2.00
t = sr
print(t)
elif x >= 3 and x <= 24:
sr = 2.00
f = (x - 3) * .50
t = f + sr
print(t)
else:
print("We only allow 24 hours tops. Check the number of hours again!")
main(count, total_charge, hours_parked, ask, total)
def main(c, y, h, a, t):
h = int(input("How many hours did the customer park?"))
calculate_charges(h, FEE, standardRate, total)
c += 1
a = int(input("Is there more customers?(Type 1 for YES and 2 for NO.)"))
if a == 1:
y = t + y
main(count, total_charge, hours_parked, ask, total)
else:
y = t + y
c += 1
print("There was a total of ", c, " customers and a profit of $", y, "for the day!" )
main(count, total_charge, hours_parked, ask, total)
How many hours did the customer park?2
2.0
Is there more customers?(Type 1 for YES and 2 for NO.)1
How many hours did the customer park?2
2.0
Is there more customers?(Type 1 for YES and 2 for NO.)2
There was a total of 3 customers and a profit of $ 0 for the day!

Your previous code did not add up the results of the previous calculation.
count = 0
total_charge = 0
total = 0
hours_parked = 0
ask = 1
standardRate = 2.00
FEE = .50
def calculate_charges(x, f, sr):
if x <= 3:
t = sr
print(t)
else:
f = (x - 3) * f
t = f + sr
print(t)
return t
def main(c, y, h, a, t):
while True:
h = abs(int(input("How many hours did the customer park?")))
if h > 24:
print("We only allow 24 hours tops. Check the number of hours again!")
else:
break
t += calculate_charges(h, FEE, standardRate)
c += 1
a = int(input("Is there more customers?(Type 1 for YES and 2 for NO.)"))
if a == 1:
y = t + y
main(c, y, h, ask, total)
else:
y = t + y
print("There was a total of ", c, " customers and a profit of $", y, "for the day!")
main(count, total_charge, hours_parked, ask, total)
How many hours did the customer park?27
We only allow 24 hours tops. Check the number of hours again!
How many hours did the customer park?6
3.5
Is there more customers?(Type 1 for YES and 2 for NO.)1
How many hours did the customer park?28
We only allow 24 hours tops. Check the number of hours again!
How many hours did the customer park?10
5.5
Is there more customers?(Type 1 for YES and 2 for NO.)2
There was a total of 2 customers and a profit of $ 9.0 for the day!

You're calling
main(count, total_charge, hours_parked, ask, total)
but count, total_charge, hours_parked, ask and total are not being updated anywhere.
So you're passing in total_charge = 0 and that's what the program is returning.
Try passing c, y, h, a, t into main within your main function. (btw, it might be simpler to do everything in a while in the calculate_charges function)
Also...
It may be easier for you to figure out what's happening if your variables have meaningful names. After studying CompSci for 4 years in undergrad and now as a graduate student, one important lesson I've learned is that following coding convention will pay off both in the short run and in the long run.

Related

Wrong calculation in Python for overpayment

I started an online training for Python. The assignment wants to me calculate 45 hours work for 10.50 hourly payment. But, 5 hours in this is overwork. So, the payment goes to 10.50 X 5
So, the payment should be 498.75.
But, my program finds different sum. What is wrong with this code? (Note that I am novice)
hours = float(input("Enter hours: "))
rate = float(input("Enter rate: "))
extraPay = float((hours-40) * (rate*1.5))
def computepay(a, b, c):
paymentCalc= a * b + c
return paymentCalc
x = computepay(hours, rate, extraPay)
print(x)
you need to substract extra hours from basic hours on calculations and also add check that extra_pay will not be in negative. Do, Like this:
hours = float(45)
rate = float(10.5)
extra_hours = float(hours - 40)
extraPay = float(extra_hours * (rate*1.5))
def computepay(a, b, c, d):
if c < 0:
c = 0
payment_calc = (a - d) * b + c
return payment_calc
x = computepay(hours, rate, extraPay, extra_hours)
print(x)
The problem is that you are adding the overpay hours twice, once with the increased rate in extraPay and once in your payment calc (a is still 45).
Also, you need to check if hours are less than 40 because if it is less, extraPay will be negative and your calculation will be wrong.
Here is my suggestion:
def computepay(hours, rate):
bonus = 0
if hours>40:
overtime = hours-40
hours=40
bonus = (overtime)*rate*1.5
return hours*rate+bonus
Try:
hours = float(input("Enter hours: "))
rate = float(input("Enter rate: "))
remainder=(max(0,hours-40))
def computepay(a, b):
paymentCalc= a * b
return paymentCalc
def compute_ext(remainder,rate):
ext = remainder * (rate*1.5)
return ext
base = computepay(min(40,hours), rate)
if remainder:
base+=compute_ext(remainder,rate)
print(base)
you used all the hours instead for a max of 40 to calculate the base pay

How to loop with two conditions, in python?

I need to write a code that displays the a return of investments for 0 to 20 years or when the today's value has reached .5 * of the investment initial invested amount. I am stuck with the latter part. When I use an IF statment, I couldn't get any value. Here is my code.
def getExpInvestAmt(investAmt, i, n):
expInvestAmt = int(investAmt * pow(1 + i / 100, n))
return expInvestAmt
def getPresentValue(exp_invest_amt, d, n):
adjAmt = int(exp_invest_amt / pow(1 + d / 100, n))
return adjAmt
def main():
investAmt = float(input("Enter investment amount:"))
i = float(input("Enter the expected investment growth rate:"))
d = float(input("Enter the discount rate:"))
n = 0
adjA = 0
print("Year \t Value at year($) \t Today's worth($)")
for x in range(0, 21):
if adjA < 0.5 * investAmt
break
expected_value = getExpInvestAmt(investAmt, i, n)
present_value = getPresentValue(expected_value, d, n)
n += 1
adjA += 1
print("{} \t {:,} \t {:,}".format(x, expected_value, present_value))
main()
This is what I am suppose to get,
Enter investment amount: 10000
Enter the expected investment growth rate: 5
Enter the discount rate: 6.25
Year Value at Year($) Today's worth($)
1 10,500 9,346
2 11,025 8,734
3 11,576 8,163
4 12,155 7,629
5 12,763 7,130
6 13,401 6,663
7 14,071 6,227
8 14,775 5,820
9 15,513 5,439
10 16,289 5,083
11 17,103 4,751 # today's value have reached <= 50% of the initial amount program stops.
I think you can simplify your code; you don't need adjA or x. Where you are using adjA you should just be using present_value, and you can just iterate n over the range instead of x:
def main():
investAmt = float(input("Enter investment amount:"))
i = float(input("Enter the expected investment growth rate:"))
d = float(input("Enter the discount rate:"))
print("Year \t Value at year($) \t Today's worth($)")
for n in range(1, 21):
expected_value = getExpInvestAmt(investAmt, i, n)
present_value = getPresentValue(expected_value, d, n)
print("{} \t {:,} \t {:,}".format(n, expected_value, present_value))
if present_value < 0.5 * investAmt:
break
To get your expected results for an investAmt of 10000 and i of 5, you need a d value of 12.347528.

Yearly Interest on house and deposit

Suppose you currently have $50,000 deposited into a bank account and the account pays you a constant interest rate of 3.5% per year on your deposit. You are planning to buy a house with the current price of $300,000. The price will increase by 1.5% per year. It still requires a minimum down payment of 20% of the house price.
Write a while loop to calculate how many (integer) years you need to wait until you can afford the down payment to buy the house.
m = 50000 #money you have
i = 0.035 #interest rate
h = 300000 #house price
f = 0.015 #amount house will increase by per year
d= 0.2 #percent of down payment on house
y = 0 #number of years
x = 0 #money for the down payment
mn = h*d #amount of down payment
while m <= mn:
m = (m+(m*i)) #money you have plus money you have times interest
y = y + 1 #year plus one
mn = mn +(h*f*y)
print(int(y))
The answer you should get is 10.
I keep getting the wrong answer, but I am not sure what is incorrect.
You can simplify the code by using the compound interest formula.
def compound_interest(amount, rate, years):
return amount * (rate + 1) ** years
while compound_interest(m, i, y) < d * compound_interest(h, f, y):
y += 1
If you are allowed to do without the while loop, you can resolve the inequality after the years y.
So you get this code snippet:
import math
base = (i + 1) / (f + 1)
arg = (d * h) / m
y = math.ceil(math.log(arg, base))

Program to Simulate 2 Coins Being Flipped at the Same Time

My assignment is to create a program that simulates 2 coins being tossed at the same time. If both heads, then Group A gets a point; if both tails then Group B gets a point. If the coins are different then the Prof gets a point. The program must take 2 inputs: number of games and number of tosses per game. Here are 2 separate sample runs to illustrate:
How many games? 1
How many coin tosses per game? 100
Game 0:
Group A: 25 (25.0%); Group B: 19 (19.0%); Prof: 56 (56.0%)
Wins: Group A=0 (0.0%); Group B=0 (0.0%); Prof=1 (100.0%)
How many games? 5
How many coin tosses per game? 10
Game 0:
Group A: 3 (30.0%); Group B: 1 (10.0%); Prof: 6 (60.0%)
Game 1:
Group A: 6 (60.0%); Group B: 1 (10.0%); Prof: 3 (30.0%)
Game 2:
Group A: 4 (40.0%); Group B: 1 (10.0%); Prof: 5 (50.0%)
Game 3:
Group A: 4 (40.0%); Group B: 1 (10.0%); Prof: 5 (50.0%)
Game 4:
Group A: 5 (50.0%); Group B: 3 (30.0%); Prof: 2 (20.0%)
Wins: Group A=2 (40.0%); Group B=0 (0.0%); Prof=3 (60.0%)
My code (albeit clunky) works for taking the inputs, simulating coin tosses, and calculating and displaying the number of points per group and the percent. My problem however, is in calculating and storing the number of wins across all of the games played. Here is my code as of now:
import random
def coinFlip():
games = input("How many games? ")
tosses = input("How many coin tosses per game? ")
for i in range(games):
gA = 0
gAW = 0
gB = 0
gBW = 0
prof = 0
profW = 0
for j in range(tosses):
flip1 = random.randint(0, 1)
flip2 = random.randint(0, 1)
if (flip1 == 0 and flip2 == 0):
gA += 1
elif (flip1 == 1 and flip2 == 1):
gB += 1
else:
prof += 1
gAper = ((gA * 1.0) / tosses) * 100
gBper = ((gB * 1.0) / tosses) * 100
profper = ((prof * 1.0) / tosses) * 100
if (gA > gB and gA > prof):
gAW += 1
elif (gB > gA and gB > prof):
gBW += 1
elif ( prof > gA and prof > gB):
profW += 1
gAWper = ((gAW * 1.0) / games) * 100
gBWper = ((gBW * 1.0) / games) * 100
profWper = ((profW * 1.0) / games) * 100
print "Game {}:".format(i)
print " Group A: {} ({}%); Group B: {} ({}%); Prof: {} ({}%)".format(gA, gAper, gB, gBper, prof, profper)
print "Wins: Group A = {} ({}%); Group B = {} ({}%); Prof: {} ({}%)".format(gAW, gAWper, gBW, gBWper, profW, profWper)
I'm thinking I should store the wins in a list, but that's where I'm lost.
The critical problem is that you have reset the long-term counts at the start of every game. Thus, nobody gets to record more than one win. This works great for my Monday-night Frisbee games, but is not effective for your assignment.
Return to your psuedo-code and see where the loops and initializations match up. Here's a code version:
def coinFlip():
# Set-up you do only once per program execution
games = input("How many games? ")
tosses = input("How many coin tosses per game? ")
games_won_A = 0
games_won_B = 0
games_won_prof = 0
for i in range(games):
# Set-up things you do once per game
tosses_won_A = 0
tosses_won_B = 0
tosses_won_prof = 0
for j in range(tosses):
# Things you do every toss
flip1 = random.randint(0, 1)
flip2 = random.randint(0, 1)
...
# Summary things you do every game
# ... such as compute percentages
# Summary things you do at the end of the program execution
# ... such as print the overall totals
Does that get you moving?
BTW< note that this becomes a lot shorter if you put the counters into a list. For instance, counting the winner of each flip becomes a single line:
win_count[flip1 + flip2] += 1
win_count can be a list of three elements, recording the wins for A, prof, and B, in that order.
This probably isn't what the OP was looking for, but in general generating random numbers with numpy can accomplish this quickly and simply.
import numpy as np
# get these from input or wherever
games = 5
tosses = 10
n_coins = 2
experiment = np.random.randint(2,size=(games, tosses, n_coins))
flip_results = experiment.sum(axis=2) # 0 means group A wins, 1 Prof, 2 group B
game_results = np.stack((flip_results == 0, flip_results == 1, flip_results == 2))
game_results = game_results.sum(axis=2)
total_results = game_results.sum(axis=1)
print(game_results, total_results)

Python-Modulus-Stuck with a coin-for-given-dollar-amount scenario

Specs: Ubuntu 13.04, Python 3.3.1
General Background: total beginner to Python;
Question-specific background: I'm exhausted trying to solve this problem, and I'm aware that, besides its instructional value for learning Python, this problem is boring and does not in any way make this world a better place :-( So I'd be even more grateful if you could share some guidance on this exhausting problem. But really don't want to waste your time if you are not interested in this kind of problems.
What I intended to do: "Calculate the number of basic American coins given a value less than 1 dollar. A penny is worth 1 cent, a nickel is worth 5 cents, a dime is worth 10 cents,
and a quarter is worth 25 cents. It takes 100 cents to make 1 dollar. So given an amount less than 1 dollar (if using floats, convert to integers for this exercise), calculate the number of each type of coin necessary to achieve the amount, maximizing the number of larger denomination coins. For example, given $0.76, or 76 cents, the correct output would be "3 quarters and 1 penny." Output such as "76 pennies" and "2 quarters, 2 dimes, 1 nickel, and 1 penny" are not acceptable."
What I was able to come up with:
penny = 1
nickel = 5
dime = 10
quarter = 25
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i > 100:
print ("Please enter an amount equal or less than 100. ")
elif i >= quarter:
quarter_n = i % quarter
i = i - quarter * quarter_n
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",penny_n,"pennies")
else:
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (penny_n,"pennies")
This solution, though the best I could come up with, does not work as expected when fed with actual input numbers. And I'm unable to figure out why. Besides, I know that even from sheer size of the code that something is wrong. I searched for similar questions but the closest I got was one that dealt with very difficult math which I couldn't understand.
My question: I know I can't ask for a complete solution because that's down to me to figure it out. I'll appreciate either a) general pointer on the correct line of thinking b) critiques to my current code/line of thinking so that I might be able to improve it.
Thank you for taking the time, even just reading this!
I think your solution may actually be working if you do a "find and replace" for all the mod operators %, switching in integer division //.
Say you have 76 cents and want to find the number of quarters. Using 76 % 25 results in 1 whereas 76 // 25 is 3.
With regard to the code, you should probably be thinking in terms of iterating over the possible coin values rather than a huge if, elif mess.
Try something like this. The only part that may need some explaining is using divmod but its really just a tuple of the integer division, modulo result. You can use that to get the number of coins and the new amount, respectively.
def coins_given(amount):
coins = [(25, 'quarter'), (10, 'dime'), (5, 'nickel'), (1, 'penny')]
answer = {}
for coin_value, coin_name in coins:
if amount >= coin_value:
number_coin, amount = divmod(amount, coin_value)
answer[coin_name] = number_coin
return answer
print coins_given(76)
# {'quarter': 3, 'penny': 1}
i think your algorithm is too complicated,
you don't need all the elifs and the elses
just check with and if and then modidy the remaining amount until you get to zero
something like this
penny = 1
nickel = 5
dime = 10
quarter = 25
q = 0
d = 0
n = 0
p = 0
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i>=25:
q = i/quarter
i %= quarter
if i>=10:
d = i/dime
i%=dime
if i>=5:
n = i/nickel
i %= nickel
if i>0:
p = i/penny
i = 0
print "The coins are %i quarters, %i dimes, %i nickels and %i pennys." %(q , d, n, p)
>>>
Please enter an amount no more than 1 dollar(in cents): 99
The coins are 3 quarters, 2 dimes, 0 nickels and 4 pennys.
>>>
Please enter an amount no more than 1 dollar(in cents): 76
The coins are 3 quarters, 0 dimes, 0 nickels and 1 pennys.
dime=10
nickel=5
penny=1
quarter=25
def change(cents):
changeIs = ""
qs = cents/quarter
cents %= quarter
if qs > 0 :
changeIs += str(qs) + " quarter(s)"
ds = cents/dime
cents %= dime
if ds > 0 :
changeIs += " " + str(ds) + " dime(s)"
ns = cents/nickel
cents %= nickel
if ns > 0 :
changeIs += " " + str(ns) + " nickel(s)"
if cents > 0 :
changeIs += " " + str(cents) + " cent(s)"
return changeIs
if __name__ == '__main__':
cents=int(raw_input("Enter the change: "))
print change(cents)

Categories

Resources