2016-04-06 107 views
-2

我被要求写,模拟MU游戏的程序:https://en.wikipedia.org/wiki/MU_puzzle在python追加字符字符串

假设有符号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点,然后将它们加在一起形成一个新的字符串?我不完全确定如何做到这一点。

+1

请修正您的代码的缩进 – skrrgwasme

+0

最新的错误是什么?它在我执行时有效 – discord1

+0

有点像's ='M'+ s [1:] * 2'? – soon

回答

1

一个实施规则2可能的途径:

if string1.startswith(('M')): 
    sub=string1[1:] 
    rule2=('M'+sub+sub) 
    print rule2 
0

以下情况如何?我尝试使用python内置方法来操作string
由于我使用的是Windows和Python 2.7,我不得不input转换为raw_input

此外,还要避免使用pythonreserved wordsstringvariables。这可能会导致与蟒蛇的问题感到困惑variablesliterals代码之间

演示:

# -*- 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 
>>>