Пример #1
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    #a=list(expr)
    #print(a)
    #b=0
    S = Stack()
    l = len(expr)
    i = 0
    while i != l:
        symb = expr[i]
        i = i + 1

        if symb == '{' or symb == '[' or symb == '(':
            t = symb
            S.push(symb)

        elif symb == '}' or symb == ']' or symb == ')':
            if S.isEmpty():
                return False
            else:
                left = S.pop()
            if not match(left, symb):
                return False

    if S.isEmpty():
        return True
    else:
        return False
Пример #2
0
def eval_postfix(s):
    """Evaluates the postfix expression 's'."""
    S = Stack()
    for ch in s:
        if ch in ('+', '-', '*', '/'):
            if S.isEmpty() is True:
                return "invalud expr"
            else:
                b = S.pop()

            if S.isEmpty() is True:
                return "invalid expr"
            else:
                a = S.pop()
            res = expr(a, b, ch)
            S.push(res)
        elif ch == ' ':
            pass
        else:
            S.push(ch)
    ans = S.pop()

    if S.isEmpty() is False:
        return "This is a false expr"
    return ans
Пример #3
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    S = Stack()
    n = len(expr)

    for i in range(0, n):
        symb = expr[i]  #next symbol
        # print(symb)

        if symb in ['{', '(', '[']:
            S.Push(symb)

        elif symb in ['}', ')', ']']:

            if S.isEmpty():
                return False
            if S.Top() == '{' and symb == '}':
                S.Pop()
            elif S.Top() == '(' and symb == ')':
                S.Pop()
            elif S.Top() == '[' and symb == ']':
                S.Pop()

        else:
            continue

    if S.isEmpty():
        return True
    else:
        return False
Пример #4
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec[")"] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()
    tokenList.reverse()
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == ')':
            opStack.push(token)
        elif token == '(':
            topToken = opStack.pop()
            while topToken != ')':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    postfixList.reverse()
    return " ".join(postfixList)
Пример #5
0
def infixTOPost(expr):
    S = Stack()

    sp = expr.split()
    i = 0
    res = ''
    while i != len(sp):
        symb = sp[i]
        i = i + 1
        if operand(symb):
            res = res + ' ' + symb
        elif operator(symb):
            while not S.isEmpty() and not OpeningPara(
                    S.top()) and HasHigherPre(S.top(), symb):
                res = res + ' ' + S.top()
                S.pop()
            S.push(symb)
        elif OpeningPara(symb):
            S.push(symb)
        elif ClosingPara(symb):
            while not S.isEmpty() and not OpeningPara(S.top()):
                res = res + ' ' + S.top()
                S.pop()
            S.pop()

    while not S.isEmpty():
        res = res + ' ' + S.top()
        S.pop()
    return res
Пример #6
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec[")"] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()
    tokenList.reverse()
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == ')':
            opStack.push(token)
        elif token == '(':
            topToken = opStack.pop()
            while topToken != ')':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    postfixList.reverse()
    return " ".join(postfixList)
Пример #7
0
def eval_prefix(expr):
    s = Stack()
    for i in range(len(expr) - 1, -1, -1):
        ch = expr[i]

        if ch in ('+', '-', '*', '/'):
            if s.isEmpty() is True:
                return "invalid expr"
            else:
                b = s.pop()
            if s.isEmpty() is True:
                return "invalid expr"
            else:
                a = s.pop()
            res = find(b, a, ch)
            s.push(res)

        elif ch == ' ':
            pass
        else:
            s.push(ch)
    ans = s.pop()

    if s.isEmpty() is False:
        return "This is a false expr"
    return ans
Пример #8
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    S = Stack()
    for ch in expr:
        if ch in ('(', '[', '{'):
            S.push(ch)
        elif ch in ('}', ']', ')'):
            if S.isEmpty():
                return False
            if matches(ch, S.topE()):
                S.pop()
            else:
                return False
        else:
            pass
    if S.isEmpty():
        return True
    return False
Пример #9
0
def conInfi(expr):
    sc = Stack()
    pexp = ''
    for ch in expr:
        if ch in ('*', '/', '+', '-'):
            while (sc.isEmpty() is False and Scale(sc.topE()) >= Scale(ch)):
                pexp += sc.pop() + ' '
            sc.push(ch)
        elif ch == '(':
            sc.push(ch)
        elif ch == ')':
            while (sc.isEmpty() is False and sc.topE() is not '('):
                pexp += sc.pop()
            sc.pop()
        else:
            pexp += ch + ' '

    while (not sc.isEmpty()):
        pexp += sc.pop() + ' '
    return pexp
Пример #10
0
def checking(list):
    stack = Stack()
    balanced = True
    index = 0
    while index < len(list) and balanced:
        symbol = list[index]
        if symbol in '([{':
            stack.push(symbol)
        else:
            if stack.isEmpty():
                balanced = False
            else:
                top = stack.pop()
                if not compare(top, symbol):
                    balanced = False

        index = index + 1
    if balanced and stack.isEmpty():
        return True
    else:
        return False
Пример #11
0
def postfix(expr):
	optstack = Stack()
	olist = []
	for i in expr.split():
		if i is '(':
			optstack.push(i)
		elif i in string.uppercase or i in string.digits:
			olist.append(i)
		elif i is ')':
			while True:
				h=optstack.pop()
				if h == '(':
					break
				olist.append(h)
		elif i in prior.keys():
			if not optstack.isEmpty():
				if optstack.peek() == '(':
					optstack.push(i)
				else:
					while True:
						if not optstack.isEmpty():
							if prior[i]>prior[optstack.peek()]:
								optstack.push(i)
								break
							else:
								olist.append(optstack.pop())
						else:
							optstack.push(i)
							break
			else:
				optstack.push(i)

	if optstack:
		while not optstack.isEmpty():
			olist.append(optstack.pop())

	return ' '.join(olist)
Пример #12
0
def check(expr):
    s = Stack()
    index = 0
    for i in expr:
        if i in '({[':
            s.push(i)
        elif i in ')}]':
            try:
                s.pop()
            except:
                return False
    if s.isEmpty():
        return True
    else:
        return False
Пример #13
0
def convert(expr):
    post = ""
    s = Stack()
    for i in range(len(expr) - 1, -1, -1):
        if isOperator(expr[i]) is True:
            #print(expr[i])
            if s.isEmpty() is True:
                return "invalid expr"
            else:
                post += s.pop()
            if s.isEmpty() is True:
                return "invalid expr"
            else:
                post += s.pop()
            post += expr[i]
            s.push(post)
            #print(s.topE())
            post = ""
        elif expr[i] is " ":
            pass
        else:
            s.push(expr[i])
            #print(s.topE())
    return s.topE()
Пример #14
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    sp = expr.split()

    b = 0
    S = Stack()

    while b != len(sp):
        symb = sp[b]
        b = b + 1
        if symb == '{' or symb == '[' or symb == '(':
            t = symb
            S.push(symb)

        elif symb == '}' or symb == ']' or symb == ')':
            if S.isEmpty():
                return False
            else:
                left = S.pop()

                if not match(symb, left):
                    return False

    return S.isEmpty()
Пример #15
0
def check(expr):
	s = Stack()
	index =0 
	for i in expr:
		if i in '({[':
			s.push(i)
		elif i in ')}]':
			try:
				s.pop()
			except:
				return False
	if s.isEmpty():
		return True
	else:
		return False
Пример #16
0
def eval_prefix(expr):
    T = Stack()
    sp = expr.split()
    l = len(sp) - 1
    while l >= 0:
        symb = sp[l]
        l = l - 1
        if not operator(symb):
            T.push(symb)
        else:
            if T.isEmpty():
                return False
            else:
                a = T.pop()
                b = T.pop()
                c = apply(a, b, symb)
                T.push(c)
    return T.pop()
Пример #17
0
def convert(expr):
    S = Stack()
    sp = expr.split()
    l = len(sp) - 1
    while l >= 0:

        symb = sp[l]
        l = l - 1
        if not operator(symb):
            S.push(symb)
        else:
            if S.isEmpty():
                return False
            else:
                a = S.pop()
                b = S.pop()
                c = a + " " + b + " " + symb
                S.push(c)
    return S.pop()
Пример #18
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""

    s = Stack()
    for char in expr:
        if char == '[' or char == '{' or char == '(':
            s.push(char)
        elif char == ']' or char == '}' or char == ')':
            if s.isEmpty():
                return False
            else:
                symbol = s.peek()
                char = invert(char)
                print("Next char is: ", char)
                if symbol == char:
                    s.pop()
                else:
                    return False

    return True