语法规则文件,模拟图灵机接受一种语言

2024-04-23 17:07:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须创建一个语法规则文件,与python脚本一起使用,以接受某些字符串。你知道吗

语法:

Define a type 0 grammar that simulates a Turing Machine computation
to accept the language (w w | w ∊ (0 + 1)*}

脚本(有一个gui组件使运行更容易):

# Read in re-writing rules
#
start_symbol = 'S'
rules = []
def  browse():
    global start_symbol, rules
    start_symbol = 'S'
    rules = []
    fn_rules = askopenfilename(title="Select rules file", filetypes=[("*.TXT", "*.txt")])
    f_rules = open(fn_rules, "r")

    for line in f_rules.readlines():
        line = line.split()
        if len(line) < 2:
            if len(line) == 1 and len(line[0]) == 1:
                start_symbol = line[0]
            continue
        rules.append((line[0], line[-1]))

    f_rules.close()
    print(rules)

def init_str():
    tape.set('_' + start_symbol + tape.get() + '_')

从逻辑上考虑我的问题,我推断我需要用我的图灵机执行以下步骤(例如,输入10111011):

1: Place an end marker at each end of the string:
$10111011$

2: Move the end markers inward till they meet in the middle
 and mark the middle:
1011x1011

3: Go back and forth matching and crossing off symbols of the
 two strings.

我唯一的问题是如何实现这一点。下面是回文语法规则文件的示例:

L
_L0 → __A
_L1 → __B

0L → L0
1L → L1

A0 → 0A
A1 → 1A

B0 → 0B
B1 → 1B

0A_ → L__
1B_ → L__

_L_ → _x_
_A_ → _x_
_B_ →_ x_

根据我对这个程序的理解,它从左到右读取,显然只是在空白处分割每一行,并使用第一个字符串作为左侧,最后一个字符串作为右侧。但是,我不确定这是否正确。代码已更新


Tags: and文件the字符串in脚本len规则