【问题标题】:Print the students with the top marks打印得分最高的学生
【发布时间】:2021-05-08 20:21:41
【问题描述】:

问:打印所有得分最高的学生。如果多个学生的分数相同,请打印两个学生。

样本输出:

Best student(s): Micheal Murphy, Dan Smith
Best mark: 89 

我的代码:

import sys

def procfile(filename):
    try:
        with open(filename, 'r') as f:
            bestMark = -1
            for line in f:
                mark, name = line.strip().split(maxsplit=1)
                mark = int(mark)
                if mark > bestMark:
                   bestMark, bestStudent = mark, name
            print(f'Best student(s): {bestStudent}')
            print(f'Best mark: {bestMark}')

    except FileNotFoundError:
        print(f'The file {filename} cannot be opened')

procfile(sys.argv[1])

我得到的输出:

Best student(s): Michael Murphy
Best mark: 89

我的问题:

如何让它打印出多个获得最高分的学生? 我希望我的输出是

Best student(s): Micheal Murphy, Dan Smith
Best mark: 89 

【问题讨论】:

标签: python


【解决方案1】:

使用列表存储学生姓名:

def procfile(filename): 
    try:
        with open(filename, 'r') as f:
            bestMark = -1
            for line in f:
                mark, name = line.strip().split(maxsplit=1)
                mark = int(mark)
                # better mark: create new list
                if mark > bestMark:
                   bestMark, bestStudents = mark, [name]

                # same mark again: add to the list
                elif mark == bestMark:
                   bestStudents.append(name)
                   
            print(f'Best student(s): {", ".join(bestStudents)}')
            print(f'Best mark: {bestMark}')

    except FileNotFoundError:
        print(f'The file {filename} cannot be opened')

with open("t.txt", "w") as f:
  f.write("20 John\n30 Bill\n20 Lisa\n30 Nobody")
procfile("t.txt")

输出:

Best student(s): Bill, Nobody
Best mark: 30

你也可以做所有学生:

def procfile(filename):
    students = {}
    try:
        with open(filename, 'r') as f:
            bestMark = -1
            for line in f:
                mark, name = line.strip().split(maxsplit=1)
                mark = int(mark)
                students.setdefault(mark,[]).append(name)
                  
            print(f'All student(s):')
            for key in sorted(students, reverse=True):
                print(key, "by", ', '.join(students[key]))
          
    except FileNotFoundError:
        print(f'The file {filename} cannot be opened')

with open("t.txt", "w") as f:
  f.write("20 John\n30 Bill\n20 Lisa\n30 Nobody")
procfile("t.txt")

输出:

All student(s):
30 by Bill, Nobody
20 by John, Lisa

在计算上它并没有更糟,你只需要更多的内存来存储字典。如果您使用collections.defaultdict 而不是使用dict.setdefault 的普通字典来处理成千上万的学生,您可以加快程序的运行速度。

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2021-01-06
    • 1970-01-01
    • 2021-07-22
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多