Snappier Python 2.6 (272 karakter), Shorter
golf:
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])
ungolfed:
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))
menampilkan:
- kekacauan logis malas-dievaluasi!
- String gaya C!
- idiom beberapa perbandingan lucu!
- banyak yang jelek!
kredit untuk jawaban user300 untuk menggambarkan bagaimana hal-hal disederhanakan jika Anda bisa mendapatkan semacam nilai terminator ketika muncul kepala dari string kosong.
Saya berharap kepala / ekor membongkar dapat dilakukan inline selama deklarasi argumen m. maka m bisa menjadi lambda, sama seperti teman-temannya n dan glob. python2 tidak bisa melakukannya, dan setelah sedikit membaca, sepertinya python3 juga tidak bisa. duka.
pengujian:
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'