python-3.xlistobjectlistobjectpython-object

How to find the minimum from a list of objects?


I want to write a method to find the minimum scored person and print his other details.

If I write a method to find minimum I can't print his other details. In question, it is told that to write "getMinRuns" in another class called Team.

python3

class Player:
    def __init__(self,playerName,playerCountry,playerScore):
        self.playerName=playerName
        self.playerCountry=playerCountry
        self.playerAge=playerScore

class Team:
    def getMinRuns(p):
        pass

n=int(input())
p=[]

for i in range(n):
    name=input()
    country=input()
    score=int(input())
    p.append(Player(name,country,score))
Team.getMinRuns(p)

Solution

  • As you are passing list of objects to the function getMinRuns you can traverse the list and read score for every single object which will help you in finding minimum scored object later you can print or write details of that object in the end of the function.

    def getMinRuns(p):
        min_score_index = 0
        for i in range(1, len(p)):
            if p[i].playerAge < p[min_score_index].playerAge:
                min_score_index = i
    
        print(p[min_score_index].playerName, p[min_score_index].playerCountry, 
        p[min_score_index].playerAge)
    

    I hope this might resolve your problem, feel free to ask question if you have any.