1

我必须编写一个接受字符串作为参数的函数,并返回一个布尔值(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

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

4

3 回答 3

2

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

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语句中时,它的计算结果为 false)。我们只是测试它是否是None,然后返回TrueFalse相应地返回。

于 2019-02-23T20:20:46.070 回答
1

你可以使用正则表达式:

import re


def chandler(test_str):
    return bool(re.fullmatch(r'^\d+(\ [+-/*//]\ \d+)*$', test_str))

print(chandler("1"))
# returns True
print(chandler("-1"))
# returns False
print(chandler("1 + 22"))
# returns True
print(chandler(" 1 + 22"))
# returns False
print(chandler("1 +"))
# returns False
print(chandler("1 22 * 333"))
# returns False
print(chandler("1  /  2"))
# returns False
print(chandler("23 + 45 - 17 * 2"))
# returns True

正则表达式分解:

'\d+'
    '\d'' matches any digit (0-9)
    '+' means at least once,
    so '\d+' means one or more digits i.e. a number

'(\ [+-/*//]\ \d+)*':
    '\ ' This matches a space
        (The '\' is redundant can just have ' ')
    '[+-/*//]' will match one of these: +.-,* or /
        (we need to escape '*' and '/' with a '/' because they are special characters)
    '\ ' again matches a space
    '\d+' again matches a number
    This block will match thing like ' + 16',
        we can have any number of these so we add a '*'
        this is like the '+' but allows us not to have any matches.
    So this means zero or more copies of <space><operator><space><number>
于 2019-02-23T20:16:34.277 回答
1

怎么每个人都把它复杂化了这么多?只是一行代码!

import re

def chandler(s):
    return bool(re.match(r'^\d+(\ [\+\-\*\/]\ \d+)*$', s))

简单地说,正则表达式从头到尾映射整个字符串,^期望$一个数字\d(至少一个数字+)。

它允许添加一个操作符号 ( [\+\-\*\/]),如果它们前面有一个空格,然后是另一个空格,然后是一个至少有一位数字的数字。

最后一部分可以使用 operator 重复多次*

于 2019-02-23T20:24:04.843 回答