五项一起对得上吗

👁️ 3 人浏览 💬 0 人评论 ❤️ 添加收藏

把这条路线算过的东西一次验完。运行下面这段程序:

import re

def is_snake(name):
    return re.fullmatch(r"[a-z_][a-z0-9_]*", name) is not None

import re

def lint(src, maxlen=45):
    out = []
    for i, l in enumerate(src, 1):
        if l != l.rstrip():
            out.append((i, "E101"))
        if len(l) > maxlen:
            out.append((i, "E102"))
        m = re.match(r"def\s+(\w+)\s*\(", l)
        if m and not is_snake(m.group(1)):
            out.append((i, "E201"))
    for i, l in enumerate(src, 1):
        m = re.match(r"\s*(\w+)\s*=\s*", l)
        if not m:
            continue
        name = m.group(1)
        used = any(re.search(r"\b" + name + r"\b", x)
                   for j, x in enumerate(src, 1)
                   if j != i and not re.match(r"\s*" + name + r"\s*=", x))
        if not used:
            out.append((i, "E301"))
    return sorted(out)

def run_formatter(src, maxlen=45):
    out = []
    for l in src:
        l = l.rstrip()
        if len(l) > maxlen and ", " in l:
            head, _, tail = l.partition("(")
            l = head + "(\n        " + tail.replace(", ", ",\n        ")
        out.append(l)
    return "\n".join(out).split("\n")

import collections
src = ['import os',
       '',
       'def CalcTotal(items):',
       '    total = 0   ',
       '    for i in items:',
       '        total = total + i   ',
       '    unused = 42',
       '    return total',
       '',
       'def calcAverage(items, weights, extra_config_value):',
       '    return CalcTotal(items) / len(items)']
names = ['items', 'total', 'unused', 'CalcTotal',
         'calcAverage', 'extra_config_value']
p = lint(src)
c = collections.Counter(code for _, code in p)
fixed = [l.replace("CalcTotal", "calc_total")
          .replace("calcAverage", "calc_average") for l in src]
ok = (len(p) == 6
      and sum(1 for n in names if is_snake(n)) == 4
      and len(lint(run_formatter(src))) == 3
      and c["E201"] == 2
      and len(lint(fixed)) == 4)
print(ok)
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论