Search code examples
pythonlistmatrixaverageminimum

finding the minimum, maximum and average of different list in a 2D matrix (two-dimensional) in python


I'm trying to find the min, max, and average of each student after(or within) the matrix. How would I get access to the list of each student's scores within the loop iteration? I've started with finding the minimum within the function(findlowest()) but can't figure out how to get just 1 student's exam scores at a time.

studentExam = 5
minMaxScore = 5

def main():
    global studentName, studentExam, score, scoreList, examScoreMaxList, min, max


def ValidateUser(score):
    while score < 0 or score > 100:
        score = float(input("Invalid input, please try again"))
    return score


def getStudentInfo():
    studentName = int(input("enter the number of student: "))
    # studentExam = int(input("how many exam scores: "))
    # Initialize matrix
    matrix = []
    # For user input
    for i in range(studentName):  # A for loop for row entries
        scoreList = []
        scoreList.append(input("enter name of students " + str(i + 1) + ": "))

        for j in range(studentExam):  # A for loop for column entries

            score = float(input("enter exam " + str(j + 1) + ": "))
            score = ValidateUser(score)
            scoreList.append(score)
        matrix.append(scoreList)
    print(matrix)
    # for printing
    for i in range(studentName):
        for j in range(studentExam+1):
            print(matrix[i][j], end=" ")
        print()
getStudentInfo()


def findLowest():
    minlist = []
    min = minlist[0]
    for i in studentExam[0:5]:
        if i < min:
            min = i
    print("the minimum number is: ", min)

findLowest()

I would like the code to display something similar to the following:

Mike H: min score - 78
        max score - 94
        avg score - 85

Sarah G: min score - 78
         max score - 94
         avg score - 85

Solution

  • This should do it. You just needed a nested for loop.

    scores = [["Mike", 100, 98, 43, 56, 43], ["John", 95, 32, 79, 75, 67]]
    
    for arr in scores:
        #arr = ["Mike", 100, 98, 43, 56, 43] or ["John", 95, 32, 79, 75, 67]
        min = None
        max = None
        sum = 0
        studentName = None
        for i in arr:
            if type(i) != str:
                if not min or i < min:
                    min = i
    
                if not max or i > max:
                    max = i
    
                sum += i
            else:
                studentName = i
        avg = sum/5
    
        print(studentName + ": \t min score - " + str(min))
        print("\t max score - " + str(max))
        print("\t avg score - " + str(avg))
        print()