PAT 1058 选择题 Python版(正则表达式)

这道题翻看了网上很多版本,貌似都没看到过怎么用正则表达式的写法,不知道是不是我的搜索姿势不太对。

思路:

  • 要解决的主要问题就是如何把括号()里的字母提取出来。我写的正则表达筛选有点丑,如果有更简洁的欢迎指出。
  • 提取括号里的内容并略过数字 flag = re.compile(r'[(][0-9](.*?)[)]')
  • 这时候筛出来的还包括空格,比如第一个人的答案[' a c', ' b d', ' a c', ' a b e']
  • 所以最后在一对一匹配的时候要用replace()函数用空代替空格

输入:
3 4
3 4 2 a c
2 5 1 b
5 3 2 b c
1 5 4 a b d e
(2 a c) (2 b d) (2 a c) (3 a b e)
(2 a c) (1 b) (2 a b) (4 a b d e)
(2 b d) (1 e) (2 b c) (4 a b c d)
输出:
3
6
5
2 2 3 4

import re
n, m = map(int, input().split())
score = []  # 每题的分数
true_ans = []  # 每题的正确答案
fault = [0 for i in range(m)]  # 统计错误信息
for i in range(m):
    info = input().split()
    score.append(int(info[0]))
    true_ans.append("".join(info[3:]))
    # true_ans 长这样['ac','b','bc','abde']

for i in range(n):
    stu_score = 0
    answer = input()
    flag = re.compile(r'[(][0-9](.*?)[)]')
    answer = flag.findall(answer)  # answer是个列表,可以输出看看内容
    for j in range(m):
        answer[j] = answer[j].replace(" ", "")   # 空替换空格
        if answer[j] != true_ans[j]:
            fault[j] += 1
        else:
            stu_score += score[j]
    print(stu_score)

mx = max(fault)
if mx == 0:
    print("Too simple")
else:
    ans = [str(mx)]
    for index, num in enumerate(fault, 1):
        if num == mx:
            ans.append(str(index))
    print(" ".join(ans))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值