Recursive counting on buy back function - python

I'm trying to create a function that is essentially a buy back program with bottles, the rules are as follows
money -> the amount of money the customer has
bottlesOwned -> the number of bottles the customer has to exchange
price -> the price of a bottle of soda pop
exchangeRate -> the exchange rate, expressed as a tuple. the first element is the minimum size of the group of bottles that can be exchanged. The second argument is the refund received for one group of bottles.
A customer may refund as many groups of bottles as they like on a single visit to the store, but the total number of bottles refunded must be a multiple of the first element of exchangeRate.
The function must output the total number of bottles which the customer is able to purchase over all trips, until the customer runs out of money.
def lightningBottle(money, bottlesOwned, price, exchangeRate):
if bottlesOwned >= exchangeRate[0]:
bottlesOwned -= exchangeRate[0]
money += exchangeRate[1]
if money >= price:
bottlesOwned += 1
bottlesbought += 1
money -= price
return lightningBottle(money, bottlesOwned, price, exchangeRate)
else:
print ("we bought",bottlesbought,"bottles")
return bottlesbought
this is as far as I've gotten but I cannot figure out how to get the bottlesbought counter to tick up without using a global variable (I can't use a global because it does not reset on concurrent tests and provides the wrong answer)

You're close. You just need bottlesbought to be an argument of your function:
def lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought=0):
if bottlesOwned >= exchangeRate[0]:
bottlesOwned -= exchangeRate[0]
money += exchangeRate[1]
if money >= price:
bottlesOwned += 1
bottlesbought += 1
money -= price
return lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought)
else:
print ("we bought",bottlesbought,"bottles")
return bottlesbought
You can give it a default value so you don't need to specify that it's equal to zero at the start (which it always is).

Related

Wriring a code in python for profitability

I need to write a program in Python using def to calculate if it would be profitable to buy a customer card for a discount or not (meaning that the purchase cost after discount + card price is less or equal to the original cost) with the following arguments: total purchase amount in euros,
discount percent with customer card and customer card price. If the card saves the customer some x amount of euros then the function should return x. If purchase + card price is more expensive than the original purchase price then return -x, where x is the number of euros it’s cheaper with the card.
The output should be something like that:
Total purchase amount: 200
Discount percent: 5
Customer card price: 5
It’s better to get a card, you will save 5 euros
So far I manage to write this code but I don't know what to do next:
def customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1):
new_price = (total_purchase amount1) * (100 - discount_percent1)/100 +
(customer_card_price1)
if new_price <= total_purchase amount1:
return customer_card_price1 - new_price
elif new_price > total_purchase amount1:
return customer_card_price1 - new_price
try:
total_purchase_amount1 - int(input("Total purchase amount"))
discount_percent1 - int(input("Discount percent"))
customer_card_price1 - int(input("Customer card price"))
You may have overthought this. If I understood it correctly, all you need is to compare the original price (without any discounts) with the new price (original price, plus card price minus customer discount). This leads to a much simpler solution:
def customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1):
new_price = (total_purchase_amount1) * (100 - discount_percent1)/100 + customer_card_price1
return total_purchase_amount1 - new_price
total_purchase_amount1 = int(input("Total purchase amount: "))
discount_percent1 = int(input("Discount percent: "))
customer_card_price1 = int(input("Customer card price: "))
print(customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1))
Example
Input: 200 / 5 / 5 -> Output: 5
Input: 200 / 5 / 15 -> Output: -5 (customer card costs more)
If I understood your question correctly, the following simple code should suffice:
def customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1):
new_price = (total_purchase_amount1) * (100 - discount_percent1)/100 + (customer_card_price1)
if new_price <= total_purchase_amount1:
return ("You save {savings} euro, you should purchase a customer card,".format(savings=total_purchase_amount1 - new_price))
else:
return ("Don't buy a card, it would cost you {cost} euro more.".format(cost=total_purchase_amount1 - new_price))
A few comments:
It may have been a typo at the time of writing your question on StackOverflow, but in your code, the total_purchase amount1 variable is missing an underscore, which would throw an error. It should be total_purchase_amount1.
Inside the if-statements, you are returning the difference between customer_card_price1 and new_price, which's not really what you're looking for? You want to compare the total purchase price with the new price.
Also, the next time you post on StackOverflow, try to include any errors that you're getting or to explain in more details what is it exactly that you're stuck on.
def profit(total_purchase,discount_percent,card_price):
discount=discount_percent / 100 * total_purchase
newpurchase= total_purchase - discount + card_price
netamount=total_purchase-newpurchase
# if netamount>0 then there would be benefit in buying card
if netamount>0:
print("Profit")
return netamount
# if netamount<=0 then there would be no benefit in buying card
print("Loss")
return netamount
print(profit(200,5,20))
Loss
Output is -10.0

Why is the function in this Parking Lot simulator program not running/producing output

I am wondering what is wrong with this code? what steps can I take to make the function and its output run? Should the variables be placed inside the function, or is there something wrong with my loops? The goal is for the function to take the 4 inputs, and then produce the output I have specified. I am getting issues with the scope of the variables. When it runs like this, I get no output. Where should I place the variables in order for them to be modified and then printed as I want them to?
#Question 1: (RUNS SOMEWHAT, SEEMS BEST)
#refer to the file Assignment 1 Q1 test for an alt version
#We are writing a function called PLSimulation, which takes 4 integers as a parameters
#param 1 (x) = minimum number of cars that can park in 1 hour
#param 2 (y) = max # than can park in 1 hour
#param 3 (z)= max that can leave in 1 hour
#param 4 (h) = # of hours to run
# variable (totalarrived) = total # of arrived cars
# variable(totalLeft) = total # of cars that left
#total_parked_cars = how many cars have park across the entire period of time
#cars_waiting_to_park = how many are in the queue
#arrival_rate = hourly arrival rate (as a % of how many can park)
#departure_rate= hourly departure rate(as a % of how many can leave)
#the function PLSsimulation indicates how many came in, how many came out
#as well as how many are waiting
import random
x=input("Enter the minimum number of cars that can park in an hour: ")
y=input("Enter the maximum number of cars that can park in an hour: ")
z=input("Enter the maximum number of cars that can leave in an hour: ")
h=input("How many hours do you want the simulation to run for?: ")
#int forms of inputs for use in PLSimulation
int_x=int(x)
int_y = int(y)
int_z = int(z)
int_h=int(h)
total_parked_cars= 0
cars_waiting_to_park = 0
totalarrived=0
totalLeft=0
arrival_rate= (totalarrived/(int_h*int_y))
departure_rate= (totalLeft/(int_h*int_z))
#Goal 1: During the course of the function, the program should do h-1, until h==0, then break
#This will be create a loop that runs the program until there are no more hours left
def PLSimulation(int_x,int_y,int_z,int_h):
total_hours = h
int_total_hours = int(total_hours)
while(int_total_hours>0):
#This while loop that goes from total_hours to 0 accomplishes goal 1
#my aim is to loop the function of each hour, then subratcted from the total
#until 0 is hit
for hour in range(0,int_h+1):
#This part generates the number of cars ready to arrive/leave per hour:
arrived_in_the_hour= random.randrange(int_x,int_y+1)
left_in_the_hour = random.randrange(0,int_z+1)
#This part adds the cars which arrived/subtracts the cars which left to the total arrived:
totalarrived += arrived_in_the_hour
totalarrived -= left_in_the_hour
#This part adds the cars which left/subtracts the cars which arrived to the total left:
totalLeft += left_in_the_hour
totalLeft -= arrived_in_the_hour
#adds the arrived in the hour to waiting to park/the queue every hour:
cars_waiting_to_park+= arrived_in_the_hour
#removes the cars that left from the queue:
cars_waiting_to_park-= left_in_the_hour
#adds the cars parked to the total parked:
total_parked_cars+= cars_waiting_to_park
#removes the now parked cars from the queue:
cars_waiting_to_park -=total_parked_cars
int_total_hours += int_h-1
#here, when total_hours ==0 and the while loop ends, print the report
#call the function so that it runs
PLSimulation(int_x,int_y,int_z,int_h)
print("The simulation is complete!\n The car arrival rate is: ", arrival_rate,
"\nThe car departure rate is: ", departure_rate,
"\nThe number of cars waiting to park is: ",cars_waiting_to_park)

How do I solve this MIT problem to find the months required to buy a house

I just picked up coding for the first time and started with the MIT free intro to python course. I am on the first problem of the second homework and I am having a hard time figuring out how to solve. I saw some other posts about this but I think it would be way easier to learn if someone could show me how to do it with my code rather than anothers.
This is the problem:
You have graduated from MIT and now have a great job! You move to the
San Francisco Bay Area and decide that you want to start saving to buy
a house. As housing prices are very high in the Bay Area, you realize
you are going to have to save for several years before you can afford
to make the down payment on a house. In Part A, we are going to
determine how long it will take you to save enough money to make the
down payment given the following assumptions:
Call the cost of your dream home total_cost.
Call the portion of the cost needed for a down payment portion_down_payment. For simplicity, assume that portion_down_payment
= 0.25 (25%).
Call the amount that you have saved thus far current_savings. You start with a current savings of $0.
Assume that you invest your current savings wisely, with an annual return of r (in other words, at the end of each month, you receive an
additional current_savings*r/12 funds to put into your savings – the
12 is because r is an annual rate). Assume that your investments earn
a return of r = 0.04 (4%).
Assume your annual salary is annual_salary.
Assume you are going to dedicate a certain amount of your salary each month to saving for the down payment. Call that portion_saved.
This variable should be in decimal form (i.e. 0.1 for 10%).
At the end of each month, your savings will be increased by the return on your investment, plus a percentage of your monthly salary
(annual salary / 12). Write a program to calculate how many months it
will take you to save up enough money for a down payment. You will
want your main variables to be floats, so you should cast user inputs
to floats.
Here is my code so far:
total_cost = float(input("What is the cost of the home? "))
annual_salary = float(input("What is your annual salary? "))
portion_saved = float(input("How much would you like to save per year? "))
portion_down = (total_cost*.25)
current_savings = 0
monthly_salary = (annual_salary/12)
interest_rate = .04
#goal is to loop up until I have enough for the down payment
print (total_cost)
print (annual_salary)
print (portion_saved)
print ("The downpayment required for this house is", portion_down)
#need to use +=, otherwise you would have to do current saving = current savings + 1
months = 1
while current_savings < portion_down:
current_savings += current_savings*(.4/12) #monthly interest
current_savings += portion_saved #monthly savings
months += months + 1
print ("It will take", months, "months to save the needed down payment of", portion_down)
You did a pretty good job.
The biggest problem I see in your code is:
months += months + 1
You need to change it to:
months +=1
I also made some tweaks in your code, but essentially I kept the same idea:
total_cost = float(input("What is the cost of the home? "))
monthly_salary = float(input("What is your monthly salary? "))
#portion_saved = float(input("How much would you like to save per year? "))
portion_down = (total_cost*.25)
current_savings = 0
interest_rate = 0.04
months = 1
portion_saved = 0.1
print ("The downpayment required for this house is", portion_down)
while current_savings < portion_down:
current_savings += current_savings(interest_rate/12)+portion_saved*monthly_salary
months +=1
print ("It will take", months, "months to save the needed down payment of",portion_down)

python code for irs_reward(money_recovered)

IRS informants are paid cash rewards based on the value of the money recovered. If the information was specific enough to lead to a recovery, the informant receives
10% of the first $75,000 plus
5% of the next $25,000 plus
1% of the remainder up to a maximum reward of $50,000.
The following function accepts the amount of money recovered and returns the reward.
to run tests: python3 -m doctest irs_reward.py -v
'''def irs_reward(money_recovered):
IRS informants are paid cash rewards based on the value of the money recovered
calculate reward amount from money recovered
args:
money_recovered (float): dollar value of money recovered
returns:
the dollar value of the reward (float)
formula:
10% of the first $75k
+ 5% of the next $25k
+ 1% of the rest, up to max total reward of $50k
examples/doctests:
no money recovered
>>> round(irs_reward(0), 2)
0.0
$75k recovered
>>> round(irs_reward(75000), 2)
7500.0
$95k recovered
>>> round(irs_reward(95000), 2)
8500.0
$200,000 recovered
>>> round(irs_reward(200000), 2)
9750.0
$42 milliion recovered, max out at $50k reward
>>> round(irs_reward(42000000), 2)
50000.0
# TO DO: Add your code here #
# ========================= #
return
Can someone help me with the code. I have tried 5 to 6 times and finally closed out the program and did not save it.
You should learn how this works, not just get people to do your homework for you, but here goes:
def calculate_reward(money_recovered):
reward = 0
if money_recovered >= 4125000:
reward = 50000
elif money_recovered >= 100000:
reward = (money_recovered - 100000)/100 + 8750
elif money_recovered >= 75000:
reward = (money_recovered - 75000)/20 + 7500
else:
reward = money_recovered/10
return reward
The reason for the number 4125000 is because thats the number needed to make the total reward 50k. It is 10% of 75k + 5% of 25k + 1% of the rest, which makes the remaining 41.25k.
The next barrier is 100k since that is 25k + 75k, so things above that but below 4125000 get taxed 1%, and each time we check for the money being over a barrier we add the max they received from lower amounts.

how to re-initiate iteration after changing a variable

I am learning python and CS via the MIT OCW material. Doing this for fun btw because I think its interesting. I am trying to tackle a problem set where for a given credit card balance (ex. $1200) and interest rate (18%), what would minimum monthly payment need to be pay it off completely in 12 months or less. Start with $100 and if more or less is needed, change it increments of $10. In my code below, if the initial start of $100 doesnt work, i dont know how to increase it by 10 and THEN start iterating again. Im not even sure starting with a "While" is the best approach. Im sure the pros could code this up in like 2 lines but I would appreciate if anyone were to help, they do it the long way so a novice like myself could follow it.
balance = float(input("Enter the outstanding balance on your credit card:"))
annual_rate = float(input("Enter the annual credit card interest rate as a decimal:"))
monthly_interest_rate = annual_rate / 12.0
minimum_monthly_payment = 100
updated_balance_each_month = balance * (1 + monthly_interest_rate) - minimum_monthly_payment
month = 1
while month <= 12:
month += 1
updated_balance_each_month = updated_balance_each_month * (1 + monthly_interest_rate) - minimum_monthly_payment
if updated_balance_each_month <= 0:
print ("Monthly payment to pay off debt in 1 year:", minimum_monthly_payment)
print ("Number of months needed:",month)
print (round(updated_balance_each_month,2))
break
else:
minimum_monthly_payment += 10
So in programming you can create functions. These are blocks of code that you can call from elsewhere that will execute what you put in them. For python the syntax looks like...
def function_name(parameter1, parameter2, parameterN):
#function code here
#optional return statement
return parameter1 + parameter2
So what you could try is putting your while loop inside a function and if the while loop is successful, return true, and if it fails return false. Then in your main you can choose to redo the function if it returns false. So here is an example of how you could fix your problem.
def try_to_pay_off(payment, interest_rate, start_balance):
month = 0
updated_balance = start_balance
while month <= 12:
month += 1
updated_balance = updated_balance * (1 + interest_rate) - payment
if updated_balance <= 0:
return True
# will return false if it goes through 12 months and debt not payed off
return False
def Main():
balance = float(input("Enter the outstanding balance on your credit card:"))
annual_rate = float(input("Enter the annual credit card interest rate as a decimal:"))
done = False
monthly_payment = 100
while not done:
if try_to_pay_off(monthly_payment,annual_rate,balance):
done = True
else:
monthly_payment += 10
# after finding the monthly payment required
print ("Monthly payment to pay off debt in 1 year:", monthly_payment)
This way you keep running your function with new values until it finds a monthly payment that can pay off your balance with interest rate in one year.
First off, welcome to StackOverflow, and I hope you enjoy the world of programming. I have heard MIT OCW is a great resource, so best of luck to you and whatever you're going to do.
If I understand the question correctly, you must find the smallest minimum payment (which is the same across all twelve months) that will pay off the debt. (I currently don't have commenting privileges, so if I misunderstand the question, I'd appreciate it if you clarified.)
To answer your question in the title, to "re-initiate iteration," you would create a second loop outside the first. Here's some example code.
# given balance and annual_rate
monthly_interest_rate = annual_rate / 12.0
minimum_monthly_payment = 100
# debt_is_paid_off is a use for a variable called a one-way flag
debt_is_paid_off = False
while not debt_is_paid_off:
updated_balance_each_month = balance
# range is a neat little python trick to go from 1 to 12 easily
for month in range(1, 13):
# update the balance
updated_balance_each_month *= (1 + monthly_interest_rate)
updated_balance_each_month -= minimum_monthly_payment
# check if it's paid off
if updated_balance_each_month <= 0:
debt_is_paid_off = True
print ("Monthly payment to pay off debt in 1 year:",
minimum_monthly_payment)
print ("Number of months needed:",month)
print (round(updated_balance_each_month,2))
# note that this only breaks out of the for-loop.
# so we need debt_is_paid_off to exit out.
break
minimum_monthly_payment += 10
Note how there are two loops in the code. The outer loop keeps increasing which minimum payment to try until the debt is paid off, and the inner loop simulates paying off the debt by repeating twelve times.
However, the standard approach - just using the "break" keyword, as you did - doesn't work in Python if there are two loops. It only breaks out of the first. So we use this new variable, debt_is_paid_off, to get us out of that second loop.
ok thanks guys for the help but I ended up coming up with a solution myself (!!!). I figured out that in the code I originally posted, it would do the calculation for month 1 then check to see if updated_balance_each_month was less than 0 and if not increase monthly minimum by 10 for each month after that until balance was equal to or below 0 instead of running through all 12 months and then increasing monthly minimum by 10. so you can see that I added another IF statement so that monthly minimum only increased if month == 12 and balance was above 0 and it worked! Now, can anyone tell me how I can add code here so that it shows up properly? I click on the {} and then paste my code where it says so but it always comes up jumbled...
balance = float(input("Enter the outstanding balance on your credit card:"))
annual_rate = float(input("Enter the annual credit card interest rate as a decimal:"))
monthly_interest_rate = annual_rate / 12.0
minimum_monthly_payment = 100
updated_balance_each_month = balance * (1 + monthly_interest_rate) - minimum_monthly_payment
month = 1
while month <= 12:
month += 1
updated_balance_each_month = updated_balance_each_month * (1 + monthly_interest_rate) - minimum_monthly_payment
if updated_balance_each_month <= 0:
print ("Monthly payment to pay off debt in 1 year:", minimum_monthly_payment)
print ("Number of months needed:",month)
print (round(updated_balance_each_month,2))
break
if month == 12 and updated_balance_each_month > 0:
minimum_monthly_payment += 10
month = 0
updated_balance_each_month = balance

Categories

Resources