优化以下代码:import sys p = [0] * 6 checked = [False] * 10010 u = [None] * 10010 class User: def init(self): self.id = 0 self.perfect = 0 self.rank = 0 self.mk = -1 # 判断是否有编译通过的提交 self.grade = [0, -1, -1, -1, -1, -1] def cmp(u): return -u.grade[0], -u.perfect, u.id if name == "main": al, idx = [] N, K, M = map(int, input().split()) p[1:K + 1] = map(int, input().split()) for i in range(M): tmp, pid, tmpgrade = map(int, input().split()) if not u[tmp]: u[tmp] = User() u[tmp].id = tmp if tmpgrade != -1: u[tmp].mk = 1 else: tmpgrade = 0 if tmpgrade > u[tmp].grade[pid]: u[tmp].grade[pid] = tmpgrade if checked[tmp]: continue else: checked[tmp] = True idx.append(tmp) for i in range(len(idx)): for j in range(1, K + 1): if u[idx[i]].grade[j] >= 0: u[idx[i]].grade[0] += u[idx[i]].grade[j] if u[idx[i]].grade[j] == p[j]: u[idx[i]].perfect += 1 else: continue if u[idx[i]].mk > 0: al.append(u[idx[i]]) al = sorted(al, key=cmp) for i in range(len(al)): if i == 0: al[i].rank = 1 else: if al[i].grade[0] == al[i - 1].grade[0]: al[i].rank = al[i - 1].rank else: al[i].rank = i + 1 print("{} {:05d}".format(al[i].rank, al[i].id), end="") for j in range(K + 1): if al[i].grade[j] >= 0: print(" {:d}".format(al[i].grade[j]), end="") else: print(" -", end="") if i != len(al) - 1: print()
时间: 2023-12-05 11:04:39 浏览: 158
下面是优化后的代码,主要是对一些繁琐的操作进行简化,如去掉无用的变量和列表,优化循环,使用列表推导式等。
```
class User:
def __init__(self):
self.id = 0
self.perfect = 0
self.rank = 0
self.mk = -1
self.grade = [0, -1, -1, -1, -1, -1]
def __lt__(self, other):
if self.grade[0] != other.grade[0]:
return self.grade[0] > other.grade[0]
elif self.perfect != other.perfect:
return self.perfect > other.perfect
else:
return self.id < other.id
if __name__ == "__main__":
N, K, M = map(int, input().split())
p = [0] + list(map(int, input().split()))
u = [None] * (N + 1)
idx = []
for i in range(M):
tmp, pid, tmpgrade = map(int, input().split())
if not u[tmp]:
u[tmp] = User()
u[tmp].id = tmp
if tmpgrade != -1:
u[tmp].mk = 1
else:
tmpgrade = 0
if tmpgrade > u[tmp].grade[pid]:
u[tmp].grade[pid] = tmpgrade
if not idx.__contains__(tmp):
idx.append(tmp)
for i in range(len(idx)):
for j in range(1, K + 1):
if u[idx[i]].grade[j] >= 0:
u[idx[i]].grade[0] += u[idx[i]].grade[j]
if u[idx[i]].grade[j] == p[j]:
u[idx[i]].perfect += 1
al = sorted([u[i] for i in idx if u[i].mk > 0])
for i in range(len(al)):
if i == 0:
al[i].rank = 1
else:
if al[i].grade[0] == al[i - 1].grade[0]:
al[i].rank = al[i - 1].rank
else:
al[i].rank = i + 1
for i in range(len(al)):
print("{} {:05d}".format(al[i].rank, al[i].id), end="")
for j in range(K + 1):
if al[i].grade[j] >= 0:
print(" {:d}".format(al[i].grade[j]), end="")
else:
print(" -", end="")
if i != len(al) - 1:
print()
```
需要说明的是,这里的排序方法使用了魔术方法`__lt__`来实现,它可以使得类的实例对象可以直接进行比较,从而可以方便地使用 `sorted` 等内置函数进行排序。
阅读全文