Python - output of function doesn't take in all requirements - python

We are quite new to the programming world, so excuse us if we're blind for an easy improvement.
We are making a system which has to order grades given to students.
We have already made a function that can round grades up - it's a request.
Now we have to make a function which can find the mean value of a given sets of grades. But there are some requirements:
If there is only one grade given - this must be the final grade (this works)
If there are more than one grade it must delete the lowest grade (this should also work because we have sorted the numbers.
THE PROBLEM: If there is a grade minus three (-3) given to a student - this grade must be the final grade of one vector of grades.
This is our code:
def computeFinalGrades(grades):
meanGrades = []
N = np.size(grades[:,0])
M = np.size(grades[0,:])
for i in range(N):
if M == 1:
grades = grades
elif M >= 2:
grades = np.sort(grades)
if -3 in grades[:,1}:
meanGrades.append(-3)
else:
grades = np.delete(grades,[0],axis=1)
meanGrades.append(np.mean(grades))
gradesFinal = roundGrade(meanGrades)
return gradesFinal
Thank yoooooou! And have a nice day! :-)

This line looks broken:
if -3 in grades[:,1}:
Maybe you where going to do this:
if -3 in grades[:,1]:
This line looks totally useless:
grades = grades

Related

How do I drop one of the inputs on this for loop?

I am doing an assignment where I need to calculate an average grade, in one part I have a for loop where it takes the input of 5 quiz grades, I can't figure how to drop the lowest grade out of the ones entered during calculation.
print("Please enter 5 quiz grades.")
print("\t")
for i in range(5):
quizgrade = float(input("Quiz grade: "))
quizgradetotal += quizgrade
print("\t")
here is the code so far.
I have tried changing the loop, but I can't figure it out.
One of the ways you can approach this is to store each entered quiz grade in a list. Then you can drop the lowest grade once you know all of the grades:
quizgrades = [] # Initialize an empty list
print("Please enter 5 quiz grades.")
print("\t")
# Grab all 5 quiz grades
for i in range(5):
quizgrades.append(float(input("Quiz grade: ")))
# Now remove the lowest number from the list
quizgrades.remove(min(quizgrades))
# Now that you have a list with the lowest grade dropped, you can easily calculate the average
average = sum(quizgrades) / len(quizgrades)
print(average)
one solution is to store all your inputs in one array
gards = []
for i in range(5):
gards.append(float(input("Quiz grade: ")))
then remove the lowest grade :
gards.remove(min(gards))
finally you calculate the average of the array :
average = sum(gards) / 4
your solution is good you can overwrite the sum on every input by adding the new value then calculate the average. but the problem is that you will never know which one is the lowest once the loop is over.

Dividing a string by an integer to get GPA calculation

I am working on Python and am writing a program where the user inputs how many courses they would like to calculate. Then the program is supposed to take the appended items (the strings) and then divide them by how many courses they would like, in other words the total (integer). I cannot seem to figure out a way to implement this properly, any help? The issue is under If value = 1.
if (value == 1):
selection = int(input("How many classses would you like to include?\n"))
for i in range (0,selection):
print("What is the grade of the class?")
item = (input())
grades.append(item)
GPA_list = [sum(item)/selection for i in grades]
print(GPA_list)
You can simplify this quite a bit by using mean, which does the summing and dividing for you:
>>> from statistics import mean
>>> print(mean(
... float(input(
... "What is the grade of the class?\n"
... )) for _ in range(int(input(
... "How many classes would you like to include?\n"
... )))
... ))
How many classes would you like to include?
5
What is the grade of the class?
4
What is the grade of the class?
3
What is the grade of the class?
4
What is the grade of the class?
2
What is the grade of the class?
4
3.4
To fix your existing code, all you need to do is make sure to convert item to a float and then call sum on grades rather than each item:
grades = []
selection = int(input("How many classses would you like to include?\n"))
for i in range(0, selection):
print("What is the grade of the class?")
item = float(input())
grades.append(item)
GPA_list = sum(grades) / selection
print(GPA_list)
Note that your code prints a fraction of the average at each step in the loop until finally printing the correct result in the last iteration; if you want to fix this as well, unindent the last two lines.

Having trouble with input validation/ excluding the highest value/lowest value

I am very, very, VERY new to programming. So far I am really enjoying this class. However lately the programming challenges have been a bit confusing and daunting. The most current challenge I'm on has me scratching my head as I can find no help in my book nor online. In a nutshell I need to create a program that takes the score of five judges in a range of 0-10, exclude the highest and lowest scores given and then calculate the average of the remaining three scores. While I understand how to validate user input for a single value and compute the average, I have no idea how to validate user input for all 5 inputs without doing anything too tedious, and exclude the highest score and lowest score that the user inputs. I have some idea of what I need to do. Take the user input as a float, then transfer it to a function that takes the highest and lowest scores then send it to another function that will compute the average. If anyone could help me with this I'll be really grateful. Below is what I've worked out so far. Thank you in advance.
def getJudgeData():
badEntry = True
while (badEntry) :
judge1 = float (input("Please enter the first judge's score : "))
if (judge1 < 0 or judge1 > 10) :
print ("The score must be greater than 0 and less than or equal to 10!")
else:
badEntry = False
while (badEntry) :
judge2 = float (input("Please enter the second judge's score : "))
if (judge2 < 0 or judge2 > 10) :
print ("The score must be greater than 0 and less than or equal to 10!")
else:
badEntry = False
Below code will ask to input a score 5 times, that is why the loop in a range of 5. It will throw a value error if the user's input is not an integer. If you want float, you can change that to a float. If the user input is more than 10, it will prompt the user to inout numbers in the correct range. Then the calculate_average function returns the average rounded to two decimal places, you can change that if needed more or less decimal places.
I was not sure what you meant by subtracting max and min values, so I removed then from the scores. But if I misunderstood, just leave them in there, and then calculate average as normal.
scores = []
def getJudgeData():
for i in range(5):
try:
judge_score = int(input("Please enter the first judge's score : "))
if (judge_score in range(11)):
scores.append(judge_score)
else:
print('Enter a score from 1 to 10')
except ValueError:
print("Enter a valid number")
def calculate_average():
max_value = max(scores)
min_value = min(scores)
scores.remove(max_value)
scores.remove(min_value)
average = sum(scores)/len(scores)
return round(average, 2)
getJudgeData()
print(calculate_average())

Trying to get the function to take 4 test scores and determine the students average score out of 320 points

def getExamPoints(examPoints):
for examPoints in range(1, 5):
examPoints = input("Please enter students exam scores: ")
totalPoints = input("Please enter total possible points: ")
print("The total exam points are: " + sum(int(examPoints)))
avg = float(int(str(examPoints))/int(totalPoints))
print("the average is: ", avg)
on Line 5 I am getting the error 'int object is not iterable'
and I have no idea why.
I am attempting to write a program with functions and this portion of the function is suppose to take four homework scores each out of eighty points and calculate the average of the scores and then take that average and multiply it by the percentage that homework is worth for the class, but I cant even seem to get this chunk of the program to get an average of homework scores. I am not very good with python, also if this isn't formatted correctly I apologize in advance, but any help would be much appreciated.
examPoints is not a list of inputs in the original code, but just one variable that gets overwritten with each iteration of the user-input loop:
for examPoints in range(1, 5):
examPoints = input("Please enter students exam scores: ")
Instead, you want to keep each input separately.
e.g. by appending it to a list:
examPoints = []
for _ in range(1,5):
# add input to list after converting it to an integer
examPoints.append(int(input("Please enter students exam scores: ")))
...
The input-text-to-integer conversion can be done either as you are appending (return error to user immediately upon input that can't be converted), or when you're performing the sum, by using a list comprehension or the map function:
# sum version
sum([int(v) for v in examPoints])
# map version
sum(map(int, examPoints))
Sorry, but (In my opinion) your code is a bit messy. Instead, try:
def getExamPoints(examPoints):
points = []
for examPoints in range(1, 5):
points = points + [int(input("Please enter students exam scores: "))]
totalPoints = input("Please enter total possible points: ")
print("The total exam points are: " + sum(examPoints))
avg = float(int(str(examPoints))/int(totalPoints))
print("the average is: ", avg)
what sum() looks for is an iterable object, like a list, and adds together everything in it. Since examPoints is defined as an integer, it is not iterable. Instead, make a separate list, and put the input inside there.

Python3 about Loops Iteration multiple variable simple algorithm

What i have to do is have T number of test cases which is how many time i will
obtain the average of "n" number of students in each test case and i need to display the average score for each test case and the highest mark in that test case and the name of student
If you can tell me the proper way to code this and explain why it has to be that way i will greatly appreciate it! I am lost
My code:
t = int(input("enter number of cases: "))
def casing(t):
for case in range (1, t+1):
n = int(input("enter number of students: "))
def studentmarks(n):
total = 0
student = "none"
for computetotal in range(1,n+1):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
highestmark = mark
if studentmark(n) > mark:
highestmark = mark
achieve = student
return highestmark, acheive
return total, studentmark()[0], studentmark()[1]
average = float((studentmarks(n)[0])/ n)
print("average: ", average, "highest: ",studentmark(n)[1], "student: ", studentmark(n)[2])
I think the code, as it is, would be much simpler to understand and debug without the function declarations. Unless you're doing functional-style programming (e.g. passing around function objects) there's rarely a good reason to use nested functions. Here you're defining the functions, then immediately calling them once, which is fairly pointless. So here's a simplified version of your code:
t = int(input("enter number of cases: "))
for _ in range (t):
total = 0
highest_mark = 0
best_student = "none"
n = int(input("enter number of students: "))
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
if mark > highestmark:
highestmark = mark
beststudent = student
average = total / n
print("average: {}, highest: {}, student: {}"
.format(average, highestmark beststudent))
I also eliminated the function named studentmark (with no "s") which your code was calling but never defined. I'm not sure if I correctly interpreted what it was supposed to be doing, but I think so. It certainly wouldn't have worked before.
There are a few reasons this isn't working - but the root cause seems to be because your highestmark is started off in the wrong place. It looks like you later expect the student name and mark to be in a tuple, which is a good idea - but you never actually make this tuple anywhere. So, make one, and call it highest - it replaces both the student and highestmark variables. Start it as None instead of "none" (which could actually be a valid student name!), so you have above the loop:
total = 0
highest = None
and change your "is this one higher than the highest" logic to this:
if highest is None or mark > highest[1]:
highest = (name, mark)
Read as "if there is no highest student yet, or this one has a higher mark than the current highest, this one is the highest". Then you'll want the return to be:
return total, highest[0], highest[1]
But, since you only have a small amount of data (enough that it is feasible to have a user type it in at a console), then you can simplify this logic quite a bit. Read all of the data for a particular test case into a list of (student, mark) tuples, and then use Python's builtins to do the calculations:
def studentmarks(n):
marks = []
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
marks.append(student, mark)
return marks
# Calculations
marks = studentmarks(5)
print('Average: ', sum(result[1] for result in marks)/len(marks))
print('Highest: ', max(marks, key=lambda s: s[1])
Seeding it with:
>>> marks
[('Fred', 4), ('Wilma', 10), ('Barney', 8), ('Wilma', 7), ('Pebbles', 6)]
Gives an average of 7.0, and a maximum of ('Wilma', 10).

Categories