更短的Snappier Python 2.6(272个字符)
打高尔夫球:
n=lambda p,s:p[0]==s[0]and m(p[1:],s[1:])
def m(p,s):
q,r,t,u=p[0],p[1:],s[0],s[1:]
return any((q=='?'and(t and m(r,u)),q=='+'and(t and(m(p,u)or m(r,u))),q=='*'and(m(r,s)or(t and m(p,u))),q=='\\'and n(r,s),q==t==0))or n(p,s)
glob=lambda*a:m(*[list(x)+[0]for x in a])
松开
TERMINATOR = 0
def unpack(a):
return a[0], a[1:]
def terminated_string(s):
return list(s) + [TERMINATOR]
def match_literal(p, s):
p_head, p_tail = unpack(p)
s_head, s_tail = unpack(s)
return p_head == s_head and match(p_tail, s_tail)
def match(p, s):
p_head, p_tail = unpack(p)
s_head, s_tail = unpack(s)
return any((
p_head == '?' and (s_head and match(p_tail, s_tail)),
p_head == '+' and (s_head and(match(p, s_tail) or match(p_tail, s_tail))),
p_head == '*' and (match(p_tail, s) or (s_head and match(p, s_tail))),
p_head == '\\' and match_literal(p_tail, s),
p_head == s_head == TERMINATOR,
)) or match_literal(p, s)
def glob(p, s):
return match(terminated_string(p), terminated_string(s))
特色:
- 懒惰的逻辑混乱!
- C风格的弦乐!
- 可爱的多重比较习语!
- 够丑!
归功于user300的答案,它说明了当从空字符串中弹出头部时,如果可以得到某种终止符值,将如何简化。
我希望可以在声明m的参数期间以内联方式执行头/尾的拆包。那么m可能是lambda,就像它的朋友n和glob一样。python2无法做到这一点,经过一番阅读后,看来python3也无法做到这一点。祸了。
测试:
test_cases = {
('abc', 'abc') : True,
('abc', 'abcdef') : False,
('a??', 'aww') : True,
('a*b', 'ab') : True,
('a*b', 'aqwghfkjdfgshkfsfddsobbob') : True,
('a*?', 'a') : False,
('?*', 'def') : True,
('5+', '5ggggg') : True,
('+', '') : False,
}
for (p, s) in test_cases:
computed_result = glob(p, s)
desired_result = test_cases[(p, s)]
print '%s %s' % (p, s)
print '\tPASS' if (computed_result == desired_result) else '\tFAIL'