我有以下棋盘:
每个广场都是一个州。初始状态为“ a”。
给定用户要移动的正方形的颜色的输入,程序需要根据该输入找到所有可能的路线。
例如:如果输入是W(对于白色),我们从“ a”转到“ e”。如果输入是R(对于红色),我们将同时从“ a”转到“ b”和“ d”。
另一个更复杂的示例:如果输入是WR,则对于W,我们从“ a”到“ e”,然后对于R,同时从“ e”到“ b”,“ d”,“ f”和“ h” 。
我有以下python程序:
def chess (input):
A = []
current_state = "a"
A.append ([current_state])
switch = {"a": a, "b": b, "c": c, "d": d, "e": e, "f": f, "g": g, "h": h, "i": i}
new_state = ""
for k in input:
for j in current_state:
new_state = new_state + switch [j] (k)
A.append ([new_state])
current_state = new_state
new_state = ""
for x in range (len (A)):
print (A [x])
chess (input ())
该开关是一个字典,其中包含板的每个状态(正方形)的单独功能。这些函数返回根据某些输入可以移动到的状态字符串。
例如,对于状态a:
def a (character):
if character == 'R':
return "bd"
elif character == 'W':
return "e"
国际象棋函数以这种方式打印包含状态的矩阵:
对于输入WR,它给出以下输出:
['a']
['e']
['bdfh']
到目前为止一切顺利,但我需要将所有路线分开。对于相同的输入,我应该具有以下输出:
Route 1 : a, e, b
Route 2 : a, e, d
Route 3 : a, e, f
Route 4 : a, e, h
有什么想法如何从矩阵中获取信息吗?
最佳答案
完美的Python设备是递归生成器。任务显然是递归的,当您需要可以产生多个解决方案的函数时,生成器是理想的选择。递归生成器起初可能会有些令人生畏,但是如果您想进行这种状态机工作,它们当然值得花时间来熟悉它们。
为了存储状态数据,我使用了字典词典。我本可以编写代码来创建此数据结构,但是我决定将其硬编码会更快。对于较大的矩阵,情况可能并非如此。 ;)
switch = {
'a': {'W': 'e', 'R': 'bd'},
'b': {'W': 'ace', 'R': 'df'},
'c': {'W': 'e', 'R': 'bf'},
'd': {'W': 'aeg', 'R': 'bh'},
'e': {'W': 'acgi', 'R': 'bdfh'},
'f': {'W': 'cei', 'R': 'bh'},
'g': {'W': 'e', 'R': 'dh'},
'h': {'W': 'egi', 'R': 'df'},
'i': {'W': 'e', 'R': 'fh'},
}
def routes(current, path):
if not path:
yield (current,)
return
first, *newpath = path
for state in switch[current][first]:
for route in routes(state, newpath):
yield (current,) + route
def chess(path):
print('Path:', path)
for i, r in enumerate(routes('a', path), 1):
print('Route', i, end=': ')
print(*r, sep=', ')
print()
# tests
chess('WR')
chess('WWW')
chess('RRR')
输出
Path: WR
Route 1: a, e, b
Route 2: a, e, d
Route 3: a, e, f
Route 4: a, e, h
Path: WWW
Route 1: a, e, a, e
Route 2: a, e, c, e
Route 3: a, e, g, e
Route 4: a, e, i, e
Path: RRR
Route 1: a, b, d, b
Route 2: a, b, d, h
Route 3: a, b, f, b
Route 4: a, b, f, h
Route 5: a, d, b, d
Route 6: a, d, b, f
Route 7: a, d, h, d
Route 8: a, d, h, f
请注意,我们可以将字符串,元组或列表作为
path
的routes
arg传递。那作业first, *newpath = path
从路径中分离出第一项,随后的项以列表的形式分配给newpath。该语法适用于最新的Python 3版本;在早期的Python版本上,您需要将该行更改为
first, newpath = path[0], path[1:]
关于python - 在3X3棋盘上实现NFA的移动功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47107663/