I'm reading this python book called "Python for software design" and it has the following exercise:
Suppose the cover price of a book is $24.95, but the 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
ok, i have the following code:
bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60
bookDiscountAmount = bookPrice * discount * totalUnits
shipping = shippingPriceRest * 59 + shippingPriceFirst
result = bookDiscountAmount + shipping
print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(bookDiscountAmount)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)
With that I get the following results:
The total price for 60 books including shipping and discount is:
Total price of the books is: 898.2
Total Shipping is: 47.25
The Total price is: 945.45
My questions are:
Is this correct?
How can i make this code better?
There are only three things to change:
1) You duplicated the number of books: 60 and 59 both appear in the code. You shouldn't have 59 in there.
2) Print you results like this: print 'The total price is: %.2f' % result
3) Usual Python convention is to name variables_like_this, notLikeThis.
The only improvement I would suggest is to use the format-function instead of string concatenation:
print """The total price for {0:d} books including shipping and discount is:
Total price of the books is: {1:7.2f}
Total Shipping is: {2:7.2f}
The Total price is: {3:7.2f}""".format(totalUnits, bookDiscountAmount
shipping, result)
this makes all the numbers nicely aligned and equally formatted (with two digits after the decimal-point and a total precision of 7).
Edit: And of course, as the other pointed out, don't hard-code the 59 there.
It looks right to me. I would avoid hard-coding 59. Instead, check whether the total is more than one, and divide up as appropriate.
Also, this is minor, but bookDiscountAmount should be bookDiscountedAmount (the discount is the amount they save, not the amount they pay). Other people have pointed out how to improve the string printing.
i did it this way but i still believe that with a function as above would be better
price = 24.95
discount = price * (40/100)
d_price = price - discount
shipping = 3 + (0.75 * (60 - 1))
wholesale = d_price * 60 + shipping
Please try this:
bookCost = 24.95
numBooks = 60.0
def cost(numBooks):
bulkBookCost = ((bookCost * 0.60) * numBooks)
shippingCost = (3.0 + (0.75 * (numBooks - 1)))
totalCost = bulkBookCost + shippingCost
print 'The total cost is: $', totalCost
cost(numBooks)
'''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?
'''
import math
book_price = float(24.95)
discount = float(book_price * 40 /100)
Book_Price= float(book_price - discount)
print ('Book Price is without shipping charges = ' , Book_Price)
shipping = 3.0
Total_Price = float(Book_Price + shipping)
print ('The book 1st price is =' ,Total_Price)
Quantity = int(input('Enter the Number of Copies = '))
if Quantity > 1:
Price = float(Book_Price * Quantity)
Additional_copy_price = 0.75
Q = float(Quantity * Additional_copy_price)
Final_Price = float(Price + Q + 3 - .75)
print (' Final price for more than one copy is = ' , Final_Price)
else:
print (Total_Price)
cov_price = 24.95 #cost of one book
discount = 0.4
per_one = (cov_price-(cov_price*discount)) #cost of one book on discount
ship_cost = 3 #shipment on first book
other_ship = 0.75 #shipment on other books
purchased = input("Enter number of books purchased : ")
purchased = int(purchased)
if(purchased):
cost = ((other_ship*(purchased-1)+(per_one*(purchased-1))) + (per_one+3))
print("The cost of books purchased including discount = ",cost)
print("Price per one is =",per_one)
i'm a beginner to python and this worked fine for me
bc = 24.95 #book cost real price
dis = 0.40 # discount percent
bcd = bc*dis # discount amount
bp = bc - bcd # book price
scf = 3 # shipping cost for the first book
scr = 0.75 # shipping cost for the rest books
cost1 = bp*scf
cost2 = bp*scr*59
TotalCost = cost1 + cost2
print(TotalCost)
This is my basic solution to this problem
price = 24.95 - (24.95)*4/10
order = 60
shipping = 3 + 0.75*(order-1)
print('The total price for 60 books including shipping and discount is %.2f$' % (order*price + shipping))
n = int(input('Enter the number of copies : '))
Book_store_price_of_one_copy = (60*24.95)/100
Shipping_cost_for_copy = (3+((n-1)*0.75))
whole_sale = (n*Book_store_price_of_one_copy)+Shipping_cost_for_copy
print(f'Whole sale of {n} copies is {whole_sale}')
#######################################################################################
#Your code, commented
#######################################################################################
bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60
bookDiscountAmount = bookPrice * discount * totalUnits # Poor variable name choice. This is not the book discount amount, it's the cost of all books without shipping
shipping = shippingPriceRest * 59 + shippingPriceFirst # You should really use your variables as much as possible. Instead of 59, use totalUnits - 1
result = bookDiscountAmount + shipping
print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(bookDiscountAmount)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)
#######################################################################################
#An example of your code, cleaned up
#######################################################################################
bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60
totalCostBeforeShipping = (bookPrice * discount) * totalUnits
shipping = (shippingPriceRest * (totalUnits-1)) + shippingPriceFirst
result = totalCostBeforeShipping + shipping
print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(totalCostBeforeShipping)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)
#######################################################################################
#An example of another method, using a loop
#######################################################################################
bookPrice = 24.95
discount = 40 # %
bookPriceWithDiscount = bookPrice * ((100.0-discount)/100.0)
firstBookShippingPrice = 3
otherBookShippingPrice = .75
totalBooks = 60
totalCost = 0
for book in range(totalBooks):
if book == 0:
totalCost += firstBookShippingPrice
else:
totalCost += otherBookShippingPrice
totalCost += bookPriceWithDiscount
shipping = firstBookShippingPrice + (otherBookShippingPrice * totalBooks)
print 'The total price for 60 books including shipping and discount is:'
print 'Total price per book is: %d'%(bookPriceWithDiscount)
print 'Total shipping is: %d'%(shipping)
print 'The total price is: %d'%(result)
Related
I’m not so sure how to do the last part which is the dictionary part and ticker part, and also
On
“”file = open("/home/ubuntu/environment/hw5/" + tickers + “.txt”)””"
This line keep showing
TypeError: must be str, not list
Any suggestion on how to fix those or make the code works ?
Here’s my code
import json
def meanReversionStrategy(prices):
total_profit = 0
first_buy = None
buy = 0
for i in range(len(prices)):
if i >= 5:
current_price = prices[i]
moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] +prices[i-5]) / 5
if current_price < moving_average * 0.95 and buy == 0:
buy = current_price
print("buy at: ",round (current_price,2))
if first_buy is None:
first_buy = buy
elif current_price > moving_average * 1.05 and buy != 0:
print("sell at: ", round(current_price,2))
print("trade profit: ", round(current_price - buy,2))
total_profit = current_price - buy
buy = 0
final_profit_percentage = ( total_profit / first_buy ) * 100
print("First buy: " , round(first_buy,2))
print("Total profit: " , round(total_profit, 2))
print("Percentage return: ", round(final_profit_percentage, 2),"%")
def simpleMovingAverageStrategy(prices):
i = 0
buy = 0
total_profit = 0
first_buy = 0
for p in prices:
if i >= 5:
moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] +
prices[i-5]) / 5
#simple moving average logic, not mean
if p > moving_average and buy == 0: #buy
print("buying at: ", p)
buy = p
if first_buy == 0:
first_buy = p
elif p < moving_average and buy != 0: #sell
print("selling at: ", p)
print("trade profit: ", p - buy)
total_profit += p - buy
buy = 0
i += 1
final_percentage = (total_profit / first_buy) * 100
print("first buy: ", first_buy)
print("total profit: ", total_profit)
print("final percentage: ", final_percentage, "%")
return total_profit, final_percentage
tickers = ["AAPL1" , "ADBE" , "BA", "CMCSA", "CSCO", "CVS", "GOOG", "TLSYY","TM"]
file = open("/home/ubuntu/environment/hw5/" + tickers + ".txt")
lines = file.readlines()
# print(lines)
prices = []
for line in lines:
prices.append(float(line))
profit, returns = simpleMovingAverageStrategy(prices)
results = {}
results["AAPL1_profit"] =profit
results["AAPL1_returns"] = returns
json.dump(results, open("/home/ubuntu/environment/hw5/results.json", "w") )
Coding Requirements
-Create a function called meanReversionStrategy which takes a list called “prices” as an argument. The function runs a mean reversion strategy, and outputs to the console the buys and sells of the strategy (like you did in HW4). The function returns the profit and final returns percentage.
-Create a function called simpleMovingAverageStrategy which takes a list called “prices” as an argument. The function runs a Simple Moving Average strategy, and outputs to the console the buys and sells of the strategy. The function returns the profit and final returns percentage.
-Create a function called saveResults which takes a dictionary as an argument. Save the dictionary to a json file called “results.json”.
loop through the list of tickers
for ticker in tickers:
-load prices from a file <ticker>.txt, and store them in the results dictionary with the
key “<ticker>_prices”
-call meanReversionStrategy(prices) and store the profit and returns in the results
dictionary with the keys “<ticker>_mr_profit” and “<ticker>_mr_returns”
-call simpleMovingAverageStrategy(prices) and store the profit and returns in the
results dictionary with the keys “<ticker>_sma_profit” and “<ticker>_sma_profit”
with the keys “ticker_mr_profit” and “ticker_mr_returns”
call saveResults(results) and save the results dictionary to a file called results.json
Welcome!
As this is a homework question, I will not solve it for You, but here is my advice for You:
tickers is an array and as your homework description states, You must 'loop through the list of tickers' and open each of them. So how do You loop over tickers?
And reflect about the error. What do You think should be the result of "/home/ubuntu/environment/hw5/" + tickers + ".txt"?
I am new to programming and I am trying to write a program for the python essentials course I am in. It's on Day 1 and I am having trouble figuring out why the Total Deductions will not compute the correct amount. This is the code I wrote:
print("=================DEDUCTIONS=================")
print("SSS: " + sss_contribution)
print("PhilHealth: " + philhealth_contribution)
print("Other Loan: " + housing_loan)
tax_rate = .10
tax_total = int(gross_salary)*int(tax_rate)
print("Tax: " + str(tax_total))
total_deductions = int(sss_contribution) + int(philhealth_contribution) + int(housing_loan) + int(tax_total)
print("Total Deductions: " + str(total_deductions))
net_salary = float(gross_salary) - float(total_deductions)
print("NET SALARY: " + str(net_salary))
I get the correct NET SALARY amount, but the Total Deductions only reflect the total for the SSS, PhilHealth, and Housing. Thank you.
You declared tax_rate as a float, so try:
tax_total = int(gross_salary)*float(tax_rate)
If you declared tax_rate as 5.10, doing an int(tax_rate) returns 5. Wheras doing a float(tax_rate) returns 5.1.
Here in your example you declared tax_rate as 0.10, so your tax_total becomes 0 since int(tax_rate) is 0. Thats why your tax is not included in your calculations
print("=================DEDUCTIONS=================")
sss_contribution = 500
philhealth_contribution = 600
housing_loan = 500.20
gross_salary = 2000
print("SSS: " +str(sss_contribution))
print("PhilHealth: " +str(philhealth_contribution))
print("Other Loan: " +str(housing_loan))
tax_rate = .10
tax_total = int(gross_salary)*float(tax_rate)
print("Tax: " + str(tax_total))
total_deductions = int(sss_contribution) + int(philhealth_contribution) + float(housing_loan) + int(tax_total)
print("Total Deductions: " + str(total_deductions))
net_salary = float(gross_salary) - float(total_deductions)
print("NET SALARY: " + str(net_salary))
I am brand new to python and I attempted to make a simple federal income tax calculator. There has to be a far simpler way to accomplish the same task. Here's what I created:
'''
# 2021 income tax calculator
print ('What\'s your yearly income after you deduct all expenses?')
myincome = int(input())
base = (myincome*.1)
e = (max(myincome-9950,0)*.02)
ex = (max(myincome-40525,0)*.1)
ext = (max(myincome-86376,0)*.02)
extr = (max(myincome-164926,0)*.08)
extra = (max(myincome-209426,0)*.03)
extras = (max(myincome-523601,0)*.02)
tax = base + e + ex + ext + extr + extra + extras
print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax')
print ()
while True:
print ('Try Different Income:')
myincome = int(input())
base = (myincome*.1)
e = (max(myincome-9950,0)*.02)
ex = (max(myincome-40525,0)*.1)
ext = (max(myincome-86376,0)*.02)
extr = (max(myincome-164926,0)*.08)
extra = (max(myincome-209426,0)*.03)
extras = (max(myincome-523601,0)*.02)
tax = base + e + ex + ext + extr + extra + extras
print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax')
print ()
continue
'''
Try this code:
# create a dictionary with amounts and rates (the key is the amount, the value is the rate)
stakes = {0: .1, 9950: .02, 40525: .1, 86376: .02, 164926: .08, 209426: .03, 523601: .02}
myincome = input('What\'s your yearly income after you deduct all expenses? ')
while myincome.isnumeric(): # loop ends if entered empty or non-numeric string
myincome = int(myincome)
# a cycle in which key-value pairs (amount-rate) are alternately extracted (unpacked)
# from the dictionary, partial taxes is calculated and the result is summed up
tax = sum(max(myincome - k, 0) * v for k, v in stakes.items())
print(f'You\'re gonna get screwed about~${tax} dollars in Federal income tax')
myincome = input('Try Different Income:')
I need to write a python program that reads 1000 lines of text and take the total and average of the salaries of each professor category (assistant, associate, full, all faculty). Here is the problem:
A university posts its employee salary at
http://cs.armstrong.edu/liang/data/Salary.txt. Each line in the file
consists of faculty first name, last name, rank, and salary (see
Exercise 13.16). Write a program to display the total salary for
assistant professors, associate professors, full professors, and all
faculty, respectively, and display the average salary for assistant
professors, associate professors, full professors, and all faculty,
respectively.
This is the code I have so far:
import urllib.request
def main():
infile = urllib.request.urlopen('http://cs.armstrong.edu/liang/data/Salary.txt')
s = infile.read().decode().splitlines()
asstTotal = 0
asstCount = 0
asscTotal = 0
asscCount = 0
fullTotal = 0
fullCount = 0
for line in s:
if "assistant" in line:
asstCount += 1
asstTotal += int(float(s[3]))
if "associate" in line:
asscCount += 1
asscTotal += int(float(s[3]))
if "full" in line:
fullCount += 1
fullTotal += int(float(s[3]))
allFacTotal = asstTotal + asscTotal + fullTotal
avgAsst = int(asstTotal / asstCount)
avgAssc = int(asscTotal / asscCount)
avgFull = int(fullTotal / fullCount)
avgAll = int(allFacTotal / 1000)
print("Total assistant professor salary is", asstTotal)
print("Total associate professor salary is", asscTotal)
print("Total full professor salary is", fullTotal)
print("Total faculty salary is", allFacTotal)
print("Average assistant professor salary is", avgAsst)
print("Average associate professor salary is", avgAssc)
print("Average full professor salary is", avgFull)
print("Average faculty salary is", avgAll)
main()
I'm not sure how to get the salaries from the respective professor ranks and totaling and averaging them. Any input would be much appreciated!
Result:
Total assistant professor salary is 24306418
Total associate professor salary is 27235856
Total full professor salary is 27631726
Total faculty salary is 79174000
Average assistant professor salary is 79174
Average associate professor salary is 79174
Average full professor salary is 79174
Average faculty salary is 79174
This can be done to account for any type of rank, by building up a list of pay for each position in a dictionary, then simply dividing the sum by the length.
My example:
import urllib.request
def main():
infile = urllib.request.urlopen('http://cs.armstrong.edu/liang/data/Salary.txt')
s = infile.read().decode().splitlines()
pays = {}
for line in s:
*name, rank, pay = line.split()
pays[rank] = pays.get(rank, []) + [float(pay)]
for rank, sals in pays.items():
avg = sum(sals) / len(sals)
print("{:>10} ({:3}): ${:,.2f}".format(rank.title(), len(sals), avg))
if __name__ == '__main__':
main()
And the output:
Associate (344): $83,849.26
Full (349): $102,229.37
Assistant (307): $65,949.55
import urllib.request
def main():
infile = urllib.request.urlopen("http://cs.armstrong.edu/liang/data/Salary.txt")
asstSalTotal = 0
asstTotal = 0
asscSalTotal = 0
asscTotal = 0
fullSalTotal = 0
fullTotal = 0
for line in infile.readlines():
data = line.decode().split()
designation = data[2]
if designation == "assistant":
asstSalTotal += float(data[3])
asstTotal += 1
elif designation == "associate":
asscSalTotal += float(data[3])
asscTotal += 1
elif designation == "full":
fullSalTotal += float(data[3])
fullTotal += 1
allSalTotal = asstSalTotal + asscSalTotal + fullSalTotal
allTotal = asstTotal + asscTotal + fullTotal
print("Total Salary:\n\tAssistant:\t%d\n\tAssociate:\t%d\n\tFull:\t%d\n\tAll:\t%d\n\nAvg Salary:\n\tAssistant:\t%d\n\tAssociate:\t%d\n\tFull:\t%d\n\tAll:\t%d\n" % (asstSalTotal, asscSalTotal, fullSalTotal, allSalTotal, asstTotal, asscTotal, fullTotal, allTotal))
main()
In python2.7, use urllib2.urlopen and group salaries together by title with a table.
In python3, use urllib.request.urlopen and change print .. to print(..)
import urllib2
rs = urllib2.urlopen('http://cs.armstrong.edu/liang/data/Salary.txt')
title_salaries = {}
for line in rs.read().split("\n"):
_, _, title, salary = line.split(' ')
if not title_salaries.has_key(title):
title_salaries[title] = []
title_salaries[title].append(float(salary))
for title, salaries in title_salaries.items():
print title
print 'avg:', sum(salaries) / len(salaries)
print 'total:', sum(salaries)
print
I am trying to align the text in my output.
purch_amt = float(input('Enter Amount of Purchase'))
state_stax = purch_amt * 0.04
county_stax = purch_amt * 0.02
tax = state_stax + county_stax
totalprice = purch_amt + tax
Print("Purchase Price", "= $", %.2f % purch_amt)
Print("State Sales tax", "= $", %.2f % state_stax)
Print("County Sales tax", "= $", %.2f % county_stax)
Print("Total Tax", "= $", %.2f % tax)
Print("Total Price", "= $", %.2f % totalprice)
... and I want it to look like this when it is run.
Purchase Price = $ 100.00
State Sales tax = $ 4.00
County Sales tax = $ 2.00
Total Tax = $ 6.00
Total Price = $ 106.00
The only way I've found to do this is extremely complex for something that should be fairly easy.
Problem solved, Thanks!
purch_amt = float(input('Enter Amount of Purchase'))
state_stax = purch_amt * 0.04
county_stax = purch_amt * 0.02
tax = state_stax + county_stax
totalprice = purch_amt + tax
def justified(title, amount, titlewidth=20, amountwidth=10):
return title.ljust(titlewidth) + " = $ " + ('%.2f' % amount).rjust(amountwidth)
print(justified('Purchase Price', purch_amt))
print(justified('State Sales Tax', state_stax))
print(justified('County Sales Tax', county_stax))
print(justified('Total Tax', tax))
print(justified('Total Price', totalprice))
String ljust, rjust, center are what you want for padding a string like that.
def justified(title, amount, titlewidth=20, amountwidth=10):
return title.ljust(titlewidth) + " = $ " + ('%.2f' % amount).rjust(amountwidth)
print(justified('Parts', 12.45))
print(justified('Labor', 100))
print(justified('Tax', 2.5))
print(justified('Total', 114.95))
You can just use the built-in string formatting:
>>> column_format = "{item:20} = $ {price:>10.2f}"
>>> print(column_format.format(item="Total Tax", price=6))
Total Tax = $ 6.00
...etc.
Breaking this down:
{item} means format the parameter named item
{item:20} means the formatted result should have width 20 characters
{price:>10.2f} means right align (>), width of 10 (10), floating point precision of 2 decimal places (.2f)
Incidentally, you might want to look at the Decimal package for currency work.