I am trying to produce a list that is recursively populated taking input from a method variable. (I believe)
My code:
class Register:
cur_unit = [100, 50, 20, 10, 5, 1, .25, .10, .05, .01]
reg_amount = []
def load_reg(self):
self.reg_amount = float(input('Enter amount of money in register...\n'))
def transaction(self):
trans_amount = float(input('Enter the cost of the transaction...\n'))
if trans_amount > self.reg_amount:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
cash_paid = float(input('Enter how much money you will pay with...\n'))
change_due = cash_paid - trans_amount
new_reg_amount = self.reg_amount - change_due
if new_reg_amount < 0:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
new_reg_amount = round(new_reg_amount, 2)
change_due = round(change_due, 2)
print('\n' + str(new_reg_amount))
print(change_due)
for i in self.cur_unit:
if change_due - i >= 0:
return [i] + [cash_paid - i]
reg = Register()
reg.load_reg()
res = reg.transaction()
print(res)
Result which produces an undesirable result:
Enter amount of money in register...
200
Enter the cost of the transaction...
24.24
Enter how much money you will pay with...
50
174.24
25.76
[20, 30.0] # undesired result
Process finished with exit code 0
Desired result which would run through cur_unit and bring back each unit if the unit can be subtracted from cash_paid without change_due being equal to or less than 0: (this is for more details needed)
[20, 5, .25, .25, .25, .01]
As Prune pointed out in the comments, this problem is better solved by iteration than with recursion. I wrote methods to do it either way in case you were curious: split_change_r is a recursive function and split_change is a cleaner iterative solution. Note that they assume your cur_unit list is already sorted.
class Register:
cur_unit = [100, 50, 20, 10, 5, 1, .25, .10, .05, .01]
reg_amount = []
def load_reg(self):
self.reg_amount = float(input('Enter amount of money in register...\n'))
def split_change_r(self, amount, l = []):
next_cur = [a for a in self.cur_unit if a <= amount][0]
if next_cur == amount:
return l + [next_cur]
else:
# here is the recursive call
return self.split_change_r(round(amount - next_cur, 2), l + [next_cur])
def split_change(self, amount):
r = []
while(amount != 0):
next_cur = [a for a in self.cur_unit if a <= amount][0]
amount = round(amount - next_cur, 2)
r.append(next_cur)
return r
def transaction(self):
trans_amount = float(input('Enter the cost of the transaction...\n'))
if trans_amount > self.reg_amount:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
cash_paid = float(input('Enter how much money you will pay with...\n'))
change_due = cash_paid - trans_amount
new_reg_amount = self.reg_amount - change_due
if new_reg_amount < 0:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
new_reg_amount = round(new_reg_amount, 2)
change_due = round(change_due, 2)
print('\n' + str(new_reg_amount))
print(change_due)
return self.split_change(change_due)
reg = Register()
reg.load_reg()
res = reg.transaction()
print(res)
Example output:
Enter amount of money in register...
200
Enter the cost of the transaction...
24.24
Enter how much money you will pay with...
50
174.24
25.76
[20, 5, 0.25, 0.25, 0.25, 0.01]
Related
I am trying to create a fine amount calculator, but I don't know how to add a surcharge to the calculations.
For each fine amount in the code, I need to add a victims surcharge that varies depending on fine amount. If the fine amount is between $0 and $99 surcharge is $40, between $100 and $200 surcharge is $50, $201 and $350 surcharge is $60, $351 and $500 surcharge is $80, and over $500 surcharge is 40%.
Any suggestions for the best way to implement this into my current code?
thank you!
def ask_limit():
limit = float(input ("What was the speed limit? "))
return limit
def ask_speed():
speed = float(input ("What was your clocked speed? "))
return speed
def findfine(speed, limit):
if speed > 35 + limit :
over35fine = ((speed - limit) * 8 + 170)
print("Total fine amount is:", over35fine)
elif speed > 30 + limit :
over30fine = ((speed - limit) * 4 + 100)
print("Total fine amount is:", over30fine)
elif speed > limit :
normalfine = ((speed - limit) * 2 + 100)
print("Total fine amount is:", normalfine)
elif speed <= limit:
print("No fine, vehicle did not exceed allowed speed limit.")
def main():
limit = ask_limit()
speed = ask_speed()
findfine(speed, limit)
main()
You can add a function to do that based on the fine value:
def ask_limit():
limit = float(input ("What was the speed limit? "))
return limit
def ask_speed():
speed = float(input ("What was your clocked speed? "))
return speed
def findfine(speed, limit):
if speed > 35 + limit :
return ((speed - limit) * 8 + 170)
elif speed > 30 + limit :
return ((speed - limit) * 4 + 100)
elif speed > limit :
return ((speed - limit) * 2 + 100)
elif speed <= limit:
0
def findSurcharge(fine):
if fine < 100:
return 40
elif fine < 200:
return 50
elif fine < 350:
return 60
elif fine < 500:
return 80
elif fine > 500:
return fine * 0.4
else:
return 0
def main():
limit = ask_limit()
speed = ask_speed()
fineAmount = findfine(speed, limit)
surcharge = findSurcharge(fineAmount)
print(f"fine: {fineAmount}, surcharge: {surcharge}")
main()
now you can print your message in the main function based on the surcharge and fine amount.
Note: adjust the if-elses in the findSurcharge function if they are not correct.
Just wanted to know let's say
Person 1: Paid 66USD
Person 2: Paid 0USD
Person 3: Paid 33USD
How do I program it in a way that it sends a table that tells person 2 has to pay 33USD TO person 1 to settle an equal balance amongst all members?
print('How many people in total')
people_num = int(input())
#Get the name list of everyone
name_list = []
for num in range(0,people_num):
print("What are their names?")
name_list.append(input())
print(name_list)
#get the amount everyone paid
amount = []
for name in name_list:
print("How much did " + name + " pay?")
amount.append(float(input()))
total_amount = sum(amount)
print(total_amount)
#create empty dictionary to calculate how much one person has to pay or receive
owe = []
for x in amount:
owe.append(round(x - (total_amount/people_num),2))
info = {}
for name, amt_owe in zip(name_list,owe):
info[name] = amt_owe
print(info)```
Here is a solution
def find_transactions(info):
for i in info.keys():
# find a negative balance : user A
if info[i] < 0:
for j in info.keys():
# find a positive balance : user B
if info[j] > 0 and i != j:
# user A will pay user B
x = abs(info[i])
if x > info[j]:
x = abs(info[j])
# change values of balances of user A and B
info[j] = info[j]-x
info[i] = info[i]+x
print(f"{i} pay {x} to {j}")
return info
Let's try with different values
people_num = 3
name_list = ["a", "b", "c"]
amount = [66, 0, 33]
in : info = {'a': 33.0, 'b': -33.0, 'c': 0.0}
out :
b pay 33.0 to a
info = {'a': 0.0, 'b': 0.0, 'c': 0.0}
amount = [66, 33, 33]
in : info = {'a': 22.0, 'b': -11.0, 'c': -11.0}
out :
b pay 11.0 to a
c pay 11.0 to a
info = {'a': 0.0, 'b': 0.0, 'c': 0.0}
The simple solution to this would be to count person's balance iterating through a list.
def process_transaction(from_user, to_user, amount):
if from_user['balance'] >= amount:
to_user['balance'] += amount
from_user['balance'] -= amount
print("Transaction success")
else:
print("Transaction failed")
bob = {"balance":100}
alice = {"balance":50}
process_transaction(bob, alice, 50)
print(bob)
print(alice)
does this help you ?
def info():
return {_name: _amount for _name, _amount in zip(name_list, amount)}
def equal_balances(_info):
# Make the transaction between sender and receiver
def transaction(payment_amount):
# print(f"balance before payment: {sender}: {round(_info[sender])}, {receiver}: {round(_info[receiver])}")
_info[receiver] += payment_amount
_info[sender] -= payment_amount
print(f"{sender} pay {round(payment_amount, 2)} to {receiver}")
# print(f"balance after payment: {sender}: {round(_info[sender])}, {receiver}: {round(_info[receiver])}")
medium_amount = total_amount / people_num # get medium amount
# get hwo pay hwo
print(f'The medium amount is: {round(medium_amount, 2)}')
for sender in _info:
if _info[sender] > medium_amount:
for receiver in _info:
if _info[sender] > medium_amount > _info[receiver]:
receiver_need = medium_amount - _info[receiver]
if _info[sender] - receiver_need < medium_amount:
transaction(_info[sender] - medium_amount)
elif _info[sender] >= receiver_need:
transaction(receiver_need)
elif _info[sender] - receiver_need == medium_amount:
transaction(_info[sender] - medium_amount)
return _info
people_num = int(input('How many people in total? '))
# Get the name list of everyone
name_list = []
for num in range(0, people_num):
name_list.append(input('What are their names? '))
print(name_list)
# get the amount everyone paid
amount = []
for name in name_list:
amount.append(float(input(f'How much did {name} pay? ')))
total_amount = sum(amount)
print(total_amount)
people_info = info()
print(people_info)
people_info = equal_balances(people_info)
print(people_info)
I have been experimenting with creating an investment calculator, and I want to print the annual totals as well as the annual compounded interest. It's doing the annual totals fine, but not the annual interest. My inputs are $10000.00 principle, at 5% interest over 5 years.
start_over = 'true'
while start_over == 'true':
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate"))
addition = int(input("Type annual Addition"))
time = int(input("Enter number of years to invest"))
real_rate = rate * 0.01
i = 1
print('total', principle * (1 + real_rate))
while i < time:
principle = (principle + addition) * (1 + real_rate)
i = i + 1
print('total', principle)
for i in range(time):
amount = i * (((1 + rate/100.0) ** time)) * principle
ci = amount - principle
i += 1
print("interest = ",ci)
redo_program = input('To restart type y or to quit type any key ')
if redo_program == 'y':
start_over = 'true'
else:
start_over = 'null'
Here are my outputs:
Type the amount you are investing: 10000
Type interest rate5
Type annual Addition0
Enter number of years to invest5
total 10500.0
total 10500.0
total 11025.0
total 11576.25
total 12155.0625
interest = -12155.0625
interest = 3358.21965978516
interest = 18871.50181957032
interest = 34384.78397935548
interest = 49898.06613914064
To restart type y or to quit type any key
Give this a go:
# Calculate year's values based on inputs and the current value of the account
def calc(current, addition, rate, year):
multiplier = 1 + rate/100 # The interest multiplier
new_total = (current + addition) * multiplier # Calculate the total
interest = round((new_total - current - addition), 2) # Interest to nearest penny/cent
return new_total, interest
def main():
# Inputs
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate: "))
addition = int(input("Type annual Addition: "))
invst_time = int(input("Enter number of years to invest: "))
# Sets current account value to principle
current = principle
# Prints values for each year of investment
for i in range(invst_time):
total, interest_gained = calc(current, addition, rate, i+1)
print("At the end of Year: ", i+1)
print("Total: ", total)
print("Interest: ", interest_gained)
print("------")
current = total # Updates value of account
# Restart Program check
while 1:
repeat_choice = input("Would you like to restart and check with different values? (Y/N)")
if repeat_choice == "Y":
main()
elif repeat_choice == "N":
print("Thanks for using the calculator")
break
else:
print("Enter Y or N!") # Error handler
continue
main()
I dont understand why the code doesnt work and they have repeated the questions to me 4 times. and say that float is not callable. i have tried doing this for quite awhile but i dont seem to get anything at all. is there any easier way for python3? I just learnt this language 2 weeks ago. its not a whole new world to me but many of the things i am not familiar with. such as indentation
def get_taxi_info():
flag_down = float(input("What's the flag-down fare: $"))
within = float(input("What's the rate per 400 meters within 9.8km? $"))
beyond = float(input("What's the rate per 350 meters beyond 9.8km? $"))
distance = float(input("What's the distance traveled (in meters)? "))
peak = input("Is the ride during a peak period? [yes/no]")
mid6 = input("Is the ride between midnight and 6am? [yes/no]")
location = input("Is there any location surcharge? [yes/no]")
surloca = float(input("What's the amount of location surcharge?"))
return (flag_down, within, beyond, distance, peak == 'yes', mid6 == 'yes', location == 'yes', surloca)
def calculate_taxi_fare():
dist = get_taxi_info()
if dist[3] > 9800:
extra = (dist[3] - 9800) % 350
if extra == 0:
a = (extra//350) + 22
else:
a = (extra//350) + 23
return a
elif dist[3] <= 9800:
extra = (dist[3] - 1000) % 400
if extra == 0:
a = (extra//400)
else:
a = (extra//400) + 1
return a
def peakornot():
peak = get_taxi_info()
if peak[4] == True and peak[5] == False:
surcharge = 1.25
return surcharge
elif peak[4] == False and peak[5] == True:
surcharge = 1.50
return surcharge
taxifare = calculate_taxi_fare()
info = get_taxi_info()
peak1 = peakornot()
taxifare = calculate_taxi_fare()
if info[6] == True:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
elif info[6] == False:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
The function calculate_taxi_fare returns a float, so on this line taxifare is a float
taxifare = calculate_taxi_fare()
Therefore you cannot say taxifare() because it looks like a function call, so you can just use for example
info[1] * taxifare
I just started learning Python and I would really appreciate some advice on this.
When I try to save the last total in the 'total_price' list, it doesn't save.
What am I doing wrong?
Also, are there any better ways to write this?
Thank you
price_list = {'gold': 10,
'red': 20,
'brown': 30
}
vol_list = {'gold': 0.1,
'red': 0.2,
'brown': 0.3
}
cl_list = {'gold': 100,
'red': 200,
'brown': 300
}
while True:
print("What do you want to buy?")
choice = input("Choices: gold, red or brown > ")
amount = int(input("How many do you want? >"))
price = price_list[choice] * amount
vol = (cl_list[choice] * amount) * vol_list[choice]
total_price = []
total_vol = []
total_price.append(price)
total_vol.append(vol)
print_price = sum(total_price[:])
print_vol = sum(total_vol[:])
print("-" * 10)
print("Your total is now: ", print_price)
print("Your total vol is now: ", print_vol)
print("-" * 10)
cont = input("Do you want to continue shopping [Y/n]?> ")
if cont == "n" or cont == "no":
print("#" * 10)
print("#" * 10)
print("Your total is: ", print_price)
print("Your total vol is: ", print_vol)
print("#" * 10)
print("#" * 10)
break
You are Initializing your arrays in your while loop, so on every new iteration the old total_price gets overwritten.
Initialize your arrays before you loop
total_price = []
total_vol = []
while True:
...