61 lines
2.0 KiB
Python
61 lines
2.0 KiB
Python
|
# -*- coding:utf-8 -*-
|
||
|
# @Author len
|
||
|
# @Create 2023/12/12 19:49
|
||
|
|
||
|
def if_formula(text):
|
||
|
# 允许的字符:数字、运算符、括号、字母和空格
|
||
|
allowed_chars = "0123456789+-*/(). abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%^"
|
||
|
operators = "+-*/%^"
|
||
|
digits = "0123456789"
|
||
|
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||
|
|
||
|
# 检查字符是否合法
|
||
|
for char in text:
|
||
|
if char not in allowed_chars:
|
||
|
return False
|
||
|
|
||
|
# 括号匹配检查
|
||
|
bracket_count = 0
|
||
|
for char in text:
|
||
|
if char == '(':
|
||
|
bracket_count += 1
|
||
|
elif char == ')':
|
||
|
bracket_count -= 1
|
||
|
if bracket_count < 0: # 右括号多于左括号
|
||
|
return False
|
||
|
if bracket_count != 0: # 左括号和右括号数量不匹配
|
||
|
return False
|
||
|
|
||
|
# 去除空格,简化后续检查
|
||
|
s = text.replace(' ', '')
|
||
|
|
||
|
# 检查运算符、数字和字母的顺序
|
||
|
if s and (s[0] in operators or s[-1] in operators):
|
||
|
return False
|
||
|
for i in range(1, len(s) - 1):
|
||
|
if s[i] in operators and s[i + 1] in operators:
|
||
|
# 防止两个运算符连续出现
|
||
|
if not (s[i] in '-+' and s[i + 1] in '-+' and (s[i - 1] in operators or s[i - 1] == '(')):
|
||
|
return False
|
||
|
elif s[i] in digits and s[i + 1] in letters:
|
||
|
# 防止数字紧跟字母
|
||
|
return False
|
||
|
elif s[i] in letters and s[i + 1] in digits:
|
||
|
# 防止字母紧跟数字
|
||
|
return False
|
||
|
elif s[i] in letters and s[i + 1] in letters:
|
||
|
# 防止连续的字母
|
||
|
return False
|
||
|
elif s[i] in '()' and s[i + 1] in letters and s[i] == ')':
|
||
|
# 防止字母紧跟闭括号
|
||
|
return False
|
||
|
|
||
|
return True
|
||
|
|
||
|
|
||
|
list = ["124141", "AAAAAA", "AFF3241", "fafdafsfas",'A13C46', "124!@$%$%#@@#$%#@!@#$%#@!", "fsd65", "A1/2B%34", "((n*y+h)^4)/100"]
|
||
|
for i in list:
|
||
|
if if_formula(i):
|
||
|
print(i, "是")
|
||
|
else:
|
||
|
print(i, "不是")
|