2013-08-04 2 views
0

이것은 파이썬이다. 전역 변수를 사용하지 않고 사용자에게 문자열 입력을 요청하는 프로그램을 작성하려고합니다. 문자열에 괄호가 나란히있는 경우에는 짝수입니다. 글자, 숫자 또는 괄호 사이에 간격이 있으면 불균등합니다. 예를 들어,()와()(),())은 짝수이고 (()와 (pie)와()는 같지 않습니다.) 아래는 지금까지 작성한 내용입니다. 무한, 나는 지금 그 문제에 붙어있어 당신의 문자열 '을 입력합니다.괄호 프로그램 만들기? 나는 붙어있어

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을 입력 할 때까지는 "옵션을 선택하십시오 :"를 계속 인쇄합니다. 가장 최신 코드입니까? "Enter your string"프롬프트에 도달 할 수있는 방법을 모르겠습니다. – Kevin

+1

Kevin과 나는 둘 다 당신의 프로그램을 실행하면서 얻은 결과를 바탕으로 elic selection == 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

를 파이썬 3를 사용하지 않는 한, 당신이해야 raw_input은 항상 문자열을 반환하지만, input은 항상 문자열을 반환하는 반면, input은 항상 문자열을 반환하는 반면, 입력은 raw_input을 사용합니다. 엘프 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. 
관련 문제