Ask for five values, subtract the lowest and take the average - python

I'm having trouble with this python code that is supposed to ask for five values, find the minimum value and subtract it and find the average of the remaining four numbers. I want to use a for loop and if anyone can help me also create a list, i can't seem to get that to work either so I'm doing it as you see below
def get_data():
name = raw_input("What is your name: ")
for i in range(5):
scores = int(input("what are your test scores? ")
return name, scores
def low_score(scores):
low = min(scores)
print low
return low, scores
def find_avg(scores, low):
avg = sum(scores)
print name, "your average = ", avg
return avg
name, scores = get_data()
low, scores = low_score(scores)
avg = find_avg(scores, low)

There are a few problems with your approach. Take a look at this while I write some comments:
def get_data():
name = raw_input("What is your name: ")
scores = []
for i in range(5):
scores.append(int(input("what are your test scores? ")))
return name, scores
def drop_low_score(scores):
sorted_scores = sorted(scores)
print "Dropping", sorted_scores[0]
highest_four_scores = sorted_scores[1:]
return scores
def find_avg(scores):
avg = sum(scores) / float(len(scores))
print name, "your average = ", avg
return avg
name, scores = get_data()
scores = drop_low_score(scores)
avg = find_avg(scores)
When you assign the value from input to score, you are overwriting it each time. Here I am appending it to a list I create before the loop.
Think of it like this:
scores = []
for i in range(5):
new_score = int(input("test score?"))
scores.append(new_score)
Each time through the loop you are appending a new value to the list of scores. At the end of the loop you have 5 scores in your list.
The next problem is you are getting the low_score, but you are doing nothing with it. There are a few ways to deal with that. Read about list to find ways to do it. In my code (since the list is so small) I simply sort it and slice the list, cutting off the first one after it is sorted (default sorting is small to large), so it removes the smallest value. You can read up on list slicing too, but this is an example,
>>> my_list = [1, 2, 3, 4]
>>> print my_list[2:]
[3, 4]
>>> print my_list[3:]
[4]
>>> print my_list[:2]
[1, 2]
The last problem is your find_avg which doesn't find an average at all, it is just summing the scores. You need to sum and divide by the number of elements in the list.

You have a missing bracket in the line -
scores = int(input("what are your test scores? ")
I'm guessing that's the source of your problem because you haven't provided any traceback.

In your loop
for i in range(5):
scores = int(input("what are your test scores? ")
you are overwriting scores five times, without saving the previous values.
Maybe you want something like this:
scores = [int(input("what are your test scores? ") for _ in range(5)]
So the whole assignment would boil down to:
scores = [int(input("what are your test scores? ") for _ in range(5)]
print('Your top four average is', (sum(scores)-min(scores))/4.0)

def get_data():
name = raw_input("What is your name: ")
scores = []
for i in range(5):
scores.append(int(input("what are your test scores? ")))
return name, scores
def low_score(scores):
low = min(scores)
print low
return low, scores
def find_avg(scores, low):
indvalue = scores.index(low)
scores.pop(indvalue)
avg = sum(scores)/len(scores)
print name, "your average = ", avg
return avg
name, scores = get_data()
low, scores = low_score(scores)
avg = find_avg(scores, low)
the above code should wrk fine... with minor modifications in your logic

Related

Python counting votes in election and combining score with names [List]

I have a problem to solve. I need to write a program which takes candidate names from the user and their number of votes received and the program should output each candidate’s name, the votes received by that candidate and the percentage of the total votes received by the candidate. The program should also output the winner of the election, the person with the least votes and the average amount of votes. I have done this so far but I don't how to combine names with appropriate vote numbers.
from statistics import mean
vote_list = []
votes_numbers = []
for i in range(5):
candidate = input("Enter the name of the candidate:")
vote_list.append(candidate)
number_votes = int(input('Enter the number of votes:'))
votes_numbers.append(number_votes)
print(vote_list)
print(votes_numbers)
for x, y in zip(vote_list, votes_numbers):
print(x, y)
total_votes = sum(votes_numbers)
max_votes = max(votes_numbers)
winner_index = votes_numbers.index(max_votes)
winner_name = vote_list[winner_index]
print(winner_name)
print(mean(votes_numbers))
print(max(votes_numbers))
you could use a dictionary to associate the votes with candidates and do it as follows:
from statistics import mean
candidate_votes = {}
for i in range(5):
candidate = input("Enter the name of the candidate:")
number_votes = int(input('Enter the number of votes:'))
candidate_votes[candidate] = number_votes
votes = list(candidate_votes.values())
max_votes_index = votes.index(max(votes))
candidates = list(candidate_votes.keys())
winner_candid_index = candidates[max_votes_index]
print("Winner is ", candidates[max_votes_index])
print("average of votes are ", mean(votes))
print("The winner ",candidates[max_votes_index], ' had ',votes[max_votes_index], '
number of votes.')
Changing your data structure from list to dictionary would allow you to keep track of the input data in an easier way.
That would also be handy in case of other / future calculations:
from statistics import mean
votes = {}
for i in range(5):
candidate = input("Enter the name of the candidate:")
number_votes = int(input('Enter the number of votes:'))
votes[candidate] = number_votes
total_votes = sum(votes.values())
max_votes = max(votes.values())
for key, value in votes.items():
if value == max_votes:
winner_name = key
break
print("{} is the winner with a total of {} votes".format(winner_name, max_votes))
Edit - New version after reading the List requirement
I've read in comments that you want to just use lists.
Even if this approach can seem simpler for a beginner I strongly suggest to learn and understand also dictionaries.
In any case I understood your requirement and here's a solution just using lists.
As you can see a possible solution is - assuming that both list will have same lenght - that if, for example, the max vote index is 3 we will find the winner's name also in index 3 of the candidates list.
I made the code verbose so that it will be easier to understand and tweak it:
from statistics import mean
candidates = []
votes_received = []
for i in range(5):
candidate = raw_input("Enter the name of the candidate:")
number_votes = int(raw_input('Enter the number of votes:'))
candidates.append(candidate)
votes_received.append(number_votes)
total_votes = sum(votes_received)
votes_received_by_winner = max(votes_received)
index_of_the_winner_name = votes_received.index(votes_received_by_winner)
winner_name = candidates[index_of_the_winner_name]
print("{} is the winner with a total of {} votes".format(winner_name, votes_received_by_winner))
If you are just looking to combine the winner name and votes in a print statement use format strings as in:
print("{} is the winner with {} number of votes".format(winner_name,max(votes_numbers)))

The percentage of scores above the average . This function should accept two parameters: the list of scores and the average

Whenever I run the function to calculate the percentage of scores above the average I get the output 56.301. The correct answer should be 34. The average is 54.8415588235294.
#This function calls on the data file
def get_meet_scores_from_file():
input_file = open('state_meet.txt','r')
all_around_points = []
aline = input_file.readline()
while aline:
values = aline.split(',')
all_around_points.append(float(values[2]))
aline = input_file.readline()
input_file.close()
return all_around_points
#This function calculates the average.
def average_scores(score_list):
average_of_scores = 0
list_length = len(score_list)
for index in range (list_length):
list_item = score_list[index]
average_of_scores = average_of_scores + (list_item / list_length)
return average_of_scores
# This is the function that is causing the problem.
#I am trying to get the code to count the number of scores above the average [enter link description here][1]so I can continue and with the code to determine the percentage.
def percentage_above_average(score_list,average):
above_average = score_list[0]
for i in range(int(above_average)):
if above_average > average:
above_average = above_average + 1
return above_average
Your logic in percentage_above_average makes no sense. All you're doing is taking the first score in score_list, adding 1 if it's above the average score, and returning that number. That just gives you a particular score, incremented by 1 in this instance; it's not a percentage or count of anything.
What you need to do is loop through score_list, count scores higher than the average, and divide that count by len(score_list). The code would look something like this:
def percentage_above_average(score_list,average):
above_average = 0
list_length = len(score_list)
for index in range (list_length):
if score_list[index] > average:
above_average = above_average + 1
return above_average / list_length
The percentage of scores above the average will be the number of scores above the average divided by the total number of scores.
Here's a nice little way to count the number of something in an iterable that meets some condition
sum(1 for i in iterable if some_condition(i))
And of course we can get the total number of scores by getting the length of the list containing them
len(score_list)
So we can put those together to make our function
def percentage_above_average(score_list,average):
above_count = sum(1 for score in score_list if score > average)
return above_count/len(score_list)

Printing an average in python, using a list

This code needs to calculate an average to retrieve an integer between 0-100. Any suggestions would be great.
Prompt the user for the number of points they expect to receive
for engagement at the end of class. This number should not be
adjusted by the program (engagement is a total of 302).
Calculate the final based on an average of the quiz scores to
date.
Prompt the user for the various scores. -1 = no more scores, 0 -
zero for that assignment. Keep looping for the grade until the user
enters a -1.
Here is my code, I definitely do not understand lists very well. Probably clearly.
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
list1.append(tot)
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
totalnum+=1
total= total+num
list1.append(num)
average= tot/eng+num
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
print("your average is",average)
If you can use built ins you can just use sum(your_list) / len(your_list) for the average.
If len(your_list) is zero, you will get a ZeroDivisionError, because you just broke math.
It's not clear to me that this is what you're trying to accomplish, but if you just want an average of all the values in the list, you can just do:
average = sum(list)/len(list)
This would return an integer, if you don't want it rounded you could do:
average = sum(list)/float(len(list))
As an aside, you have this:
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
Which could be made simpler, like:
for e in list1:
print e
Python will do the counting for you. :)
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
else:
list1.append(num)
totalnum+=1
total= (num+eng)/tot
print(len(list1))
average = (sum(list1)/tot)*100
counter=0
for e in list1:
print (e)
print("your average is",average)
This is more what I was looking for. Thanks to #Tommy, #SQLnoob, and #Slayer for the tips that I have implemented into the code.

find average value and above average value using def function in python

here is my code so far. I'm not sure whether I do something wrong on the code because the average seems to be wrong. please help me. Thank you
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append(student_score)
results.append(student_name)
print(results)
return results
def calc_average():
total=0
total=total+student_score
average= total/scores
print("the average is ", average)
return
def above_average():
above_average=0
for i in range (scores):
if results [i] > average:
above_average = above_average + 1
print(" the above average score is ", above_average)
return above_average
enter_score()
calc_average()
above_average()
You're making a list results that contains scores and names alternating -- very hard to use. You return that list from enter_score, then completely ignore -- you throw it away! So the other two functions are supposed to work on some magic, or thin air...?
Clearly, the overall flow at the end must instead be:
results = enter_score()
average = calc_average(results)
above_average(results_average)
and calc_average must end with return average.
results is better arranged by replacing the two results.append calls with a single one:
results.append((student_score, student_name))
i.e, make it a list of tuple, not a weird mix of numbers and names.
The other two functions clearly must loop on that list (which they now receive as an argument) to do their respective jobs.
So:
def calc_average(results):
total = 0
for student_score, student_name in results:
total=total+student_score
average= total/float(len(results))
print(average)
return average
and:
def above_average(average, results):
above_average = 0
for student_score, student_name in results:
if student_score > average:
above_average += 1
print(" the number of above average scores is ", above_average)
return above_average
I fixed/ammended your code so that it works:
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append((student_name, student_score))
print(results)
return results
def calc_average(results):
total=0
for student_name, student_score in results:
total=total+student_score
average= total/len(results)
print("the average is ", average)
return average
def above_average(results, average_score):
above_average_no=0
for student_name, student_score in results:
if student_score > average_score:
above_average_no = above_average_no + 1
print(" the above average score is ", above_average_no)
return above_average_no
results = enter_score()
average_score = calc_average(results)
above_average_no = above_average(results, average_score)
I wont provide detailed explanation on what and why things changes. Leave it to you to figure it out. Please note that I tried to make minimal changes to your code. Many things could be improved, such as calculating sum, etc. Hope this helps.

The code says variable referenced before assignment?

I'm getting this error from the code, "UnboundLocalError: local variable 'lowest' referenced before assignment". Why am I getting this? What does 'referenced before assignment' in this case really mean? Because I think that I assign the variable 'lowest' only after 'scores' variable is defined. Any help would be appreciated.
def main():
scores = get_score()
total = get_total(scores)
lowest -= min(scores)
average = total / (len(scores) - 1)
print('The average, with the lowest score dropped is:', average)
def get_score():
test_scores = []
again = 'y'
while again == 'y':
value = float(input('Enter a test score: '))
test_scores.append(value)
print('Do you want to add another score? ')
again = input('y = yes, anything else = no: ')
print()
return test_scores
def get_total(value_list):
total = 0.0
for num in value_list:
total += num
return total
main()
You're using -=, which requires a starting value. But you don't provide a starting value. In context it looks like you meant to use = instead.
That's because in main() you are saying
lowest -= min(scores)
which is essentially lowest = lowest - min(scores). Since you don't have lowest set previously, you'll get that error
Your lowest variable is not defined. You use "lowest -= min(scores)" which means subtract min(scores) from lowest, but lowest doesn't exist yet. Based on the name of the variable I'm guessing you want to do:
def main():
scores = get_score()
total = get_total(scores)
lowest = min(scores)
average = total / (len(scores) - 1)
print('The average, with the lowest score dropped is:', average)

Categories