我需要制作一个使用堆栈的函数,以查看html文件中的开始和结束标签是否平衡。该问题使您可以假定html逐行显示,而不必担心缩进。当我使平衡标签(例如>)失衡时,下面的程序可以工作,而这就是所有问题所要解决的问题,但是我试图编辑函数,以便它会看到不平衡的html起始标签。我的功能注意到>之类的东西,但是没有注意到<< html>之类的东西。我当时想我可以在函数中添加另一个语句,例如 “如果ch =='<'而不是stack.is_empty(): 返回False” 但是我不确定该将其放置在函数中的什么位置。
class Stack:
""" Last in first out"""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def peek(self):
return self.items[len(self.items - 1)]
def push(self,item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def HTMLCheck(newfile):
# How to see if << is covered
with open(newfile) as file:
stack = Stack()
list1 = list()
for line in file:
line = line.rstrip()
list1.append(line)
index = 0
while index < len(list1):
for ch in list1[index]:
if ch == '<':
stack.push(ch)
elif ch == '>':
if stack.is_empty():
return False
else:
stack.pop()
index += 1
return True
print(HTMLCheck('HW5.txt'))
答案 0 :(得分:1)
def HTMLCheck(newfile):
# How to see if << is covered
with open(newfile) as file:
stack = Stack()
list1 = list()
for line in file:
line = line.rstrip()
list1.append(line)
index = 0
while index < len(list1):
for ch in list1[index]:
if ch == '<':
stack.push(ch)
elif ch == '>':
if stack.is_empty():
return False
else:
stack.pop()
index += 1
return stack.is_empty() # if the stack is not empty then it was not balanced ...
答案 1 :(得分:1)
另一种解决方案。我对算法做了一些改进,还检查了标签的全名。
onPress={() => this.setState({ submit: !this.state.submit })}