【问题标题】:Making a Parentheses program? I'm stuck制作括号程序?我被困住了
【发布时间】:2013-08-04 16:41:03
【问题描述】:

这是 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()

【问题讨论】:

  • 什么是 def recursion(): recursion() under your elif selection == 2.
  • “我的程序不断打印'输入你的字符串'”。这很有趣,当我运行它时,它会一直打印“选择一个选项:”直到我输入 3。这是你最新的代码吗?我看不出你怎么能到达“输入你的字符串”提示符。
  • 根据 Kevin 和我都从运行您的程序中得到的信息,在我看来,如果您在 elic selection ==2 下取出 def 递归并放入 recursion(),一切正常。剩下的就是在 recursion() 中修复你的 if 语句来做你想做的事情

标签: python loops recursion input parentheses


【解决方案1】:

这会输出正确的偶数/非偶数答案。

 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...

【讨论】:

    【解决方案2】:

    除非您使用的是 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.
    

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2017-09-26
      • 2019-04-30
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多