Skip to content

Instantly share code, notes, and snippets.

@reinana
Last active September 6, 2020 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reinana/d063963881591b4268d8ce27399976f5 to your computer and use it in GitHub Desktop.
Save reinana/d063963881591b4268d8ce27399976f5 to your computer and use it in GitHub Desktop.
stackCaluculation
class Node:
def __init__(self,data):
self.data = data
self.next = next
class Stack:
def __init__(self):
self.head = None
self.next = None
def push(self,data):
temp = self.head
self.head = Node(data)
self.head.next = temp
def pop(self):
if self.head == None: return None
temp = self.head
self.head = self.head.next
return temp.data
def peek(self):
if self.head == None: return None
return self.head.data
def applyOperation(op1,op2,operation):
#op1 = int(op1)
#op2 = int(op2)
if operation == "+": return op1+op2
if operation == "-": return op1-op2
if operation == "*": return op1*op2
if operation == "/" and op2==0: return op1
elif operation == "/": return op1/op2
return None
def porandOperand(arr):
operations = {
"*":3,
"/":3,
"+":2,
"-":2,
"(":1,
")":1
}
operand = []
operation = Stack()
arr = arr.replace("+",",+,").replace("-",",-,").replace("*",",*,").replace("/",",/,").replace("(","(,").replace(")",",)")
arr = arr.split(",")
for i in range(0,len(arr)):
if arr[i].isdigit(): operand.append(arr[i])
elif arr[i]=="(": operation.push(arr[i])
elif arr[i]==")":
stackTop = operation.pop()
while stackTop != "(":
operand.append(stackTop)
stackTop = operation.pop()
else:
while (operation.head != None ) and (operations[operation.peek()] >= operations[arr[i]]):
operand.append(operation.pop())
operation.push(arr[i])
while operation.head != None:
operand.append(operation.pop())
print(operand)
return operand
#print(porandOperand("(1+4)*(3+7)"))
def caluculator(arr):
arr = porandOperand(arr)
print(arr)
cal = Stack()
for i in range(0,len(arr)):
if arr[i].isdigit(): cal.push(int(arr[i]))
else:
op1 = cal.pop()
op2 = cal.pop()
cal.push(applyOperation(op2,op1,arr[i]))
return cal.peek()
print(caluculator("(1+41)*(311+7)"))
print(caluculator("2+500000*3-6"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment