2016-05-27 2 views
0

Zusätzlich zur Bestimmung, ob eine Gleichung (str) ausgeglichen ist oder nicht, möchte ich bestimmen können, ob die Gleichung (str) mehr links oder rechts hat Klammern oder hat nicht übereinstimmende Klammern. Welche Änderungen/Ergänzungen muss ich am folgenden Code vornehmen, um das zu erreichen, was ich will?Auswuchtklammer - So ermitteln Sie, ob es weitere linke oder rechte Klammern gibt

brackets = ["()[]{}"] 
i = 0 
e = 1 
x = Stack() 

for a in s: 
    for pair in brackets: 
     if a == pair[i]: 
      x.push(a) 
     elif a == pair[e] and not x.is_empty() and x.pop() != pair[i]: 
      balanced = "Equation is not balanced" 
      return balanced 

if x.is_empty(): 
    balanced = "Equation is balanced" 
    return balanced 
else: 
    balanced = "Equation is not balanced" 
    return balanced 

Antwort

0

ich weiß nicht, die Stack in Ihrem Code, so verwende ich list statt.

brackets = ["()","[]","{}"] 
i = 0 
e = 1 

x = [] 

def check(s): 
    for a in s: 
     for pair in brackets: 
      if a == pair[i]: 
       x.append(a) 
      elif a == pair[e] and x and x.pop() != pair[i]: 
       balanced = "Equation is not balanced" 
       return balanced 

    if not x: 
     balanced = "Equation is balanced" 
     return balanced 
    else: 
     balanced = "Equation is not balanced" 
     return balanced 

s = "(({[]}))[]{}" 
print(check(s)) 
0

Diese Implementierung erfordert keine Stapel, nur einfache Variable Zähler:

def checkForBalanced(symbolString): 
    index = 0 
    temp = 0 
    while index < len(symbolString): 
     if symbolString[index] in ['(','{','[']: 
      temp++ 
     elif symbolString[index] in [')','}',']']: 
      temp-- 
     else: 
      pass 

    return temp 


def main(): 
    result = checkForBalanced("(2+3)-[(5-4)]") 
    if result>0: 
     print 'Equation has ',result,'more left brackets' 
    elif result<0: 
     print 'Equation has ',result,'more right brackets' 
    else: 
     print 'Balanced Equation' 
Verwandte Themen