У меня есть скрипт на python, который создает связанный список для ввода, а затем сравнивает символы, чтобы убедиться, что все открытые скобки имеют закрывающие скобки в правильном порядке.
Например. (9- {5 * 2 (1 + 1)}) == Верно
(9- {5 * 2 {1 + 1))) == Неверно
Моя проблема возникает, когда я сравниваю возвращаемое значение функции со строкой. Функция if просто останавливается в строке 152. Когда я прерываю скрипт, я получаю эту ошибку:
Traceback (most recent call last):
File "lab2.py", line 195, in <module>
bracketCheck(list)
File "lab2.py", line 152, in bracketCheck
if list.getNodeAtPosition(i) == '(' or list.getNodeAtPosition(i) == '{' or list.getNodeAtPosition(i) == '[':
File "lab2.py", line 114, in getNodeAtPosition
currentNode = currentNode.getNext()
KeyboardInterrupt
Ниже приведен код моего сценария, в котором Связанный список в значительной степени вдохновлен atraub из DreamInCode. Кроме того, ввод необходимо вводить по одному, пока вы не введете «done»:
import sys
stack = []
openbrackets = ['(','{','[']
closebrackets = [')','}',']']
class LinkedList:
class Node:
def __init__ (self, cargo=None):
self.cargo = cargo
self.next = None
def __str__ (self):
return str(self.cargo)
def __len__ (self):
return self.length
def isEmpty (self):
if length == 0:
return True
else:
return False
def getElement(self):
print self.__str__()
def getNext (self):
return self.next
def setElement(self, cargo):
self.cargo = cargo
def setNext(self, cargo):
self.next = cargo
def hasNext(self):
return self.next != None
def __init__(self):
self.first = LinkedList.Node()
self.length = 0
def __len__ (self):
return self.length
def __add__(self, other):
retList = LinkedList()
for item in self:
retList.append(item)
for item in other:
retList.append(item)
return retList
def getFirst(self):
return self.first.getNext()
def currentPoint(self):
current = self.first.getNext()
def setFirst(self, cargo):
toAdd = LinkedList.Node(cargo)
toAdd.setNext(self.first.getNext())
self.first.setNext(toAdd)
self.length += 1
def removeFirst(self):
if self.length > 0:
value = self.first.getNext().getElement()
self.first.setNext(self.first.getNext().getNext())
self.length -= 1
return value
else:
print "Error: List is empty"
def addLast(self, cargo):
current = self.first
while current.hasNext():
current = current.getNext()
current.setNext(LinkedList.Node(cargo))
self.length += 1
def removeLast(self,index=None):
if index ==None:
index = self.length-1
previous = self.getNodeAtPosition(self.checkIndex(index)-1)
toRemove = previous.getNext()
afterNext = None
if toRemove.hasNext():
afterNext = toRemove.getNext()
previous.setNext(afterNext)
self.length-=1
return toRemove.getElement()
def getLast(self):
current = self.first
while current.hasNext():
current = current.getNext()
return current
def moveNext(self):
current = self.first
def getNodeAtPosition(self, index):
currentNode = self.first
for i in range(index+1):
currentNode = currentNode.getNext()
return currentNode
def __str__ (self):
if self.length == 0:
return '[]'
retString = "["
currentElement = self.first.getNext()
for i in range(self.length):
retString += str(currentElement) + ", "
currentElement = currentElement.getNext()
return retString[:-2] + ']'
def checkIndex(self, index):
if type(index) != int:
raise TypeError("Index must be an integer or a slice not a")
if index < 0:
index += self.length
if index >= self.length or index < 0:
raise IndexError("Index out of bounds")
return index
def bracketCheck(list):
checkList = LinkedList()
opencount=0
closecount=0
while(list.first.hasNext):
isEqual = True
i=0
i=i+1
if list.getNodeAtPosition(i) == '(' or list.getNodeAtPosition(i) == '{' or list.getNodeAtPosition(i) == '[':
checkList.addLast(list.first.getNodeAtPosition(i))
opencount = opencount + 1
if list.getNodeAtPosition(i) == ')':
closecount = closecount + 1
if list.first.getLast() == openbrackets[0]:
checkList.removeLast()
else:
isEqual = False
if list.getNodeAtPosition(i) == '}':
closecount = closecount + 1
if list.first.getLast() == openbrackets[1]:
checkList.removeLast()
else:
isEqual = False
if list.getNodeAtPosition(i) == ']':
closecount = closecount + 1
if list.first.getLast() == openbrackets[2]:
checkList.removeLast()
else:
isEqual = False
'''print checkList'''
print opencount
print closecount
if isEqual == False:
print "an extra is missing."
else:
print "win!"
print "Enter list:"
list = LinkedList()
while input != "done":
input = raw_input()
if input == "done":
break
list.addLast(input)
print list
bracketCheck(list)