I
I
igoodmood2016-03-17 16:10:38
Python
igoodmood, 2016-03-17 16:10:38

Where is the error in the code written in Python?

Created a filter program for checking HTML document tags. But when checking, I found that she marks the correct expressions for checking as incorrect. Changed code fragments, but it does not help. Help, please, where exactly is the error?

class Stack:
    def __init__(self):
        self.item = []
    def push(self,item):
        self.item.append(item)
    def pop(self):
        return self.item.pop()
    def isEmpty(self):
        return self.item==[]
    def size(self):
        return len(self.item)
s=Stack()
def html(tag):
    balanced= True
    index=0
    tag1=0
    tag2=0
    while index<len(tag) and balanced:
        symbol=tag[index]
        if symbol=="<":
            s.push(symbol)
        elif symbol==">" :
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced=False
            else:
                s.pop()
        index=index+1         
    if balanced and s.isEmpty() :
        return True
    else:
        return False
print(html('</html> </body> ,This is html! <body> </title> <title> </head> <head> <html>'))     
print(html('<>title</>'))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2016-03-17
@igoodmood

On the very first line you pushed '<' then popped on '/' and on the next iteration you have balanced=False because the stack is empty. And further in the loop, the value of balanced does not change.
I have not seen the TK, but you can check the balance by parentheses, for example, like this:

class Stack:
    def __init__(self):
        self.item = []

    def push(self,item):
        self.item.append(item)

    def pop(self):
        return self.item.pop()

    def isEmpty(self):
        return self.item==[]

    def size(self):
        return len(self.item)



def html(tag):
    s = Stack()
    for symbol in tag:
        if symbol == "<":
            s.push(symbol)
        elif symbol == ">" and s.isEmpty():
            return False
        elif symbol == ">":
            s.pop()       
    return True if s.isEmpty() else False


if __name__ == '__main__':
    print(html('</html> </body> ,This is html! <body> </title> <title> </head> <head> <html>'))     
    print(html('<>title</>'))
    print(html('</html> </body ,This is html! <body> </title> <title> </head> <head> <html>'))
    print(html('>/html< </body> ,This is html! <body> </title> <title> </head> <head> <html>'))

M
Mr4x, 2016-03-18
@Maxim_Samburskiy

The same can be done more simply:

count = 0
for symbol in tag:
    if symbol == "<":
        count += 1
    elif symbol == ">":
        count -= 1
return count == 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question