How do I pass the return statement from calculateTuitionIncrease into an array and then use that array when calculating the total cost?
Here's my code:
import math
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
counter = 0
while counter <= years:
increasedCost = (cost)+(cost*increase)
return increasedCost
def calculateTotalCost(terms,tuition,creditHours,books,roomAndBoard,scholarships):
#This function will calculate the total cost of all your expenses.
totalBookCost = (books*terms)
totalTuitionCost = (tuition*creditHours)*(terms)
totalRoomAndBoard =(roomAndBoard*terms)
totalCost = (totalBookCost+totalTuitionCost+totalRoomAndBoard)-(scholarships)
return totalCost
def main():
#Variable declaration/initialization
years = 0
terms = 0
numberOfSchools = 0
tuitionCost1 = 0
tuitionCost2 = 0
tuitionCost3 = 0
tuitionCost = 0
bookCost = 0
roomAndBoard = 0
scholarships = 0
tuitionIncrease = 0
increasedCost = 0
creditHours = 0
overallCost = 0
#User inputs
years = int(input("Will you be going to school for 2, 4 or 6 years?"))
#If-statements for if user will be going to multiple schools.
if years == 4 or years == 6:
numberOfSchools = int(input("How many schools do you plan on attending during this time?"))
if numberOfSchools == 2:
tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
tuitionCost = (tuitionCost1+tuitionCost2)/(2) #Finds average tuition between schools & assigns it to a variable
elif numberOfSchools == 3:
tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
tuitionCost3 = int(input("How much will you be paying per credit hour at the third school you'll be attending?"))
tuitionCost = (tuitionCost1+tuitionCost2+tuitionCost3)/(3) #Finds average tuition cost between schools & assigns it to a variable
else:
tuitionCost = int(input("Please enter how much you will be paying per credit hour."))
terms = (years*2)
tuitionIncrease = float(input("Please enter the projected tuition increase per year in percentage form (ex. if increase is 7% enter .07)."))
creditHours = int(input("On average, how many credit hours will you be receiving per term?"))
roomAndBoard = int(input("Please enter what your price of room and board will be per term."))
bookCost = int(input("Please enter what your average book cost will be per term."))
scholarships = int(input("Please enter the total amount you will be recieving from grants and scholarships."))
#Calls function that calculates tuition increase per year
increasedCost = calculateTuitionIncrease(tuitionCost,tuitionIncrease,years)
#Calls function that calculates the total cost.
overallCost = calculateTotalCost(terms,tuitionCost,creditHours,bookCost,roomAndBoard,scholarships)
print ("Your total estimated college cost is", overallCost)
main()
For starters, it looks like calculateTuitionIncrease should be returning a list, because currently it's returning a single value and the loop is wrong (it's not advancing at all):
def calculateTuitionIncrease(cost, increase, years):
# This function calculates the projected tuition increase for each year.
counter = 0
answer = []
while counter <= years:
increasedCost = (cost)+(cost*increase)
answer.append(increasedCost)
counter += 1
return answer
As for the second part of the question, it's not clear how you're supposed to "use that array when calculating the total cost", but surely you must iterate over the list returned by calculateTuitionIncrease and do something with each element, for each year - you should know how to do this, it must be part of the problem description you received.
It looks like you're trying to return multiple values from the calculateTotalCost function. You could try using a tuple, which is like a mini-array that you can create by listing some values inside parentheses.
For instance, in your code you could replace
return totalCost
with
return (totalCost, totalBookCost, totalTuitionCost, totalRoomAndBoard)
The short answer is that you would make an empty list before the loop, and then append new items to it inside of your loop. After the loop you can either return the list or do something else with the list.
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
counter = 0
# make an empty list
# before you start the loop
costsPerYear = []
# you should use 'less than' here (or start the counter at 1)
while counter < years:
increasedCost = (cost)+(cost*increase)
# append this cost to the end of the list
costPerYear.append(increasedCost)
# add one to the counter
counter = counter + 1
# once the loop is over, return the list
return costsPerYear
Then you could sum this quantity:
adjustedTuitions = calculateTuitionIncrease(cost, increase, years)
totalTuitionCost = sum(adjustedTuitions)
Alternatively, you can return the sum of those estimates
and use a for loop in place of the while loop.
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
# make an empty list
# before you start the loop
costsPerYear = []
for year in range(years):
increasedCost = (cost)+(cost*increase)
# append this cost to the end of the list
costPerYear.append(increasedCost)
# return the sum of those costs
return sum(costsPerYear)
and use it like this:
totalTuitionCost = calculateTuitionIncrease(cost, increase, years)
Here's a tutorial on for loops and lists.
Also, you don't need to import the math module, because you're not using any of its special math functions.
You can use yield instead of return and use that function as iterator. So that's the example:
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
counter = 0
while counter <= years:
counter += 1
yield (cost)+(cost*increase)
print(sum(calculateTuitionIncrease(1000, 10, 5))) # -> 66000
# the same but long way
sum = 0
for i in calculateTuitionIncrease(1000, 10, 5):
sum += i
print(sum) # -> 66000
Related
def compound_interest(P, r, n, Y):
'''
Computes the future value of investment after Y years
P: initial investment principal
r: the annual interest rate
n: the number of times per year interest will be compounded
Y: the number of years over which to invest
P = float(input("Enter your starting principal ($): "))
r = float(input("Enter the annual interest rate (value between 0 and 1): "))
n = float(input("Enter the number of times per year to compound interest: "))
Y = float(input("Enter the number of years over which to invest: "))
returns: the future value of investment
'''
compound_interest = ((P)((1+(r/n))**(ny)))
print("After 10 year (s), you will have", "$" + str(compound_interest))
return compound_interest
Here is a solution to your problem:
import math
def compound_interest():
P = float(input("Enter your starting principal ($): "))
r = float(input("Enter the annual interest rate (value between 0 and 1): "))
n = float(input("Enter the number of times per year to compound interest: "))
Y = float(input("Enter the number of years over which to invest: "))
cpd_interest = P * math.pow(r+1, n * Y)
print("After {} year (s), you will have {} $".format(Y, cpd_interest))
return cpd_interest
compound_interest()
I've removed the parameters you give in your function, because you don't need them if you ask for them as input() from the user.
I also improved your calculation: When you want to calculate the interest it should be the starting principal * (the interest percentage +1 to the power (number of years times number of times per year)). I used the math.pow() function for this, and you can see here how it works exactly.
I renamed the variable name from compound_interest to cpd_interest, as it's a bad idea to have variable names the same name as your function.
I also rewrote your print statement, and used a replacement field to correctly format the invested years & interest. You cannot return inside a print statement, returning is always the last thing the function does (unless it returns nothing).
I made an assignment of a weekly savings calculator and after generating the exe file and run it, it will open cmd, prompt for the required inputs and closes immediately after making the calculations and displaying a list. I'd like the program window to stay open while displaying the list so the user can take notes if desired.
weeks = []
#Creates a list with each week's amount for the selected number of periods.
def create_list(amount, periods):
counter = 0
savings = 0
while (counter < periods):
savings += amount
weeks.append(savings)
counter += 1
#Formats each item in the list and prints it separately.
def display(lists):
i = 1
for entry in lists:
print ("On period {} you should deposit ${} ".format(str(i), entry))
i += 1
def main():
amount = int(input("Enter savings amount you want to start with: "))
periods = int(input("For how many periods do you want to save?: "))
print()
create_list(amount, periods)
display(weeks)
total = sum(weeks)
print ("\nAfter {} periods you will have ${} saved.".format(periods, total))
main()
This is the output of the code I am trying to write. I have seen this done for C++, but not python with a dictionary. The key here is the dictionary is not optional. I need to use it to fulfill the assignment.
ID Candidate Votes Received % of Total Vote
1 Johnson 5000 55.55
2 Miller 4000 44.44
Total 9000
and the winner is Johnson!
I need to use a dictionary and a loop to create this. However, I am stuck on 3 points.
1.The percent- current code returns the percent before it has the whole total ex: first candidate always has 100%.
2. Declare a winner- code finds the max votes and returns the number value but I need it to return the name.
3. How to format the dictionary values so it lines up under the header. I don't think is possible, but it must be a requirement to use a dictionary for a reason. I am thinking I need to make a copy of the dictionary and format that?
Here is what I have so far:
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
dct[i] = {name,votes,int(votes)/total*100}
i += 1
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+max(totalVotes))
Which returns:
Please enter a name: Smith
Please enter vote total for canidate: 100
Please enter a name: Frieda
Please enter vote total for canidate: 200
Please enter a name: West
Please enter vote total for canidate: 10
Please enter a name:
ID Name Votes % of Total Vote
1 {'Smith', '100', 100.0}
2 {'Frieda', 66.66666666666666, '200'}
3 {3.225806451612903, '10', 'West'}
Total 310
The Winner of the Election is 200
You add the number of each candidates votes at the same time you calculate the percent vote for each candidate. You need to find the total votes first, then divide each candidates votes by the total
You are returning the max of a list of integers. Obviously you aren't going to get a string. You need some way to connect the number votes with the candidate.
Don't bother. You can try to figure out how many tabs you need to get the whole thing lined up, but from experience, it is basically impossible. You could separate them with commas and open it in excel as a csv, or you could just make the user figure out what number goes with what.
The other answer uses data tables, so I will take another, more vanilla and cool approach to getting what you want.
class candidate():
def __init__(self, name, votes):
self.name = name
self.votes = int(votes)
def percentvotes(self, total):
self.percent = self.votes/total
def printself(self, i):
print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent))
def getinput():
inp = input('Please enter your candidates name and votes')
return inp
candidates = []
inp = getinput()
s = 0
while inp != '':
s+=1
candidates.append(candidate(*inp.split(" ")))
inp = getinput()
for c in candidates:
c.percentvotes(s)
candidates.sort(key = lambda x:-x.percent)
print('ID\tname\t\tvotes\t\tpercentage')
for i, c in enumerate(candidates):
c.printself(i+1)
I have added very little changes to your code to make it work:
I have mentioned the changes as comments in the code.
Edit: It's more efficient to use objects for each candidate if you require scaling in the future.
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
# I change it to a list so it's much easier to append to it later
dct[i] = list((name,int(votes)))
i += 1
# I calculate the total percent of votes in the end and append to the candidate
maxVal = 0
for i in range(1, len(dct) + 1):
if dct[i][1] > maxVal:
maxInd = i
dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(dct)
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+ dct[maxInd][0]))
I believe that this is the solution you are looking for. Just change the input statements in case you are using Python 2.x. Using Dataframe, the output will be exactly how you wanted.
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=["Candidate", "Votes Received","Percentage of total votes"])
names=list()
votes=list()
while True:
name = str(input("Enter Name of Candidate."))
if name=='':
break
else:
vote = int(input("Enter the number of votes obtained."))
names.append(name)
votes.append(vote)
s=sum(votes)
xx=(votes.index(max(votes)))
myArray = np.array(votes)
percent = myArray/s*100
for i in range(len(names)):
df1 = pd.DataFrame(data=[[names[i],votes[i],percent[i]]],columns=["Candidate", "Votes Received","Percentage of total votes"])
df = pd.concat([df,df1], axis=0)
df.index = range(len(df.index))
print (df)
print ("Total votes = ",s)
print ("The man who won is ",names[xx])
For my computer science class I have to make a program that will calculate grades.
This is my first computer science class (no prior experience) so I am struggling through it.
These are the directions:
Ask the user for the number of tests, assignments, quizzes, and labs in their course.
Ask the user if there is a final with a separate weight from the tests above, e.g. a course has 2 tests, each weighing 12.5%, and 1 final weighing 15%.
For each category having a number > 0
a. Prompt the user for the weighted percent, out of 100%, which should total
100% for all categories!!!
b. Get the score(s) for the category.
c. If the category is labs, then sum all the scores.
d. Else, average the scores.
e. Calculate the weighted average for the category.
Using the weighted average of each category, calculate the grade in the course.
Ask the user if he/she wants to calculate a grade for another class.
If the user responds yes, then go back to step 1.
Else, end the program.
My code so far:
def main():
lists = get_user_input()
get_scores(lists);
get_weighted_average(lists)
def get_user_input():
# How many?
t = int(input("How many tests?: "))
a = int(input("How many assignments?: "))
q = int(input("How many quizzes?: "))
l = int(input("How many labs?: "))
# How much weight on grade?
tw = float(input("Enter weight of tests: "))
aw = float(input("Enter weight of assignments: "))
qw = float(input("Enter weight of quizzes: "))
lw = float(input("Enter weight of labs: "))
lists = [t, a, q, l, tw, aw, qw, lw]
return lists
def get_scores(lists):
# What are the scores?
scores = [0] * 5
for(x in range(lists[0]):
test_scores = float(input("enter your test scores: "))
scores[x] = test_scores
for(x in range(lists[1]):
test_scores = float(input("enter your assignment scores: "))
scores[x] = assignment_scores
for(x in range(lists[2]):
test_scores = float(input("enter your quiz scores: "))
scores[x] = quiz_scores
for(x in range(lists[3]):
test_scores = float(input("enter your lab scores: "))
scores[x] = lab_scores
sumlabs = 0
for(x in range(lists[3]):
sumlabs = sumlabs + scores[x]
print(sumlabs)
def get_weighted_average(lists):
main()
I am not sure how to proceed so any help is much appreciated.
Averaging a score means adding them up and dividing by the number of them. You can use the fact that a list has a way to tell you how many elements it has. For example if x is a list then len(x) is the number of things in the list. You should be careful about not trying to calculate the score of an empty list, because that would mean dividing by zero. In the following function the 'if score_list:' will be true if there is something in the list. Otherwise it returns None (since the average is not defined).
def average_score(score_list):
if score_list: # makes sure list is not empty
total = 0 # our total starts off as zero
for score in score_list: # starts a loop over each score
total += score # increases the total by the score
return total / len(score_list) # returns aveage
To form a list of scores from user input, presuming the user will put them all on the same line when you prompt them, you can get a string from the user (presumably like: "13.4 12.9 13.2" And then use the string's split method to convert this to a list of strings like ["13.4", "12.9", "13.2"], and then convert this list of strings to a list of floats. Finally using the average function above you can get an average:
test_score_entry = raw_input("Enter your test scores separated by spaces: ")
test_sore_strings = test_score_entry.split()
test_scores = [float(_) for _ in test_score_strings]
average_score = average(test_scores)
I'm very new to Python and I hope for some help or guides by asking here.
Here's the problem:
Write a program that estimates the average number of drawings it takes before the user’s numbers are picked in a lottery that consists of correctly picking six different numbers that are between 1 and 10. To do this, run a loop 1000 times that randomly generates a set of user numbers and simulates drawings until the user’s numbers are drawn. Find the average number of drawings needed over the 1000 times the loop runs.
I tried to create something (below), but I just can't think of how to get those average number. Also it seems the loop is not good. Any help or solution? thank you in advance.
from random import randint
from random import choice #???
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
x = 0
randomlotterylist = []
while not x>1000:
lottery = []
for i in range (6):
lot.append(randint(1,10))
randomlotterylist.append(lottery)
x = x + 1
#Next.. ????
First, you want to know your theoretical average number of drawings, that's (1/10)^6 assuming no repetition allowed. Therefore on average every 1,000,000 tries you'd hit the correct number. That is only if the order matters but I assume in your case the order does not matter, so def your average is less than that...
from random import randint
def number_of_tries_before_hitting_jackpot(user_number):
n_tries = 0
while True:
random_number = set([randint(1,10) for i in range(1,7)])
if user_number == random_number:
return n_tries
else:
n_tries+=1
def ask_user_his_number():
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
return set(userlist)
n_tries_list = []
for x in range(1,1001):
user_number = ask_user_his_number()
print user_number
tmp = number_of_tries_before_hitting_jackpot(user_number)
print tmp
n_tries_list.append(tmp)
avg_number_drawings = reduce(lambda x, y: x + y, n_tries_list) / len(n_tries_list)
print avg_number_drawings
This code is not what I'd do in the sense that the user needs to input its 6 numbers 1,000 times (v annoying for the user). You could change the ask_user_his_number function to a function that just randomly selects a set of 6 numbers.
by using random module, for loop, list in short without defining fuction.
from random import *
user_num=[]
count=0
for i in range(6):
random_num=randint(1,10)
user_num+=[random_num]
user_num.sort()
for j in range(1000):
picked=[]
for k in range(6):
pick_num=randint(1,10)
picked+=[pick_num]
picked.sort()
if picked==user_num:
count+=1
print("the avg darwing is: ",count, count/1000)