![](/img/trans.png)
[英]Checking validity of an expression that contains nested parentheses by using stack
[英]Checking the validity of a basic expression
我必須編寫一個接受字符串作為參數的函數,並返回一個布爾值(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
語句時結果為false)。 我們只是測試它是否為None
,然后相應地返回True
或False
。
您可以使用正則表達式:
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>
每個人如何使它過於復雜? 只是一行代碼!
import re
def chandler(s):
return bool(re.match(r'^\d+(\ [\+\-\*\/]\ \d+)*$', s))
簡而言之,正則表達式將整個字符串從開始^
映射到末尾$
期望一個數字\\d
(至少一位數字+
)。
如果在運算符( [\\+\\-\\*\\/]
)之前加一個空格,然后再加一個空格,再加上一個至少有一個數字的數字,則它可以添加一個符號。
最后的部分可以使用運算符*
重復多次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.