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
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'm ranking the top ten basketball players in the NBA via points, minutes, free throws, and efficiency. However, when I go to print the rankings the rankings are incorrect. It seems to be ranking them in terms of the value of each character in the numbers but I want them to be ranked by the highest amount to the lowest amount of those previously mentioned values.
My code:
def readData(filename):
inputFile = open(filename, 'r')
inputFile.readline()
master_data_list = []
for line in inputFile:
master_data_list.append(line.split(","))
return master_data_list
def points(master_data_list):
pointList = []
for player in master_data_list[:-3]:
index = (player[1], player[2], player[6])
pointList.append(index)
return pointList
def minutes(master_data_list):
minutesList = []
for player in master_data_list[:-3]:
index = (player[1], player[2], player[5])
minutesList.append(index)
return minutesList
def freethrows(master_data_list):
freethrowsList = []
for player in master_data_list[:-3]:
index = (player[1], player[2], player[18])
freethrowsList.append(index)
return freethrowsList
def efficiency(master_data_list):
effList = []
for player in master_data_list:
formula = int(((player[6] + player[9] + player[10] + player[11] + player[12])-((player[15] - player[16]) + (player[17] - player[18]) + player[13]))/(player[4]))
index = (player[1], player[2], formula)
effList.append(formula)
return effList
def main():
master_data_list = readData("player_career.csv")
pointList = points(master_data_list)
minutesList = minutes(master_data_list)
freethrowsList = freethrows(master_data_list)
#effList = efficiency(master_data_list)
#got this code from
pointList = sorted(pointList, key = lambda x: x[2], reverse = True)
minutesList = sorted(minutesList, key = lambda x: x[2], reverse = True)
freethrowsList = sorted(freethrowsList, key = lambda x: x[2], reverse = True)
#effList = sorted(effList, key = lambda x: x[2], reverse = True)
print("Top 10 players based on total points scored.")
for line in pointList[:10]:
print(line[0], line[1]+"-"+line[2])
print()
print("Top 10 players based on total minutes.")
for line in minutesList[:10]:
print(line[0], line[1]+"-"+line[2])
print()
print("Top 10 players based on total free throws.")
for line in freethrowsList[:10]:
print(line[0], line[1]+"-"+line[2])
print()
"""
print("Top 10 players based on total efficiency.")
for line in effList[:10]:
print(line[0], line[1]+"-"+line[2])
print()
"""
The output of the code:
Top 10 players based on total points scored.
Terrell Brandon-9994
Rony Seikaly-9991
David Vaughn-998
Buddy Jeannette-997
Irv Torgoff-997
Greg Ballard-9953
Ralph Simpson-9953
John Lucas-9951
Don Kojis-9948
Phil Chenier-9931
Top 10 players based on total minutes.
Fred Hoiberg-9976
Charlie Johnson-9972
Stewart Granger-996
Gary Gregor-996
Keith Bogans-9957
Al Wood-9939
Kenny Gattison-9930
Willis Bennett-993
Jack Molinas-993
Corie Blount-9925
Top 10 players based on total free throws.
Kurt Rambis-999
Charlie Scott-998
Walt Wesley-998
Albert King-996
Lucious Harris-994
Johnny Neumann-991
Frank Johnson-990
Mardy Collins-99
Calvin Garrett-99
Bob Lackey-99
I haven't done efficiency yet so it's not included.
Here's a sample of the input file:
player stats
If someone has an idea to get them to rank correctly, thanks.
Please change this key = lambda x: x[2] into key = lambda x: int(x[2]) to compare integers, not strings.
You need to change the strings in your input into integers, like:
def points(master_data_list):
pointList = []
for player in master_data_list[:-3]:
index = (player[1], player[2], int(player[6]))
pointList.append(index)
return pointList
Write a python program that will take 3 lists:
Name Wage Hours
Juan 7.50 35
Rae 11.00 41
Ivanna 18.25 26
Lilly 9.25 35
Robert 11.10 45
and use this logic:
An employee gets overtime when they have worked more than 40 hours
Overtime pay is calculated using this formula:
Gross Pay = (35*Wage) + ((Hours-35)*Wage*1.5)
Regular pay is calculated using this formula:
Gross Pay = (Hours*Wage)
Use a loop to process these lists.
Print each employee, their wages, Hours and gross pay.
I'm running this program and I have the for loop. The input works fine, but the while loop that its supposed to have the same output is not giving me any output at all. Here's my code.
`Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
GP = 0
if(Hours[X] > 40):
GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
else:
GP = Hours[X] * Wage[X]
print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)
Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)`
my output is going as
Name Wage Hours GP
Juan 7.5 35 262.5
Rae 11 41 484.0
Ivanna 18.25 26 474.5
Lilly 9.25 35 323.75
Robert 11.1 45 555.0
Name Wage Hours GP
Juan 7.5 35 555.0
I don't know where the error is in the while loop.
Your last line needs to be indented. So instead of
while (Y):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
it needs to be
while (Y):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
because right now the print is outside of the while loop, so it is only printing with the value Y=0.
Have to follow python code indented and need to give proper while loop condition with (increment/decrement/boolean). As your code need to increment the value of Y.
Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
GP = 0
if(Hours[X] > 40):
GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
else:
GP = Hours[X] * Wage[X]
print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)
Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y<counter):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
Y=Y+1
import xlrd
import numpy
fileWorkspace = 'C://Users/jod/Desktop/'
wb1 = xlrd.open_workbook(fileWorkspace + 'assign2.xls')
sh1 = wb1.sheet_by_index(0)
time,amount,category = [],[],[]
for a in range(2,sh1.nrows):
time.append(int(sh1.cell(a,0).value)) # Pulling time from excel (column A)
amount.append(float(sh1.cell(a,1).value)) # Pulling amount from excel (column B)
category.append(str(sh1.cell(a,2).value)) # Pulling category from excel (column C)
#print(time)
#print(amount)
#print(category)
print('\n')
p_p2 = str(sh1.cell(0,1))
p_p1 = p_p2.replace("text:'","")
pp = p_p1.replace("'","")
print(pp) # Printing the type of pay period (Row 1, col B)
c_p2 = str(sh1.cell(1,1))
c_p1 = c_p2.replace("text:'","")
cp = c_p1.replace("'","")
print(cp) # Printing the type of compound period (Row 2, col B)
netflow = 0
outflow = 0
inflow = 0
flow = 0
cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor",
"Testing", "Marketing", "Materials", "Logistics"]
if pp == "Years" and cp == "Years": # if pay period and compound period are both in years
IRR = numpy.irr(amount) * 100 # Calculates the internal rate of return (IRR)
print ("IRR:", round(IRR, 2), '%', '\n') # prints (IRR)
for i in time: # for every value in time array
if cat[5] in category: # if "Labor" for cat array is in category array or not
# calculates the present values using all the amount values (col B) instead of
# just using the ones that has "Labor" category label beside them
# Need to make every other value 0, such as beside "Redeemable" and "Salvage"
flow = amount[i] / numpy.power((1 + (IRR/100)), time[i])
if flow>0:
inflow = inflow + flow
if flow<0:
outflow = outflow + flow
print ('Present Value (P) is:', round(flow,0), '\n')
netflow = outflow + inflow
print("In year 0 or current year")
print("-------")
print ('Outflow is: ', round(outflow,0))
print ('Inflow is: ', round(inflow,0))
print ('Netflow is: ', round(netflow,0), '\n')
outflow2 = (round(outflow,0))*(1+(IRR/100))**(9)
inflow2 = (round(inflow,0))*(1+(IRR/100))**(9)
netflow2 = outflow2 + inflow2
print("In year 9")
print("-------")
print ('Outflow is: ', round(outflow2,0))
print ('Inflow is: ', round(inflow2,0))
print ('Netflow is: ', round(netflow2,0), '\n')
I have commented important lines of code for clarification.
Here is the original question:
illustrate the breakdown of major project revenues and expenses by category as a percentage of that project’s future value in year 9. The illustration must also clearly indicate the total future value of the project in year 9 as well as the IRR.
There will be a total of 10 revenue and cost categories that a project may be composed of. The categories are: Sales, salvage, subsidy, redeemable, utility, labor, testing, marketing, materials and logistics. All revenues and expenses will fall in one of these ten categories. The project pay period and compound period will be identified at the top of the Excel sheet. Pay period and compound period may be designated as any of the following: years, quarters, months.
I am getting confused because I am not able to pull the only values from beside the "Labor", "Redeemable", or "Salvage". I just don't know where I am making a mistake, or there is something that is incomplete. Below is the excel file image:
Excel File Image 2
Excel File Image 3
After revising, all cashflows are discounted at the irr. What is done is the following:
i) determineAdjustments takes the pay period (column A) and adjusts if for the year ended (if it is a monthly amount it puts it in the proper year ended) and if its monthly puts in in the month ended (no adjustment necessary). This will divide the pay period by 12 if yearly cash flows are needed (yearly compounding)
ii) IRR is calculated, and the compounding period is used to adjust the monthly IRR for monthly pay periods
iii) all expenses are discounted at the IRR and input into a list for cat_contributions['category_name'] = [discounted period 1, discounted period 2 ... ]
iv) Then the net inflows and outflows are sums of these.
I can't type up data in the spreadsheets from the images as that would take a while, but maybe tinker with this and see if you can get it to work.
from __future__ import division
import xlrd
import numpy
import os
import math
def main(xls = 'xls_name.xlsx', sh = 0):
#save script in same folder as the xls file
os.chdir( os.getcwd() )
wb = xlrd.open_workbook(xls)
sh = wb.sheet_by_index(0)
pay_period = sh.cell_value(0,1)
compounding_period = sh.cell_value(1,1)
compounding_factor, pay_factor = determineAdjustments(
pay_period, compounding_period)
number_of_periods = max( sh.col_values(0, start_rowx = 2) )
flow_per_period = [ 0*i for i in range( int( math.ceil( number_of_periods/pay_factor ) ) + 1 ) ]#list of length number of pay_periods
for r in range(2,sh.nrows):
pay_period = int( math.ceil( sh.cell_value(r,0) / pay_factor ) )
flow_per_period[pay_period] += sh.cell_value(r,1) #unadjusted cash flows
irr = calculateIRR(flow_per_period, compounding_factor)
cat_contributions = sortExpenditures(sh, irr, pay_factor)
total_cat_contributions, netflow, total_outflow, total_inflow = calculateFlows(cat_contributions)
printStats(cat_contributions, irr, compounding_factor, pay_factor,
total_cat_contributions, netflow, total_outflow, total_inflow)
return
def determineAdjustments(pay_period, compounding_period):
if compounding_period == 'years':
compounding_factor = 1
if pay_period == 'months':
pay_factor = 12
if pay_period == 'years':
pay_factor = 1
#assume no days pay periods
if compounding_period == 'months':
compounding_factor = 12
#assume no yearly payouts and that the
#all payments are in months
pay_factor = 1
return compounding_factor, pay_factor
def calculateIRR(cashflow, compounding_factor):
irr = numpy.irr(cashflow)
irr_comp = (1 + irr)**compounding_factor - 1
#seems like in first example it uses rounded irr, can do something like:
#irr_comp = round(irr_comp,4)
return irr_comp
def sortExpenditures(sh, irr, pay_factor):
#percentages and discounting occurs at the IRR caculated in the main
#function
cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor",
"Testing", "Marketing", "Materials", "Logistics"]
#python dictionary to sort contributions into categories
cat_contributions = {}
for c in cat:
cat_contributions[c] = []
# create list of contributions of each list item to FV in a dictionary
for r in range(2,sh.nrows):
try:
#discounted cash flow of each expenditure
#using formula FV = expenditure/(1+i)^n
cat_contributions[sh.cell_value(r,2)].append(
sh.cell_value(r,1) / ( (1 + irr) ** (sh.cell_value(r,0)/pay_factor) )
)
except KeyError:
print "No category for type: " + sh.cell_value(r,2) +'\n'
return cat_contributions
def calculateFlows(cat_contributions):
total_outflow = 0
total_inflow = 0
total_cat_contributions = {}
for cat in cat_contributions:
total_cat_contributions[cat] = sum( cat_contributions[cat] )
if total_cat_contributions[cat] < 0:
total_outflow += total_cat_contributions[cat]
else:
total_inflow += total_cat_contributions[cat]
netflow = total_inflow + total_outflow
return total_cat_contributions, netflow, total_outflow, total_inflow
def printStats(cat_contributions, irr, compounding_factor, pay_period,
total_cat_contributions, netflow, total_outflow, total_inflow):
print "IRR: "+str(irr*100) +' %'
if compounding_factor == 1: print "Compounding: Yearly"
if compounding_factor == 12: print "Compounding: Monthly"
if pay_period == 1: "Cashflows: Year Ended"
if pay_period == 12: "Cashflows: Month Ended"
print "Future Value (Net Adjusted Cashflow): " +str(netflow)
print "Adjusted Inflows: " + str(total_inflow)
print "Adjusted Outflows: " + str(total_outflow) +'\n'
for cat in total_cat_contributions:
if total_cat_contributions[cat] != 0:
print '-----------------------------------------------------'
print cat + '\n'
print "Total Contribution to FV " + str( total_cat_contributions[cat] )
if total_cat_contributions[cat] < 0:
print "Contribution to Expenses: " + str ( abs(100 * total_cat_contributions[cat]/total_outflow) )
else:
print "Contribution to Revenues: " + str ( abs(100 * total_cat_contributions[cat]/total_inflow) ) +'\n'
main(xls='Book1.xlsx')
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)