Exercism: Bob (Python)

一道简单字符串匹配的题,不过这是我最近花时间最多的一道题了。原因是之前看了一下python的正则表达式,想说只用正则表达式来做。但是废了半天劲也没写出很满意的答案。

看了看其他人的答案,感觉1)还是直接使用isupper()比较简单, 2)把单个匹配条件拆分出来再来做组合。

原版:

import re
RESPONSES = {
    "^[\s]*$":"Fine. Be that way!",
    "^[A-Z]+\?$": "Calm down, I know what I'm doing!",
    "^[A-Z]+$": "Whoa, chill out!",
    "^.*\?$": "Sure.",
    ".*": "Whatever."
}
def response(hey_bob):
    msg = "".join([c for c in hey_bob if c.isalpha() or c =='?'])
    if not msg and hey_bob.strip():
        return "Whatever." 
    for pattern in RESPONSES:
        if re.search(pattern, msg.strip()):
            return RESPONSES[pattern]

改进版

import re

def is_question(msg):
    return msg.strip()[-1] == '?'
def is_empty(msg):
    return len(msg.strip()) == 0
def is_shouting(msg):
    return msg.isupper()

RESPONSES = {
    (is_empty,) :"Fine. Be that way!",
    (is_shouting, is_question): "Calm down, I know what I'm doing!",
    (is_shouting,): "Whoa, chill out!",
    (is_question,): "Sure.",
    (lambda x: True, ) : "Whatever." 
}
def response(hey_bob):
    for checks, res in RESPONSES.items():
        if all(check(hey_bob) for check in checks):
            return res

评论

此博客中的热门博文

拜厄练习曲44, 45

拜厄练习曲38, 39

Exercism: Anagram (Python)