I did define the class as below but it gives me error message says, name 'checkBrackets' is not defined.---> 50 result = checkBrackets(equation)
I did define the class as below but it gives me error message says, name 'checkBrackets' is not defined.
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def isEmpty (self):
return len(self.stack) == 0
def peek (self):
if len(self.stack) != 0:
return self.stack[-1]
def pop(self):
if len(self.stack) != 0:
return self.stack.pop(-1)
###
def checkBrackets(statement):
stack = Stack()
size = 0
flag = "Wrong"
for ch in statement:
if ch in ('{','[','('):
size += 1
statck.push(ch)
elif ch in ('}',']',')'):
size += 1
if stack.isEmpty():
return (flag, size)
else:
left = stack.pop()
if (ch=="}" and left !="{") or (ch=="]" and left !="[") or (ch==")" and left !="(") :
return (flag, size)
if stack.isEmpty():
flag ="OK"
return (flag, size)
else:
return (flg, size)
equation = input ("Enter_qauation: ")
result = checkBrackets(equation)
print ("%s_%d"%(result[0],result[1]))
The function is defined, but it is defined in the class Stack so you need to call it as Stack.checkBrackets(equation). There were two more errors(spelling errors), so the final code looks like:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def isEmpty (self):
return len(self.stack) == 0
def peek (self):
if len(self.stack) != 0:
return self.stack[-1]
def pop(self):
if len(self.stack) != 0:
return self.stack.pop(-1)
###
def checkBrackets(statement):
stack = Stack()
size = 0
flag = "Wrong"
for ch in statement:
if ch in ('{','[','('):
size += 1
stack.push(ch) # spelling correction
elif ch in ('}',']',')'):
size += 1
if stack.isEmpty():
return (flag, size)
else:
left = stack.pop()
if (ch=="}" and left !="{") or (ch=="]" and left !="[") or (ch==")" and left !="(") :
return (flag, size)
if stack.isEmpty():
flag ="OK"
return (flag, size)
else:
return (flag, size) # spelling correction
equation = input ("Enter_equation: ")
result = Stack.checkBrackets(equation) # Changed Line
print ("%s_%d"%(result[0],result[1]))
Sample Output 1:
Enter_qauation:
(1+2)=3
OK_2
Sample Output 2:
Enter_qauation:
1+2=(3
Wrong_1
Related
Update
Thanks to the comments of some community members, I realize that there are some similar problems, but they may a bit different, please allow me to explain it further.
I actually hope to use the same method in a real problem, So briefly:
Reuse of edges in differernt path is completely allowed
a unique(or a new) path from A to B is defined as a collection of vertices that have any different vertices.
Let me use a quiz from Python data structure and algorithm analysis by Bradley .N Miller and David L. Ranum to expain my qusetion.
Quesion:
Consider the task of converting the word FOOL to SAGE, also called word ladder problem. In solving
In the word ladder problem, only one letter must be replaced at a time, and the result of each step must be a word, not non-existent.
Input:
FOUL
FOOL
FOIL
FAIL
COOL
FALL
POOL
PALL
POLL
POLE
PALE
PAGE
SALE
POPE
POPE
SAGE
We can easily find the path from FOOL to SAGE, as Bradley showed:
enter image description here
and I used Breadth First Search (BFS) to solve probem:
class Vertex:
def __init__(self, key, value = None):
self.id = key
self.connectedTo = {}
self.color = 'white'
self.dist = sys.maxsize
self.pred = []
self.disc = 0
self.fin = 0
self.value = value,
#self.GraphBulided = False
self.traverseIndex = 0
self.predNum = 0
def addNeighbor(self, nbr, weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return '{} connectedTo: {}'.format(self.id, \
str([x.id for x in self.connectedTo]))
def setColor(self, color):
self.color = color
def setDistance(self, d):
self.dist = d
#I want store all Pred for next traverse so I use a list to do it
def setPred(self, p, list = False):
if not list:
self.pred = p
else:
self.pred.append(p)
self.predNum += 1
def setDiscovery(self,dtime):
self.disc = dtime
def setFinish(self,ftime):
self.fin = ftime
#def setGraphBulided(self, tag = True):
# self.GraphBulided = tag
def getFinish(self):
return self.fin
def getDiscovery(self):
return self.disc
def getPred(self):
if isinstance(self.pred, list):
if self.traverseIndex < self.predNum:
return self.pred[self.traverseIndex]
else:
return self.pred[-1]
else:
return self.pred
def __hash__(self):
return hash(self.id)
def getPredById(self):
if self.traverseIndex < self.predNum and isinstance(self.pred, list):
pred = self.pred[self.traverseIndex]
self.traverseIndex += 1
print("vertix {}: {} of {} preds".format(self.id, self.traverseIndex, self.predNum))
return [pred, self.traverseIndex]
else:
pred = None
return [pred, None]
def getCurrPredStaus(self):
#if not self.pred:
# return None
return self.predNum - self.traverseIndex
def getDistance(self):
return self.dist
def getColor(self):
return self.color
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self, nbr):
return self.connectedTo[nbr]
def getValue(self):
return self.value
def findPath(self, dest):
pass
class Graph:
def __init__(self):
self.vertList = {}
self.numVertics = 0
self.verticsInSerach = set()
self.GraphBulided = False
def addVertex(self, key, value = None):
self.numVertics = self.numVertics + 1
newVertex = Vertex(key, value=value)
self.vertList[key] = newVertex
return newVertex
def getVertex(self, n):
if n in self.vertList:
return self.vertList[n]
else:
return None
def __contains__(self, n):
return n in self.vertList
def addEdge(self, f, t, cost = 0, fvalue = None, tvalue = None):
if f not in self.vertList:
nv = self.addVertex(f, fvalue)
if t not in self.vertList:
nv = self.addVertex(t, tvalue)
self.vertList[f].addNeighbor(self.vertList[t], cost)
def setGraphBulided(self, tag = True):
self.GraphBulided = tag
def getVertices(self):
return self.vertList.keys()
def setGraphBulided(self, tag = True):
self.GraphBulided = tag
def setSerachedVertixs(self, vertix):
self.verticsInSerach.add(vertix)
def getGraphBulided(self):
return self.GraphBulided
def getSerachedVertixs(self):
return self.verticsInSerach
def __iter__(self):
return iter(self.vertList.values())
def __hash__(self):
hashIds = [x for x in self.getVertices()]
if len(hashIds) > 0 and hashIds[0]:
return hash(', '.join(hashIds))
else:
return None
Here are some additional functions for building graphs
def buildGraph(wordFile, DFSgraph = False):
d = {}
g = Graph()
if DFSgraph:
g = DFSGraph()
wfile = open(wordFile)
for line in wfile:
word = line[:-1]
for i in range(len(word)):
bucket = word[:i] + '_' + word[i+1:]
if bucket in d:
d[bucket].append(word)
else:
d[bucket] = [word]
for bucket in d.keys():
for word1 in d[bucket]:
for word2 in d[bucket]:
if word1 != word2:
g.addEdge(word1, word2)
wfile.close()
return g
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def bfs(g, start, listpred = False):
start.setDistance(0)
start.setPred(None)
vertQueue = Queue()
vertQueue.enqueue(start)
while (vertQueue.size() > 0):
currentVert = vertQueue.dequeue()
if currentVert.getConnections():
g.setSerachedVertixs(currentVert)
for nbr in currentVert.getConnections():
#print('sreach {}'.format(currentVert.getId()))
if (nbr.getColor() == 'white' or nbr.getColor() == 'gray'):
nbr.setColor('gray')
nbr.setDistance(currentVert.getDistance() + 1)
if nbr.predNum > 0 and currentVert.getId() not in [x.getId() for x in nbr.pred]:
nbr.setPred(currentVert, listpred)
elif nbr.predNum == 0:
nbr.setPred(currentVert, listpred)
vertQueue.enqueue(nbr)
currentVert.setColor('black')
Therefore, we can easily find the shortest path we need (If we only store one pred for one vertix).
wordGraph = buildGraph('fourletterwords1.txt', DFSgraph=False)
bfs(wordGraph, wordGraph.getVertex('FOOL'), listpred=True)
def traverse(y):
x=y
while(x.getPred()):
print(x.getPred())
x = x.getPred()
print(x.getId())
traverse(wordGraph.getVertex('SAGE'))
However, I still don't know how to trace all the paths correctly, can you give me some suggestions?
FIND path from src to dst ( Dijkstra algorithm )
ADD path to list of paths
LOOP P over list of paths
LOOP V over vertices in P
IF V == src OR V == dst
CONTINUE to next V
COPY graph to working graph
REMOVE V from working graph
FIND path from src to dst in working graph( Dijkstra algorithm )
IF path found
IF path not in list of paths
ADD path to list of paths
I'm trying to create a function that checks for balance brackets, according to the class I created.
But I keep getting False all the time.
I would really appreciate if you could show me where I was wrong and explain me the solution to my mistake.
class Stack:
def __init__(self):
self.__items = []
self.__top = 0
def is_Empty(self):
if self.__top <= 0:
return "Stack Empty!"
else:
return f"Your stack is not Empty!\nThe current stack is {self.my_stack()}"
def __str__(self):
"""Print current stack"""
return self.my_stack()
def push(self, item):
"""Push item in stack."""
self.__items.append(item)
self.__top += 1
def pop(self):
"""Remove top of the stack."""
if self.__top <= 0:
return self.is_Empty()
self.__top -= 1
return self.__items.pop()
def top(self):
"""Return top of the stack."""
if self.__top <= 0:
return self.is_Empty()
else:
return self.__items[-1]
def my_stack(self):
"""Show the current stack"""
if not self.__items:
return self.is_Empty()
else:
return f"The current stack is {self.__items}"
def check_balance(test):
"""
Return True if brackets are balanced, False otherwise.
"""
oppositeBracket = {']': '[', ')': '(', '}': '{'}
lefts = Stack()
for char in test:
if char in '[({':
lefts.push(char)
if char in '])}':
if lefts.is_Empty():
return False
else:
if lefts.top() != oppositeBracket[char]:
return False
lefts.pop()
if not lefts:
return True
return False
for example:
print(check_balance("(10+10)"))
And I get
False
You have 2 small bugs in your code:
isEmpty method returns always True since you return non empty string.
Your final check for empty stack (if not lefts) is always True as well since lefts is equal to your stack object and it even if it's empty, it won't be logical False.
The code should be:
class Stack:
def __init__(self):
self.__items = []
self.__top = 0
def is_Empty(self):
return self.__top <= 0
def __str__(self):
"""Print current stack"""
return self.my_stack()
def push(self, item):
"""Push item in stack."""
self.__items.append(item)
self.__top += 1
def pop(self):
"""Remove top of the stack."""
if self.__top <= 0:
return self.is_Empty()
self.__top -= 1
return self.__items.pop()
def top(self):
"""Return top of the stack."""
if self.__top <= 0:
return self.is_Empty()
else:
return self.__items[-1]
def my_stack(self):
"""Show the current stack"""
if not self.__items:
return self.is_Empty()
else:
return f"The current stack is {self.__items}"
def check_balance(test):
"""
Return True if brackets are balanced, False otherwise.
"""
oppositeBracket = {']': '[', ')': '(', '}': '{'}
lefts = Stack()
for char in test:
if char in '[({':
lefts.push(char)
elif char in '])}':
if lefts.is_Empty():
return False
else:
if lefts.top() != oppositeBracket[char]:
return False
lefts.pop()
return lefts.is_Empty()
You are treating is_Empty as returning a boolean, but it doesn't. It returns a string in either case. (and such is always "True" in a boolean sense)
UnitTest:
l = Stack()
l.push('1')
assert not l.is_Empty()
This assert should not fail, but does.
I'm trying a leetcode min stack problem and my code is not working, tried finding a solution but can't see what's wrong. It seems to work for most inputs but fails "
["MinStack","push","push","push","top","pop","getMin","pop","getMin","pop","push","top","getMin","push","top","getMin","pop","getMin"]
[[],[2147483646],[2147483646],[2147483647],[],[],[],[],[],[],[2147483647],[],[],[-2147483648],[],[],[],[]]" .
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.count = 0
self.minEle = -1
def push(self, x: int) -> None:
if self.count == 0:
self.minEle = x
self.stack.append(x)
elif x < self.minEle:
self.stack.append(2*x - self.minEle)
self.minEle = x
elif x >= self.minEle:
self.stack.append(x)
self.count += 1
def pop(self) -> None:
y = self.stack.pop()
if y < self.minEle:
self.minEle = 2*self.minEle - y
self.count -= 1
def top(self) -> int:
if self.count >=1:
return self.stack[(self.count - 1)]
else:
return 0
def getMin(self) -> int:
return self.minEle
Try:
class MinStack:
def __init__(self):
self.sc = []
self.sm = []
# #param x, an integer
# #return an integer
def push(self, x):
self.sc.append(x)
if x <= self.getMin():
self.sm.append(x)
return x
# #return nothing
def pop(self):
if self.sc.pop() == self.getMin():
self.sm.pop()
# #return an integer
def top(self):
return self.sc[-1]
# #return an integer
def getMin(self):
try:
return self.sm[-1]
except IndexError:
return self.top()
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
obj.pop()
print(obj.top())
print(obj.getMin())
param_3 = obj.top()
param_4 = obj.getMin()
I can only push two values onto the stack array that I have created when I use the myPush() function. The reason I need to do it this way is because I am not allowed to use the built-in stack functions. Plus I have to use an array not a lit. Thank you.
I can only push two values onto the stack array that I have created when I use the myPush() function. The reason I need to do it this way is because I am not allowed to use the built-in stack functions. Plus I have to use an array not a lit. Thank you.
class Stack:
def __init__(self, data):
if data > 0:
self.stack = [0] * data
self.top = -1
self.stack[self.top] = self.stack[-1]
elif data <= 0:
self.stack = [0] * 10
self.top = -1
def showStack(self):
for i in self.stack:
print(i, end=" ")
return
def isEmpty(self):
return self.stack == []
def myEmpty(self): #complete this function
return # just a placeholder
def push(self, data):
self.stack.append(data)
def myPush(self, data):
if data == 0:
print("You did not enter a value.")
elif self.sizeStack() <= 10:
current = self.stack[stack.top]
self.stack[stack.top] = data
self.stack[stack.top - 1] = current
def pop(self):
data = self.stack[-1]
del self.stack[-1]
return data
def myPop(self): #complete this function
return # just a placeholder
def myPeek(self):
temp = self.top
return temp
def sizeStack(self):
return len(self.stack)
userVal = int(input("Enter the size of the stack: "))
stack = Stack(userVal)
while True:
print('\n1 display the stack')
print('2 add a value to the stack')
print('3 check the value at the top of the stack')
print('4 remove the value at the top of the stack')
print('5 check if the stack is empty')
print('99 quit')
option = int(input("Enter your choice: "))
if option == 1:
stack.showStack()
elif option == 2:
temp = int(input("Enter a number to add to the stack: "))
stack.myPush(temp)
elif option == 3:
print(stack.peek())
elif option == 99:
break
else:
print('Wrong option')
print
try defining a some customized functions that map to your list. Read up on customization here
class stack:
def __init__(self, data):
self.stack = [0] * data
self.top = -1
# whatever you want to do to init the list
def __str__(self): # replaces your showstack function now just use print(stack)
return self.stack
def __iter__(self): # creates an iterator you can use
return iter(self.stack)
def __len__(self): # replaces your sizestack function
return len(self.stack)
basically just adjust the methods you need.
Because stack allows to either push or pop, it is suitable to redo actions by just simply popping the latest action by the user. I have a stack class where:
class Node:
def __init__(self,item,the_next = None):
self.item = item
self.next = the_next
def __str__(self):
return str(self.item)
class LinkedStack:
def __init__(self):
self.top = None
self.count = 0
def __len__(self):
return self.count
def is_empty(self):
return self.count == 0
def isFull(self):
return False
def reset(self):
self.top = None
self.count = 0
def __str__(self):
current = self.top
ans = ""
while not (current is None):
ans += str(current)
ans += '\n'
current = current.next
return ans
def _get_node(self,index):
if 0<= index< len(self):
current = self.top
while index>0:
current = current.next
index -=1
return current
def pop(self):
if self.is_empty():
raise StopIteration("Stack is empty")
output = self.top.item
self.top = self.top.next
self.count -=1
return output
def push(self,item):
newNode = Node(item)
newNode.next = self.top
self.top = newNode
self.count +=1
if __name__ == "__main__":
L = LinkedStack()
and in another file, i import the stack from above and try to implement the undo action.
from Stack import LinkedStack
class Editor:
def __init__(self):
self.count = 0
self._list = LinkedList()
self._stack = LinkedStack()
def command(self,userCommand):
userCommand = userCommand.split(' ')
try:
if userCommand[0] == 'insert':
position = int(userCommand[1])
if len(userCommand) ==1:
raise Exception('no num is given')
textInput = input("Enter your text:")
self._stack.push(self.insertText(position,textInput)) #I'm thinking of adding the action into the stack by pushing it.
print(self._list)
pass
except Exception:
print('?')
if userCommand[0] == 'undo': #here if they choose to undo, by right i just pop the last action from the stack
self._stack.pop()
if __name__ == '__main__':
myCommand = Editor()
while True:
command = input('Enter an option:')
if command.lower() == 'quit':
break
else:
myCommand.command(command)
because I'm merely undoing actions, i thought of adding the command actions into a stack. if you take a look at the insert command above, where i added a comment, am i doing it correctly? Because I'm running out of ideas.
By the way, the insertText is a function which is working and I'm not planning to paste it here as it's getting lengthy. LinkedList() is just a linked list class i imported from another file as well.
The 'undo' doesn't seemed to revert the state. For example, if my LinkedList() contains:
1
2
3
4
None
and if i use the insert function to insert another number, 7 at index 1
1
7
2
3
4
None
and if i undo the action, I'm supposed to have:
1
2
3
4
None