Thinkpython book exercise - python

price_book = 24.95
number_books = 60.0/100
first_book_cost = 3
additional_copy = 0.75
discounted_books = price_book*number_books
total_price = discounted_books*(first_book_cost*1+additional_copy*(60-1))
print "The total price of 60 copies of book is %s$."%(total_price)
Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
Could someone please tell me what am I doing wrong!!
The answer should be 523.23, and I am getting 707.33!
Thank you in advance!

Sometimes books, especially free ones, have typos and errors.
According to the information you provided, the total wholesale cost should be:
>>> cover_price_of_book = 24.95
>>> shipping_cost_for_first_book = 3.00
>>> shipping_cost_for_additional_books = 0.75
>>> wholesale_cost_of_book = 24.95 * .60
>>> total_number_of_books = 60
>>> total_wholesale_cost = (wholesale_cost_of_book * total_number_of_books) + (shipping_cost_for_first_book + (total_number_of_books - 1) * shipping_cost_for_additional_books)
total_wholesale_cost
945.4499999999

The question here isn't very clearly stated.
Do they get a 40% discount on order total/book cost/etc.?
I modeled what I thought you were asking, but I cannot come close to 523.23.
In fact, all books being 40% discounted to 14.97 * 60, comes to 898.20 before shipping costs.
#first book costs 24.95
book_cost = 24.95
#they order 60 books
number_books = 60
#shipping cost of book 1 is $3
ship1_cost = 3
#shipping cost for subsequent books is 0.75
ship_cost = 0.75
#print (book 1 + shipping) + (subsequent book qty (59) * unit price) + (subsequent shipping costs (59 * 0.75))
print (book_cost + ship1_cost + ((number_books - 1) * book_cost) + ((number_books - 1) * ship_cost))

Related

Calculating returns with trading costs

This perhaps is an over simplification of calculating trading returns while including trading costs. I've made some assumptions - the commission for investing and extracting an investment is 1% and 2% respectively. The commissions do not change over the trading period which in this case is 5 time steps. I've used Python code to perform the calculations.
Set of positive and negative percentage changes in price for a given asset over 5 time steps is {0.031% , 0.00121% , 0.0231% , -0.0213% , -0.0121%}.
The commission to enter an investment is 1% of the invested amount, the commission to exit an investment is 2% of the current value of the invested amount.
If I invest 1 euro in this asset, is the following correct?
1.
The final investment amount if I do not trade the investment until $t=5$ is:
the final percentage change amount at $t=5$ which is 'initial invested amount' + '% change' - 'commission to enter' - 'commission to exit', therefore:
initial_investment_amt = 1
comission_in_amt = 1
comission_out_amt = 2
price_change = -.0121
return_amt = (initial_investment_amt + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100) = 0.97 which represents a loss of 1 - .97 = .03
2.
The final investment amount if I trade the investment at each time step until $t=5$ is:
initial_investment_amt = 1
comission_in_amt = 1
comission_out_amt = 2
price_change = .031
return_amt_1 = (initial_investment_amt + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = .00121
return_amt_2 = (return_amt_1 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = .0231
return_amt_3 = (return_amt_2 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = -.0213
return_amt_4 = (return_amt_3 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = -.0121
return_amt_5 = (return_amt_4 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
print(return_amt_1)
print(return_amt_2)
print(return_amt_3)
print(return_amt_4)
print(return_amt_5)
prints :
0.97031
0.9403220999999999
0.9105530999999999
0.8803400999999998
0.8502190999999998
which represents a loss of $1 - 0.85 = 0.15$.
First, I have to respectfully disagree with your conclusion for case 1:
The final investment amount if I do not trade the investment until $t=5$ is: the final percentage change amount at $t=5$ which is 'initial invested amount' + '% change' - 'commission to enter' - 'commission to exit
The correct formula for the final value, I believe, is
((initial investment amount - commission to enter) * (1 + % change)) - commission-to-exit.
The main difference being the fact that the commission to enter/investment fee is taken out of circulation before the return on investment can be earned. This makes for a significant difference over time.
Assuming I'm correct, below is the code I propose. I took the liberty of changing some of the terminology for ease of reference, but you can obviously change it to whatever suits you:
p_changes = [0.03100, 0.00121, 0.02310, 0.02130, -0.01210]
initial_investment_amt = 100 #I used a larger initial investment; otherwise, the fees would have eaten you alive...
invest_fee = 1
sell_fee = 2
def periodic_ret(amount,change,reinv):
if reinv == 0:
if ind + 1 == 1: #for the initial period
forward = (amount-invest_fee)*(1+change)
if ind +1 == len(p_changes): #for the final period
forward = (amount*(1+change))-sell_fee
else:
forward = (amount*(1+change))
else:
forward = (amount-invest_fee)*(1+change)-sell_fee
print(forward)
return forward
for i in range(len(p_changes)):
reinv = 1 #1 if an invest and sell fee are paid each period, or 0, if an invest fee is paid once upfront and sell fee is paid once at the end
if i == 0: #for the initial period
cur = periodic_ret(initial_investment_amt, p_changes[0], reinv)
else:
cur = periodic_ret(cur,p_changes[i], reinv)
Output (w/ reinv = 1):
100.06899999999999
97.18887348999998
96.41083646761896
95.44308728437926
91.30032592823827
Both the commissions and price changes are given as percentages. This means that immediately after investment the amount in the account is:
initial_investment_amt*(1-commission_in_amt/100)
The _amt suffix is perhaps confusing but commission is stated as % in the question.
After the first investment period the account has the amount:
initial_investment_amt*(1-commission_in_amt/100)*(1-price_change/100)
And finally after exit the client receives:
initial_investment_amt*(1-commission_in_amt/100)(1-price_change/100)(1-commission_out_amt/100)
I think the pattern is clear so you just insert more price_changes for a lengthier investment and if you disinvest and reinvest you'll have a lot more commission to pay.
Hope this is OK - sorry no code - but it seems clearer like this and uses the question notation.

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))

Figuring out money change in python

I have an assignment where I have to prompt the user for cost of a product and amount paid, I have to output change in pennies, dimes, quarters, $1, $5, $20, $50, and $100, for example: The cost of the item is $19.99 and the client pays with a $50 bill. The change to be provided is 1 $20 bill, one $10 bill, and one penny.
I am confused how to get an output like that though, any help would be greatly appreciated, heres what I have so far
cost = float(input('Cost: '))
amount_paid = float(input('Amount paid: '))
penny = 0.01
dime = 0.10
quarter = 0.25
dollar_1 = 1.00
dollar_5 = 5.00
dollar_10 = 10.00
dollar_20 = 20.00
dollar_50 = 50.00
dollar_100 = 100.00
change = cost - amount_paid
if amount_paid < cost:
print('Error')
I dont know what to do next
A common misstep here is to use floats. You should instead convert everything to the smallest whole unit (a cent) and use integer math. Floating point math is...fuzzy.
currencies = {"penny": 1,
"nickel": 5,
"dime": 10,
"quarter": 25,
"dollar": 1_00,
"five": 5_00,
"ten": 10_00,
"twenty": 20_00,
"fifty": 50_00,
"hundred": 100_00}
# never seen that numeric notation before? It's safe to embed underscores
# in numerical literals! It's often used for large numbers in place of
# commas, but it makes sense here in place of a period.
Then you should only need to define a dictionary for the result, and use divmod to find how many of the denomination can fit in the amount left due.
change_due = {}
for denomination, amt in reversed(currencies.items()):
if amt < amt_due:
d, m = divmod(amt_due, amt)
change_due[denomination] = d
amt_due = m
welcome to stackoverflow! I wrote the code for you and this is how it works. Basically it sees each currency and uses integer division // to see how many integers can fit in. It then subtracts that amount from the remaining change and the process continues. Please ask if you don't understand something, or if you think there is an error.
Code:
cost = float(input('Cost: '))
amount_paid = float(input('Amount paid: '))
penny = 0.01
dime = 0.10
quarter = 0.25
dollar_1 = 1.00
dollar_5 = 5.00
dollar_10 = 10.00
dollar_20 = 20.00
dollar_50 = 50.00
dollar_100 = 100.00
changeTypes = {dollar_100:0,dollar_50:0,dollar_20:0,dollar_10:0,dollar_5:0,dollar_1:0,quarter:0,dime:0,penny:0}
change = amount_paid-cost
if amount_paid < cost:
print('Error: InsufficientFunds')
for changeType in changeTypes:
numAmount = max(0,change//changeType)
change-=numAmount*changeType
changeTypes[changeType] = int(numAmount)
print(changeTypes)
P.S you should make this a function, it shouldn't be too hard.
You could do this good with dictionaries, but without using still there are many ways to go about this, options are endless, heres one idea
def get_bills(change, value):
if change//value > 0:
bills = change//value
change -= bills * value
return bills, change
else:
return 0, change
cost = float(input('Cost: '))
paid = float(input('Amount Paid: '))
while paid < cost:
paid = float(input('Amount Paid: '))
change = paid - cost
hundreds, change, = get_bills(change, 100)
fifties, change, = get_bills(change, 50)
twenties, change = get_bills(change, 20)
tens, change = get_bills(change, 10)
fives, change = get_bills(change, 5)
ones, change = get_bills(change, 1)
quarters, change = get_bills(change, .25)
dimes, change = get_bills(change, .1)
nickels, change = get_bills(change, .05)
pennies = round(change * 100)
print(f"Hundreds: {hundreds}, Fifties: {fifties}, Twenties: {twenties}," +
f" Tens: {tens}, Fives: {fives}, Ones: {ones}, Quarters: {quarters}," +
f" Dimes: {dimes}, Nickels: {nickels}, Pennies: " +
f"{pennies}")
bill = float(input())
paid = float(input())
Available = {100.0:0,50.0:0,20.0:0,10.0:0,5.0:0,1.0:0,0.25:0,0.10:0,0.01:0}
due = paid-bill
for change in sorted(Available,reverse = True):
amt= max(0,due//change)
due-=amt*change
Available[change] = int(amt)
print(Available)
I know this is a late response but maybe it can help someone.
Below is a code for doing exactly what you want. The program iterates through the notes available from largest to smallest and calculates how many times the current note may be used to deduct from the remaining change to be given.
Finally returning a list containing the notes used to reach the sum required.
# Available notes for change
notes = [500, 200, 100, 50, 20, 10]
def change_notes(change, notes):
notes_out = []
for note in notes:
print(f"current note is {note}")
sleep(1)
while change > 0 and note <= change:
if change - note >= 0:
change -= note
notes_out.append(note)
print(f"change is {change}")
sleep(1)
if change == 0:
break
return notes_out

I can't understand how this (function?) works

I'm pretty new to Python and I'm going through a starter book. The code isn't written in English so I tried my best to translate, hope you guys understand.
It has this exercise where we calculate the taxes from the user salary:
salary = float(input("Enter your salary to taxes calculation: "))
base = salary
taxes = 0
if base > 3000:
taxes = taxes + ((base - 3000) * 0.35)
base = 3000
if base > 1000:
taxes = taxes + ((base - 1000) * 0.20)
My problem is when the input is bigger than 3000, for example, if I run the code with the salary of 5000, the result will be 1100. But when I do the 'same' math on the calculator the result is 700, so I'm lost in here, could someone explain it please?
Please note that in case of salary 5000, the control will go to both the if statements. So it comes out as 700 from first, and 400 from second, therefore answer is 700+400. This also makes sense, as tax calculation is mostly partitioned in brackets, and is not a flat percentage on salary.
Alright, let's walk through it with your example of 5000
salary = float(input("Enter your salary to taxes calculation: "))
base = salary
# base = 5000
taxes = 0
if base > 3000: # base is larger than 3000, so we enter the if statement
taxes = taxes + ((base - 3000) * 0.35)
# taxes = 0 + ((5000 - 3000) * 0.35)
# taxes = 0 + 700
# taxes = 700
base = 3000 # base is set to 3000
if base > 1000: # base was set to 3000 in the line above, so we enter the if statement
taxes = taxes + ((base - 1000) * 0.20)
# taxes = 700 + ((3000 - 1000) * 0.20), remember taxes is already 700 from above
# taxes = 700 + 400
# taxes = 1100
since it is two if statements and not an if and an else we evaluate both statements when base is set larger than 3000. I hope that helps.
It flows on to the second function
so if I sub in the numbers:
Salary = 5000
base = 5000
taxes = 0
if 5000 > 3000:
taxes = 0 + ((5000- 3000) * 0.35) # = 700
base = 3000
if 3000 > 1000:
taxes = 700 + ((3000 - 1000) * 0.20) # = 1100
This is an economical equation which calculate tax for every part of salary.
the procedure would be this:
For amount greater than 3000 calculate 35% tax for this portion of salary.
For amount greater than 1000 (and less than 3000) calculate 20% tax for this portion of salary.
Tax over salary would be the summation of this taxes.

Can anyone please explain this following programming questioƱ?

Question: Define a Python function named calculate_tax() which accepts one parameter, income, and returns the income tax. Income is taxed according to the following rule: the first $250,000 is taxed at 40% and any remaining income is taxed at 80%. For example, calculate_tax(100000) should return $100,000 * 0.40 = $40,000, while calculate_tax(300000) should return $250,000 * 0.40 + 50,000 * 0.80 = $140,000.
My question is simple, does the question ask for me to print out the whole math operation $100,000 * 0.40 = $40,000, or just the final answer$40,000?
It does say "should return $250,000 * 0.40 + 50,000 * 0.80 = $140,000," but all your function should actually return is the final value of 250000. The function should simply do the calculation and return the result. The equation is written out in order to help you create the function, not as an output requirement.
However, the best person to clarify assignments is the teacher who assigned them.
Is not it? like this:
def calculate_tax(income=250000):
tax = 0
if income <= 250000:
tax = income * 0.4
else:
tax = 250000 * 0.4 + (income - 250000) * 0.8
return int(tax)
print calculate_tax(100000) # 40000
print calculate_tax(300000) # 140000

Categories

Resources