HJ68 成绩排序
题目链接
思路建立字典,key代表名字,value为数字,最后sorted函数按规定排序。注意名单中的名字会重名,所以key应该是名字加上编号,以免同名的分数被覆盖。将编号填充为3位数,方便最后输出名字的slice,即从第一位到倒数第三位,左闭右开。
代码
import sysn, order = int(input()), input()
dic = dict()
for i in range(n):inf = input().split(' ')dic[inf[0] + str(i).zfill(3)] = int(inf[1])if order == '0':for i in sorted(dic.items(), key = lambda x : x[1], reverse = True):print(i[0][:-3] + ' ' + str(i[1]))
else:for i in sorted(dic.items(), key = lambda x : x[1]):print(i[0][:-3] +' ' + str(i[1]))
HJ69 矩阵乘法
[题目链接](https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b?tpId=37&tqId=21292&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=)
思路
根据输入得到矩阵A,B,再直接根据题目中的公式计算乘积。
import sysx, y, z = int(input()), int(input()), int(input())
A = [[0] * y for _ in range(x)]
B = [[0] * z for _ in range(y)]
ans = [[0] * z for _ in range(x)]
for i in range(x):A[i] =[int(m) for m in input().split(' ')]
for i in range(y):B[i] = [int(m) for m in input().split(' ')]
for i in range(x):for j in range(z):cal = 0for k in range(y):cal += A[i][k] * B[k][j]ans[i][j] = cal
for i in range(x):out = [str(m) for m in ans[i]]print(' '.join(out))
HJ70 矩阵乘法计算量估算
思路:使用栈。遍历运算顺序,如果是左括号,跳过,如果是字母,就把字母对应的[行,列]写入栈中。如果遇到右括号,则弹出栈中最后两位,将乘法次数加入结果,把乘积得到的新矩阵的[行,列]加入栈。遍历结束后,如果栈中元素大于等于两个,就继续弹出两个,重复上述步骤,知道栈中只有一位元素。
代码
import sysn = int(input())
lis = []
for i in range(n):lis.append(list(map(int, input().split())))
op = input()
stack = []
ans = 0
for x in op:if x.isalpha():stack.append(lis[ord(x) - ord('A')])elif x == ')' and len(stack) >=2:m2, m1 = stack.pop(), stack.pop()ans += m1[0] * m1[1] * m2[1]new = [m1[0], m2[1]]stack.append(new)
while len(stack) >= 2:m2, m1 = stack.pop(), stack.pop()ans += m1[0] * m1[1] * m2[1]new = [m1[0], m2[1]]stack.append(new)print (ans)