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()
4

2 に答える 2

0

Python 3 を使用していない限り、input の代わりに raw_input を使用する必要があります。これは、input は入力に最もよく一致する型で結果を返すのに対し、raw_input は常に文字列を返すためです。Python 3 では、input は常に文字列を返します。また、なぜ再帰を再定義しているのですか? elif ステートメントから呼び出すだけです。例:

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.
于 2013-08-04T16:58:45.607 に答える
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...
于 2013-08-04T16:57:00.913 に答える