python - 检查基本表达式的有效性

标签 python python-3.x

我必须编写一个接受字符串作为参数并返回一个 bool 值(True 或 False)的函数,该值指示该字符串是否表示有效的基本表达式。

我必须假设这些有效表达式由一个或多个由基本运算符(仅 +、-、* 和/)分隔的 整数组成。字符串必须以整数开头和结尾。此外,一个空格必须始终分隔有效表达式中的整数和运算符。

例如:

>>> chandler("1") 
True
>>> chandler("-1") 
False 
>>> chandler("1 + 22") 
True 
>>> chandler(" 1 + 22") 
False # because this string starts with space 
>>> chandler("1 + ")
False 
>>> chandler("1 22 * 333")
False
>>> chandler("1  /  2")
False # because of two spaces instead of one
>>> chandler ("23 + 45 - 17 * 2")
True

我不知道如何以及从哪里开始。 我被允许只使用字符串和列表相关的东西(比如方法)

最佳答案

下面是一个如何使用正则表达式解决这个问题的例子:

import re

def chandler(s):
    regex = r'\d+( [+*/-] \d+)*'
    if re.fullmatch(regex, s):
        return True
    else
        return False

我们在这里做的是制作一个正则表达式字符串,指定要识别的模式,然后调用 fullmatch() 以确保整个字符串 s 与给定的匹配图案。让我们回顾一下其中的每一部分:

r'             # the beginning of a regex string
\d             # this is shorthand for "any digit" - e.g. the characters 0 through 9
\d+            # adding '+' to it means "we want at least one of these"
[+*/-]         # this specifies a *group* of these four operators we're looking for
( [+*/-] \d+)  # We're looking for a single space, followed by any of those four characters, 
               # followed by another single space, followed by at least one digit
( [+*/-] \d+)* # Adding '*' means "we want at least 0 of that entire expression in the parentheses

我们使用 re.fullmatch() 而不是 re 的其他方法之一来确保整个字符串与我们想要的匹配。如果我们使用 re.match(),那么它会匹配任何以数字开头的内容,无论字符串的其余部分是否不是我们想要的。

如果字符串匹配,

re.fullmatch() 返回一个正则表达式匹配对象,或者 None(当您将它放在 if 声明)否则。我们只是测试它是否为 None,并相应地返回 TrueFalse

关于python - 检查基本表达式的有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845659/

相关文章:

javascript - Flask Dynamic 依赖下拉列表

python - 使用 PIP 安装程序在 MAC OS X LION 10.7.2 上安装 PIL

带有另一个基类的 python 抽象方法破坏了抽象功能

python-3.x - Python 3 中 math.log2(x) 的时间复杂度是多少?

python - 编写一个程序,要求用户输入 5 个数字,并输出这些数字中最大的数字和最小的数字。

python - 在 admin tabularinline 中显示外键字段

python - Pandas Dtypewarning : How do I find the dtype of different cells in a column?

python - 由于 gcc 错误,无法使用 pip 安装 sasl

python-3.x - 检查元素是否在 python 列表中第一次出现

python - 为文件夹中的文件生成字典元素列表