0

这是 Python。我正在尝试编写一个程序,该程序在不使用全局变量的情况下向用户询问字符串输入。如果字符串只有并排的括号,那么它是偶数。如果它有字母、数字或括号被隔开,那么它是不均匀的。例如,() 和 ()() 和 (()()) 是偶数,而 (() 和 (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,否则您应该使用 raw_input 而不是 input,因为 input 会以与输入最匹配的任何类型返回结果,而 raw_input 总是返回一个字符串。在 Python 3 中,输入总是返回一个字符串。另外,你为什么要重新定义递归?只需从 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 回答