gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:33:10 26 4
gpt4 key购买 nike

我必须编写一个接受字符串作为参数并返回一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com