2016-04-06 192 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 
>>>