Skip to content Skip to sidebar Skip to footer

How Can I Find Max Number Among Numbers In This Code?

class student(object): def student(self): self.name=input('enter name:') self.stno=int(input('enter stno:')) self.score=int(input('enter score:'))

Solution 1:

Similar to Rawing's answer, but instead of a lambda, you can use operator.attrgetter()

from operator import attgetter

class ...
    # You class code remains unchanged

y=[]
j=0while(j<3):
    a=student()
    a.student()
    y.append(a)
    j+=1


max_student = max(y, key=attrgetter('score'))
print("Highest score:", max_student.name, max_student.score)

Produces output like this:

entername:danenterstno:3enterscore:3entername:emilyenterstno:20enterscore:20entername:frankenterstno:1enterscore:1Highest score:emily20

Solution 2:

for b in y:
    max = b.score
    if man < b.score:
        max = b.score

You assign max to b.score, and in the next line you check if man < b.score.

  1. If this is your actual code, man is not defined anywhere so you will get a NameError.

  2. If this is not your actual code and just a typo and man is max, and in your code it is if max < b.score then this if will always be False, as you just assigned b.score to max in the line above.

Either way, why don't you simply use the built-in max function?

print(max(y, key=lambda student_obj:student_obj.score))

Solution 3:

You can use the max function with a custom key function:

b = max(y, key=lambda student: student.score)
print(b.stno, b.score)

Solution 4:

The max for loop should be like this:

# works only with non-negative numbersmax_val=0for b in y:ifmax_val<b.score:max_val=b.score

or use the max function as Rawing suggested.

-- Edited as Jim suggested

Post a Comment for "How Can I Find Max Number Among Numbers In This Code?"