2013-08-04 41 views
0

這是Python。我試圖編寫一個程序,要求用戶輸入字符串而不使用全局變量。如果字符串只有並列的括號,那麼它就是偶數。如果它包含字母,數字或括號,則不均勻。例如,()和()()和(()())是偶數,而(()和(餡餅)和()不是。下面是我迄今爲止寫的。輸入您的字符串」無限,我堅持用這個問題現在。製作小括號程序?我被卡住

selection = 0 
def recursion(): 
#The line below keeps on repeating infinitely. 
    myString = str(input("Enter your string: ")) 
    if not myString.replace('()', ''): 
     print("The string is even.") 
    else: 
     print("The string is not even.") 

while selection != 3: 
    selection = int(input("Select an option: ")) 

    #Ignore this. 
    if selection == 1: 
     print("Hi") 

    #This won't work. 
    elif selection == 2: 
     def recursion(): 
      recursion() 
+0

什麼是高清遞歸():遞歸()在你的elif選擇== 2 – sihrc

+1

_「我的程序不斷上打印‘請輸入您的字符串’無限」 _。這很有趣,當我運行它時,它會一直打印「選擇一個選項:」,直到我輸入3爲止。這是您的最新代碼嗎?我沒有看到你甚至可以達到「輸入你的字符串」提示。 – Kevin

+1

根據凱文和我都運行你的程序,它看起來像我一切工作,如果你只是在elic選擇== 2下取出你的def遞歸,並且只需要遞歸遞歸()。剩下的就是在遞歸()中修復if語句以做你想做的事情 – sihrc

回答

0

此輸出正確連/甚至沒有答案。

selection = 0 
def recursion(): 
    myString = str(raw_input("Enter your string: ")) #Use raw_input or () will be() 
    paren = 0 
    for char in myString: 
     if char == "(": 
      paren += 1 
     elif char == ")": 
      paren -= 1 
     else: 
      print "Not Even" 
      return 

     if paren < 0: 
      print "Not even" 
      return 
    if paren != 0: 
     print "Not even" 
     return 
    print "Even" 
    return 

while selection != 3: 
    selection = int(input("Select an option: ")) 

    #Ignore this. 
    if selection == 1: 
     print("Hi") 

    #This won't work. 
    elif selection == 2: 
     recursion() #This isn't a recursive function - naming it as so is... 
0

除非你使用Python 3,你應該使用raw_input而不是輸入,因爲輸入以任何類型匹配最好的輸​​入爲結果,而raw_input總是返回一個字符串。在Python 3中,input總是返回一個字符串。此外,爲什麼要重新定義遞歸? elif s tatement。例如:

selection = 0 
def recursion(): 
#The line below keeps on repeating infinitely. 
    myString = raw_input("Enter your string: ") # No need to convert to string. 
    if not myString.replace('()', ''): 
     print("The string is even.") 
    else: 
     print("The string is not even.") 

while selection != 3: 
    selection = int(raw_input("Select an option: ")) 

    #Ignore this. 
    if selection == 1: 
     print("Hi") 

    #This won't work. 
    elif selection == 2: 
     recursion() # Just call it, as your program already 
        # recurs because of the if statement.