【问题标题】:How do you write a program that checks if the input follows a syntax?你如何编写一个程序来检查输入是否符合语法?
【发布时间】:2021-10-30 13:13:04
【问题描述】:

不确定这是否是正确的提问地点,但我确实需要帮助找出我做错了什么。我想编写一个程序来检查我的输入是否符合语法。

这些是每个语法规则的五个函数:

def molecule(q):      
    atom(q)               # molecule starts with an atom
    if q.peek() == "":    # if the next letter in the queue is none(end of line) dequeue the letter (end function)
        q.dequeue()
    else:                 # otherwise check if the atom is followed by a number
        number(q)

def atom(q):
    capital_letter(q)     # atom could be a single upper case letter
    if q.peek() == "":    # if it's the end of the line dequeue the letter (end the function)
        q.dequeue()
    else:                 # if it's not the end of the line, check if its a lowercase letter
        lowercase_letter(q)

def capital_letter(q):    # checks for capital letters
    letter = q.dequeue()
    if letter.isupper():
        return
    raise Syntaxerror("Missing capital letter")

def lowercase_letter(q):  # checks for lowercase letters
    letter = q.dequeue()
    if letter.islower():  
        return
    raise Syntaxerror("Expecting lowercase letter")

def number(q):            # checks if numbers are greater than 2
    letter = q.peek()
    if int(letter) >= 2:
        return
    raise Syntaxerror("Expecting numbers greater than 2")

但是,在启动程序时,它并没有完全遵循语法。根据该程序工作的输入例如:Aa2 和 Ab 我得到的输出是(这是正确的):

Follows the syntax

但是,如下格式的输入不起作用(应该起作用):A、B12 和 A3。我得到的输入“A”的错误是:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

对于 A3 和 B12,我得到:

Wrong! Expecting lowercase letter

我看不出我在代码中哪里做错了,为什么它不符合语法,感谢您的帮助!

【问题讨论】:

    标签: python syntax


    【解决方案1】:

    在这里提出一个想法 - 为什么不使用正则表达式。如果你愿意,你可以解决它:

    import re
    num = '[0-9]'
    let = '[a-z]'
    LET = '[A-Z]'
    print(re.match(re.compile(f'(^{LET})|(^{LET}{let})'), 'Ss'))
    print(re.match(re.compile(f'(^{LET})|(^{LET}{let})'), 'sS'))
    

    【讨论】:

      【解决方案2】:

      首先,关于您的 LinkedQueue 的一些事情

      • 我认为你对dequeue 的看法是错误的,它不会停止该功能(它不应该停止)。这就是为什么你会得到一个 TypeErrorA:而不是停止函数,而是向你的 number 函数发送一个空队列。
      • 你的代码中有很多重复,我认为这段代码应该属于你的LinkedQueue(所有if peek=='': dequeue
      • 我不认为最后添加一个空字符串对你有帮助

      我不知道如何正确纠正这些问题,但LinkedQueue 需要认真反思。

      对于第二个错误,您的代码与您的规则相矛盾:小写字母是可选的,但您将其设为强制性。 lowercase_letter 函数不应引发任何错误。

      您的lowercase_lettercapital_letter 函数还有另一个问题:您在测试前出列。它现在保持沉默,因为如果测试失败,您将引发异常,但在另一种情况下,这种行为可能是意外结果的来源。假设您从lowercase_letter 中删除了异常,并且您的输入是A3:您弹出数字认为它是一个字母,现在您的堆栈为空。没有加注,所以你的代码返回并molecule 调用number 并再次抛出TypeError

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-21
        • 1970-01-01
        • 1970-01-01
        • 2022-06-25
        • 1970-01-01
        • 2016-10-18
        • 1970-01-01
        相关资源
        最近更新 更多