Python 检查括号的数量,如果';(';和';)';括号
我试图计算输入数学表达式中括号的数量。若右括号不多于左括号,程序应提示用户告诉他们错误:Python 检查括号的数量,如果';(';和';)';括号,python,python-3.x,Python,Python 3.x,我试图计算输入数学表达式中括号的数量。若右括号不多于左括号,程序应提示用户告诉他们错误: "Unexpected right parenthesis between _ and _" 例如: expression = ( ( 1 + 2 ) ) ) ) output: Unexpected right parenthesis between ( ( 1 + 2 ) ) and ) ) 问题:如何获得((1+2))和()之间的索引以打印出所需的输出 下面是我现在拥有的代码。我感谢任何能帮我的人
"Unexpected right parenthesis between _ and _"
例如:
expression = ( ( 1 + 2 ) ) ) )
output: Unexpected right parenthesis between ( ( 1 + 2 ) ) and ) )
问题:如何获得((1+2))和()之间的索引以打印出所需的输出
下面是我现在拥有的代码。我感谢任何能帮我的人。多谢各位
tokenList = []
countLeft = 0
countRight = 0
mark1 = []
mark2 = []
expression = input("Enter an expression: ")
for i in expression.split(" "):
tokenList.append(i)
for i in range(len(tokenList)):
if tokenList[i] == '(':
countLeft += 1
if tokenList[i] == ')':
countRight += 1
if countLeft < countRight:
for i in range(len(tokenList)):
if tokenList[i] == '(': # this is to store the index of '('
mark1.append(i)
for i in range(len(tokenList)):
if tokenList[i] == ')': # this is to store the index of ')'
mark2.append(i)
while (' and ')' in tokenList:
tokenList.pop(mark1[-1])
mark1.pop(-1)
mark2.pop(0)
print("Unexpected right parenthesis between _ and _")
if countRight < countLeft:
print(f"There is {countLeft - countRight} unclosed left parenthesis in {expression}")
tokenList=[]
countLeft=0
countRight=0
mark1=[]
mark2=[]
表达式=输入(“输入表达式:”)
对于表达式中的i.split(“”):
tokenList.append(i)
对于范围内的i(len(令牌列表)):
如果令牌列表[i]=='(':
countLeft+=1
如果令牌列表[i]==')':
countRight+=1
如果countLeft
您可以遍历字符串并找到括号不匹配的第一个点。一种方法是,如果你找到一个(
),只需将1
加到某个总数中(如果你找到一个),则减去1
)
。如果此数字变为<0
,则表示不匹配(如果字符串末尾大于0)。大概是
def find_mismatched_brackets(expression):
out = "Unexpected right parenthesis between {} and {}"
stack = 0
for i, j in enumerate(expression):
stack += 1 if j == '(' else -1 if j == ')' else 0
if stack < 0:
return out.format(expression[:i], expression[i:])
find_mismatched_brackets('( ( 1 + 2 ) ) ) )')
这是堆栈的完美候选。如果循环字符串中的所有字符,并且每次遇到“(“将其推送到堆栈中,每次找到“)”)时,都会从堆栈中弹出“(” 最后,如果一切都正确,你将得到一个空堆栈。或者,当堆栈为空时,你会发现一个右括号。也就是说,当你知道你有一个不平衡的表达式时 大概是这样的:
expr = "(( a + b ))))"
stack = []
for idx, char in enumerate(expr):
if(char == '('):
stack.append(char)
if(char == ')'):
if(len(stack) == 0):
print('Unexpected right parenthesis between {0} and {1} '.format(expr[:idx], expr[idx:]))
break
else:
stack.pop()
stack+=1 if j='('else-1 if j=')'else 0
是一个非常笨拙的表达式,但实际上读起来非常好。@madpysicator是的,我在思考是否包括它:)另一种选择是在循环之外定义一个字典,例如valid_chars={'(':1'):-1}
然后将堆栈+=…
行替换为堆栈+=有效字符。获取(j,0)
非常感谢大家!!堆栈似乎有点过分了,除非你处理的是多种不同类型的分组符号。同意,出于某种原因,我的大脑无法想出像计数器这样简单的东西。。。
expr = "(( a + b ))))"
stack = []
for idx, char in enumerate(expr):
if(char == '('):
stack.append(char)
if(char == ')'):
if(len(stack) == 0):
print('Unexpected right parenthesis between {0} and {1} '.format(expr[:idx], expr[idx:]))
break
else:
stack.pop()