内容:
对于XN+1或XN*2图灵机进行模拟,任意给定的十进制数a,转换为收缩扩展二进制的编码,再编程模拟此Turing机的运行过程,要求输出从开始运行起的每一步骤的结果。 用C或C++或java或python语言实现程序解决问题
步骤:
- 算法分析
(1):输入一个十进制数后转化为二进制数并对其进行扩充并多加几个0防止最后结果出现问题。
(2):使用列表存储,读取内态和输入太,并用if语句选择执行的命令,最后输出每步执行的结果
(3):将最终得到的列表一的扩充码进行缩减得到通常的二进制码(即将110—,,10—1,并且除去第一个1之前的0和,后的0),最终将其转化为10进制数,
1)调用bin()对十进制的数值进行转换
2)图灵机的运行过程:用if选择语句挑选执行的命令语句并用list改变内态
list2 = 0 #list2用于存储图灵机的内态
for i ,j in enumerate(list1):
print("xn*2图灵机第",end="")
print(i+1,end="")
print("次运行结果:")
if j == '0' and list2 == 0:
list1[i] = '0'
list2 = 0
print(list1)
elif j == '1' and list2 == 0:
list1[i] = '0'
list2 = 1
print(list1)
elif j == '0' and list2 == 1:
list1[i] = '1'
list2 = 0
print(list1)
elif j == '1' and list2 == 1:
list1[i] = '0'
list2 = 10
print(list1)
elif j == '0' and list2 == 10:
list1[i] = '1'
list2 = 11
print(list1)
elif j == '0' and list2 == 11:
list1[i] = '1'
list2 = 0
print(list1)
3)最后扩充编码的缩减以及转换为十进制数:
s = "".join(list1)
s1 = s.replace('110', ',')
s1 = s1.rstrip('0')
s2 = s1.replace(',', '') # 将扩充和增加的部分去除
print("xn*2图灵机运行完成后的编码:", end="")
print(s2)
s3 = s2.replace('10', '1') # xn*2图灵机执行完成后的编码形式转化成二进制编码
print("转化为二进制编码为:", end="")
print(s3)
n = int(s3, base=2) # 将二进制数转化为整数
print("最终结果为:", end="")
print(n)
源代码:
import math
print("请输入一个十进制数:")
x = int(input())
a = bin(x)
a = bin(x).replace("0b", '0')
print("该数的二进制数为:"+ a )
y = a + ','
z = y.replace('1', '10')
w = z.replace(',', '110')
list1 = list(w)
print("该数的二进制扩充为:")
print(w)
for i in w:
list1.append('0')
print("xn*2图灵机所需编码列表",end="")
print(list1)
def operation():
list2 = 0 #list2用于存储图灵机的内态
for i ,j in enumerate(list1):
print("xn*2图灵机第",end="")
print(i+1,end="")
print("次运行结果:")
if j == '0' and list2 == 0:
list1[i] = '0'
list2 = 0
print(list1)
elif j == '1' and list2 == 0:
list1[i] = '0'
list2 = 1
print(list1)
elif j == '0' and list2 == 1:
list1[i] = '1'
list2 = 0
print(list1)
elif j == '1' and list2 == 1:
list1[i] = '0'
list2 = 10
print(list1)
elif j == '0' and list2 == 10:
list1[i] = '1'
list2 = 11
print(list1)
elif j == '0' and list2 == 11:
list1[i] = '1'
list2 = 0
print(list1)
def changeList():
s = "".join(list1)
s1 = s.replace('110', ',')
s1 = s1.rstrip('0')
s2 = s1.replace(',', '') # 将扩充和增加的部分去除
print("xn*2图灵机运行完成后的编码:", end="")
print(s2)
s3 = s2.replace('10', '1') # xn*2图灵机执行完成后的编码形式转化成二进制编码
print("转化为二进制编码为:", end="")
print(s3)
n = int(s3, base=2) # 将二进制数转化为整数
print("最终结果为:", end="")
print(n)
operation()
changeList()