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:emily20Solution 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.
If this is your actual code,
manis not defined anywhere so you will get aNameError.If this is not your actual code and just a typo and
manismax, and in your code it isif max < b.scorethen this if will always beFalse, as you just assignedb.scoretomaxin 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.scoreor 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?"