我被要求编写一个模拟MU游戏的程序:postcss-import
假设有符号M,I和U可以组合以产生符号串。 MU难题要求一个人从“公理”字符串MI开始并将其转换为字符串MU,在每个步骤中使用以下转换规则之一:
Nr. Formal rule Informal explanation Example
--- ----------- -------------------------------------------- --------------
1. xI → xIU Add a U to the end of any string ending in I MI to MIU
2. Mx → Mxx Double the string after the M MIU to MIUIU
3. xIIIy → xUy Replace any III with a U MUIIIU to MUUU
4. xUUy → xy Remove any UU MUUU to MU
这是我到目前为止所做的:
string = input("Enter a combination of M, U and I: ")
while True:
if string and all(c in "MIU" for c in string):
print("This is correct")
break
continue
else:
print("This is incorrect")
break
rule = input("Enter a rule 1-4 or q to quit: ")
rule1 = (string+'U')
while True:
if rule == ('1') and string.endswith('I'):
print(rule1)
break
continue
elif rule == ('2') and string.startswith('M'):
但是,我坚持第二条规则。我假设它要求我从字符串的范围内的起点1打印字符串,因为M将是0,然后将它们一起添加以形成新的字符串?我不完全确定如何做到这一点。
答案 0 :(得分:1)
实施规则2的方法之一可能是:
if string1.startswith(('M')):
sub=string1[1:]
rule2=('M'+sub+sub)
print rule2
答案 1 :(得分:0)
怎么样?我尝试使用python
内置方法来操纵string
由于我使用的是Windows和Python 2.7,因此我必须将input
转换为raw_input
同时避免使用python
reserved words
作为string
作为variables
。这可能会导致python在variables
和literals
演示代码:
# -*- coding: utf-8 -*-
myStr = raw_input("Enter a combination of M, U and I: ")
while True:
if myStr and all(ch in "MIU" for ch in myStr):
print("This is correct")
break
else:
print("This is incorrect")
break
rule = raw_input("Enter a rule 1-4 or q to quit: ")
#Rule 1
# xI→xIU ; Add a U to the end of any string ending in I; e.g. MI to MIU
if rule == '1' and myStr.endswith('I'):
newStr = "".join((myStr,'U'))
print newStr
#Rule 2
# Mx → Mxx ; Double the string after the M ;MIU to MIUIU
elif rule == '2' and myStr.startswith('M') and not myStr.endswith('I'):
newStr = "".join((myStr,myStr[1:]))
print newStr
<强>输出:强>
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Enter a combination of M, U and I: MI
This is correct
Enter a rule 1-4 or q to quit: 1
MIU
>>> ================================ RESTART ================================
>>>
Enter a combination of M, U and I: MU
This is correct
Enter a rule 1-4 or q to quit: 2
MUU
>>>
>>>
Enter a combination of M, U and I: MIU
This is correct
Enter a rule 1-4 or q to quit: 2
MIUIU
>>>