Everything is working for me in this program except for one thing; I need my output to group the names and values together in the print(names, "\n" values) section.
For example: Pat : €99, Kev : €55, Dermot : €100.
My code is below:
salesperson = int(input("How many salesperson's do you wish to account
for:"))
names = []
values = []
counter = 0
total_sales = 0
total_value = 0
if salesperson > counter:
while salesperson != counter:
name = input("Please enter in the salesperson's name:")
value = float(input("Please enter in the value of sales for the
salesperson:"))
salesperson -= 1
names.append(name)
values.append(value)
total_value += value
from statistics import mean
average_values = mean(values)
minimum = min(values)
maximum = max(values)
print(names,"\n",values)
print(average_values)
print(total_value)
print(minimum)
print(maximum)
You can do this using zip(), and f-strings:
print([f"{x}: £{y}" for x, y in zip(names,values)])
Output:
['Pat: £1.0', 'Dermot: £2.0', 'Kev: £3.0', 'Boris: £4.0', 'Jeremy: £5.0']
Related
The first line gives the number of entries. Further, each entry contains the name of the candidate and the number of votes cast for him in one of the states. Summarize the results of the elections: for each candidate, determine the number of votes cast for him. Use dictionaries to complete the tasks.
Input:
Number of voting records (integer number), then pairs <> - <>
Output:
Print the solution of the problem.
Example:
Input:
5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1
Output:
McCain 16
Obama 17
My problem is at the step when I have to sum keys with same names but different values.
My code is:
cand_n = int(input())
count = 0
countd = 0
cand_list = []
cand_f = []
num = []
surname = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
cand_list.append(cand_f)
for k in cand_list:
for i in k:
if i.isdigit():
num.append(int(i))
else: surname.append(i)
while countd < cand_n:
edict[surname[countd]] = num[countd]
countd += 1
print(edict)
You can add the name and vote to the dictionary directly instead of using one more for() and while().
If the name does not exist in the dictionary, you add the name and vote. If the name exists in the dictionary, increase the vote.
cand_n = int(input())
count = 0
cand_list = []
cand_f = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
if cand_f[0] in edict:
edict[cand_f[0]] += int(cand_f[1])
else:
edict[cand_f[0]] = int(cand_f[1])
print(edict)
Which data structure is best for calculating average of inputted numbers ?
I used an array, but it feels clumsy.
Is there a more standard way to do this?
import os
def getGrades():
g = input("How many tests?")
numGrades = int(g)
grades = []*numGrades
for x in range(numGrades):
t = int(input("Enter Grade #" + str(x+1) + ": "))
grades.append(t)
avgGrades(grades)
def avgGrades(a):
total = 0
count = 0
for t in a:
total = total + t
count = count + 1
avg = total / count
print (f"average is: {avg}")
getGrades()
There is a statistics module which you can use:
import statistics
def get_grades_avg():
g = input("How many tests?")
num_grades = int(g)
grades = [] * num_grades
for x in range(num_grades):
grades.append(int(input("Enter Grade #" + str(x + 1) + ": ")))
return statistics.mean(grades)
avg = get_grades_avg()
print('avg: {}'.format(avg))
Using Python list is well. Maybe trying some built-in functions for getting average grade would be more easily.
Assume grades is a list store some grade.
sum(grades) / len(grades)
You can use something like this:
def average_factory():
count_numbers = 0
sum_numbers = 0
def wrapper(number):
nonlocal count_numbers
nonlocal sum_numbers
sum_numbers += number
count_numbers += 1
return sum_numbers / count_numbers
return wrapper
def get_number(message):
str_number = input(message)
try:
return int(str_number)
except (ValueError, TypeError):
print('Invalid number, please try again')
return get_number(message)
def get_average_of_all_tests():
count_tests = get_number('How many tests? ')
get_average = average_factory()
average = 0
for test_number in range(1, count_tests + 1):
number = get_number('Enter Grade #{test_number}: '.format(test_number=test_number))
average = get_average(number)
return average
Yes this solution seems a little complex with average factory. But I think storing all value just for calculating average is not so good idea. Storing only count and sum of grades is better.
If you have any question about solution feel free to ask me about it.
numpy or scipy offer good facilities for this.
store your numbers in an numpy.array([]).
To obtain your mean, numpy.mean(<yourarray>)
Your code would look like:
import numpy
import os
def getGrades():
g = input("How many tests?")
numGrades = int(g)
grades = []*numGrades
for x in range(numGrades):
t = int(input("Enter Grade #" + str(x+1) + ": "))
grades.append(t)
yourArray = numpy.array(grades)
return numpy.mean(yourArray)
I'm having trouble appending the student dictionary value that coincides with key 'id' to a list. Any help is much appreciated!
students = list();
students.append( {'id':12345, 'first_name':'Alice',
'last_name':'Anderson','assignments':[('assignment_1',0),('assignment_2',2),
('assignment_3',3)]})
students.append({'id':22345, 'first_name':'John',
'last_name':'Sparks','assignments':[('assignment_1',2),('assignment_2',3),
('assignment_3',4)]})
students.append({'id':32345, 'first_name':'Taylor',
'last_name':'Mason','assignments':[('assignment_1',3),('assignment_2',2),
('assignment_3',3)]})
def return_passing(students):
grade_sum = 0
counter = 0
for s in students: #loop thru students
for assignment, grade in s['assignments']:
grade_sum += grade
counter += 1
average = grade_sum / counter
lst = list()
if average >= 2.0:
lst.append((s['id']))
return lst
return_passing(students)
print(return_passing(students))
You have several issues with initializing things at the wrong place, so they get reset. Explanations for those are in the comments:
def return_passing(students):
lst = [] # initialize lst here
for s in students: #loop thru students
grade_sum = 0 # reset these for each student
counter = 0
for assignment, grade in s['assignments']:
grade_sum += grade
counter += 1
# now that we have gone throug all assignments
# compute average
average = float(grade_sum) / counter # convert to float for precision
if average >= 2.0:
lst.append(s['id'])
return lst # return only after you've gone through all students
i am making a calculator in python which gives me students grade average and also subject grade average.
below is a picture of how i need my inputs and how my output should look.
I am trying to use nested lists and functions.I tried this.
You can easily do this with a while loop and Pandas
import pandas
list_marks = {}
subjects = int(input("Number of subjects: "))
while(True):
name = input("Name of student (leave empty if finished): ")
if not name:
break
scores = []
for i in range(1, subjects + 1):
scores.append(int(input("Subject %d: " % i)))
list_marks[name] = scores
scores = pandas.DataFrame(list_marks)
print(scores)
# student1 student2 student3
# 0 100 90 80
# 1 100 90 60
print(scores.mean(axis=0))
# student1 100.0
# student2 90.0
# student3 70.0
# dtype: float64
print(scores.mean(axis=1))
# 0 90.000000
# 1 83.333333
# dtype: float64
or using NumPy:
import numpy
scoresarray = numpy.array(list(list_marks.values()))
print(numpy.mean(scoresarray, axis=0))
# [ 90. 83.33333333]
print(numpy.mean(scoresarray, axis=1))
# [ 100. 90. 70.]
Try this code
def calc(student_count):
list_marks = []
for i in range(int(student_count)):
student_name = input("name of student?")
sub1_score = input("Score of subject 1?")
sub2_score = input("Score of subject 2?")
average = (int(sub1_score) + int(sub2_score))/2
list_marks.append([student_name,sub1_score,sub2_score,average])
print (list_marks)
return list_marks
no_of_students = input("How many students?")
#no_of_subjects = input("How many subjects?")
calc(no_of_students)
This will produce the output you want for two subjects.
If you have many subjects, sum them and divide by their count
I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades.
I'm pretty much stuck. Right now I´ve only got:
for c in range (0,50):
grade = ("What is the grade?")
Also, how could I print the count of grades that are below 50?
Any help is appreciated.
If you don't mind using numpy this is ridiculously easy:
import numpy as np
print np.mean(grades)
Or if you'd rather not import anything,
print float(sum(grades))/len(grades)
To get the number of grades below 50, assuming you have them all in a list, you could do:
grades2 = [x for x in grades if x < 50]
print len(grades2)
Assuming you have a list with all the grades.
avg = sum(gradeList)/len(gradeList)
This is actually faster than numpy.mean().
To find the number of grades less than 50 you can put it in a loop with a conditional statement.
numPoorGrades = 0
for g in grades:
if g < 50:
numPoorGrades += 1
You could also write this a little more compactly using a list comprehension.
numPoorGrades = len([g for g in grades if g < 50])
First of all, assuming grades is a list containing the grades, you would want to iterate over the grades list, and not iterate over range(0,50).
Second, in every iteration you can use a variable to count how many grades you have seen so far, and another variable that sums all the grades so far. Something like that:
num_grades = 0
sum_grades = 0
for grade in grades:
num_grades += 1 # this is the same as writing num_grades = num_grades + 1
sum_grades += sum # same as writing sum_grades = sum_grades + sum
Now all you need to do is to divide sum_grades by num_grades to get the result.
average = float(sum_grade)s / max(num_grades,1)
I used the max function that returns the maximum number between num_grades and 1 - in case the list of grades is empty, num_grades will be 0 and division by 0 is undefined.
I used float to get a fraction.
To count the number of grades lower than 50, you can add another variable num_failed and initialize him to 0 just like num_counts, add an if that check if grade is lower than 50 and if so increase num_failed by 1.
Try the following. Function isNumber tries to convert the input, which is read as a string, to a float, which I believe convers the integer range too and is the floating-point type in Python 3, which is the version I'm using. The try...except block is similar in a way to the try...catch statement found in other programming languages.
#Checks whether the value is a valid number:
def isNumber( value ):
try:
float( value )
return True
except:
return False
#Variables initialization:
numberOfGradesBelow50 = 0
sumOfAllGrades = 0
#Input:
for c in range( 0, 5 ):
currentGradeAsString = input( "What is the grade? " )
while not isNumber( currentGradeAsString ):
currentGradeAsString = input( "Invalid value. What is the grade? " )
currentGradeAsFloat = float( currentGradeAsString )
sumOfAllGrades += currentGradeAsFloat
if currentGradeAsFloat < 50.0:
numberOfGradesBelow50 += 1
#Displays results:
print( "The average is " + str( sumOfAllGrades / 5 ) + "." )
print( "You entered " + str( numberOfGradesBelow50 ) + " grades below 50." )