1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| # (1, '0'):2中1是状态,‘0’是转换条件,2是满足转换条件后转到的状态 edges = {(1, '0'): 2, (1, '1'): 2, (1, '2'): 2, (1, '3'): 2, (1, '4'): 2, (1, '5'): 2, (1, '6'): 2, (1, '7'): 2, (1, '8'): 2, (1, '9'): 2, (2, '0'): 2, (2, '1'): 2, (2, '2'): 2, (2, '3'): 2, (2, '4'): 2, (2, '5'): 2, (2, '6'): 2, (2, '7'): 2, (2, '8'): 2, (2, '9'): 2}
# 接受的状态 acception = [2]
def fsmsim(string, current_state, edges, acception, pos=0): if pos >= len(string): return current_state in acception, string[:pos] else: letter = string[pos] if (current_state, letter) in edges: current_state = edges[(current_state, letter)] pos += 1 return fsmsim(string, current_state, edges, acception, pos) else: return False, string[:pos]
fsmsim('0', 1, edges, acception) >>> (True, '0')
fsmsim('06', 1, edges, acception) >>> (True, '06')
fsmsim('067', 1, edges, acception) >>> (True, '067')
fsmsim('067p', 1, edges, acception) >>> (False, '067')
|