Question

Please solve the following problem with programming using proper data structures. (Programming Language: Python) A similar...

Please solve the following problem with programming using proper data structures. (Programming Language: Python)

A similar application to the parentheses matching problem comes from hypertext markup language (HTML). In HTML, tags exist in both opening and closing forms and must be balanced to properly describe a web document. This very simple HTML document:

Example>

Hello, world

is intended only to show the matching and nesting structure for tags in the language. Write a program that can check an HTML document for proper opening and closing tags.

To simplify the problem, we suppose the opening and closing tags are provided in separate lines without indentation (shown in the green box on the right above).

Consult the example on parentheses matching in lecture slides or the more general balanced symbol example in section 3.7 of the book at:

http://interactivepython.org/runestone/static/pythonds/BasicDS/BalancedSymbols(AGeneralCase).html.

Create a Stack abstract data type

The Stack class should include the following methods:

  • push(item) function to add a new item to the stack
  • pop() function to remove the top item from the stack
  • peek() to return the top item in the stack
  • is_empty() to test whether the stack is empty
  • size() to tell the size (number of items) in the stack

Create a html_checker function

The function:

  • Takes a string of HTML code as argument;
  • Returns true if all tags are balanced; false if otherwise.

Here is what the function should do:

  • Create a new Stack object;
  • Use the split() method of a string to split it into text lines;
  • Create a loop to read the text lines, and for each text line:
    • If the text line matches an opening tag (e.g.

      ), add the tag name (e.g. “h1”) to the stack;

    • If the text line is ordinary content without a HTML tag, skip the line;
    • If the text line is a closing tag (e.g. ), check whether the stack is empty():
      • The HTML code is unbalanced if stack is currently empty;
      • If not empty, use pop() to read and remove the top item from stack:
        • The top item/tag matches the current closing tag, then the HTML code is balanced (true);
        • Otherwise, the HTML code is unbalanced (false).

Program Execution

Create two variables, one with balanced HTML code and the other with unbalanced HTML code. Run the html_checker function with each of the two variables as argument to test the program.

Bonus:

Create a loop to read user input for multiple lines of HTML code (until the user hits a special key to signal the end) and run html_checker function on that input text.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Screenshot

----------------------------------------------------------

Program

#Create a class stack
class Stack:
     #Constructor
     def __init__(self):
         self.elements = []
     #Add element to stack
     def push(self, element):
         self.elements.append(element)
     #Remove from stack
     def pop(self):
         return self.elements.pop()
     #Get top element from stack
     def peek(self):
         return self.elements[len(self.elements)-1]
     #Check empty
     def is_empty(self):
         return self.elements == []
     #Check size of stack
     def size(self):
         return len(self.elements)
     #Override toString
     def __str__(self):
         if len(self.elements)==0:
             return ''
         tempString=''
         for i in range(len(self.elements)):
             tempString+=str(self.elements[i])+' '
         return tempString
#Method to check tag
def html_checker(htmlString):
    #Create a stack
    stack = Stack()
    #Create a list for each line
    lst = list()
    #Loop to get each line
    for line in htmlString:
        line = line.rstrip()
        lst.append(line)
    ind = 0
    #Check stach emty or balanced
    while ind < len(lst):
        for chr in lst[index]:
            if chr == '<':
                stack.push(ch)
            elif chr == '>':
                if stack.is_empty():
                    return False
                else:
                    stack.pop()
        ind += 1
    #If not empty return false
    return stack.is_empty()
#Test
def main():
    #Two string to check
   str1="<h1>This is a Heading</h1>"
   str2="<h1This is a Heading</h1>"
   if(html_checker(str1)):
       print("str1 Correct format")
   else:
       print("str1 Wrong format")

   if(html_checker(str2)):
       print("str2 Correct format")
   else:
       print("str2 Wrong format")
   str3=""
   inp=""
   print("Enter html instructions: ")
   while inp!="quit":
       inp=input()
       str3+=inp
     
   if(html_checker(str3)):
       print("str3 Correct format")
   else:
       print("str3 wrong format")
main()

-------------------------------------------------------

Output

str1 Correct format
str2 Wrong format
Enter html instructions:
<h1>This is a Heading</h1>
<p>This is a paragraph./p>
quit
str3 wrong format

Add a comment
Know the answer?
Add Answer to:
Please solve the following problem with programming using proper data structures. (Programming Language: Python) A similar...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Data Structures and Algorithms. (C++ Language) 1. Write the definition code for a function that p...

    Data Structures and Algorithms. (C++ Language) 1. Write the definition code for a function that passes in a stack and returns (using a return statement) the number of items in the stack (the stack size). a. assume the this function is to be toolkit function in the implementation of the ADT stack. b. assume that this function is not a toolkit function. 2. Given the declaration: s = stack i = item struct STACK { INFO_RC i; int top; }...

  • The last 3 cases are tests .cpp files to test the code. The language of this...

    The last 3 cases are tests .cpp files to test the code. The language of this code must be C++ because that is the only I am familiar with. Soreland, a software company, is planning on releasing its first C++ compiler with the hopes of putting MiniSoft's Visual C++ out of business (that reminds me of another story). Consequently, Soreland has contracted with the Fruugle Corporation to design and build part of their compiler. Of course, since Fruugle gets all...

  • Please answer question 8.35 Python 3.0 for language Comment for each part of line of code...

    Please answer question 8.35 Python 3.0 for language Comment for each part of line of code explaining what is being done 8.35 A stack is a sequence container type that, like a queue, supports very restrictis methods: All insertions and removals are from one end of the stack, typicly aces the top of the stack. Implement container class Stack that implements cked to a a subclass of object, support the len) overloaded operator, and support the me be referred a...

  • This is my code so far: <!DOCTYPE html> <html> <head> <title>JavaScript is fun</title> <meta charset="utf-8" />...

    This is my code so far: <!DOCTYPE html> <html> <head> <title>JavaScript is fun</title> <meta charset="utf-8" /> </head> <body> <script type ="text/javascript"> //declare a variable and store text in it var x = "JavaScript is fun"; //write the variable 5 times document.write(x + x + x + x + x); //store 5 as string in variable x x = "5"; //store 3 as string in variable y var y = "3"; //write the value x + y to the document document.write("<br>");...

  • 2 Apply Your Knowledge Reinforce the skills and apply the concepts you learned in this chapter Styling a Webpage Instru...

    2 Apply Your Knowledge Reinforce the skills and apply the concepts you learned in this chapter Styling a Webpage Instructions: In this exercise, you will use your text editor to create external, embedded, and inline styles for the Durango Jewelry and Gem Shop home page. You will style the sections of the semantic wireframe header, nav, main, and tooter and a div element that surrounds all of the content to center the content on the page. You will also float...

  • Unit 1 Programming Assignment Follow the directions for each of the following questions. Answer the question...

    Unit 1 Programming Assignment Follow the directions for each of the following questions. Answer the question or provide the code in a space below the question. 1. Write the complete script tag set for a script whose line statement is document.write(“Hello, world.”); 2. Build a complete HTML document and include the answer to the previous question such that the page executes the script as the page loads. Open the document in your browser to test the results. 3. Add a...

  • ** Language Used : Python ** PART 2 : Create a list of unique words This...

    ** Language Used : Python ** PART 2 : Create a list of unique words This part of the project involves creating a function that will manage a List of unique strings. The function is passed a string and a list as arguments. It passes a list back. The function to add a word to a List if word does not exist in the List. If the word does exist in the List, the function does nothing. Create a test...

  • Java using data structures The objective is to create your own Hash Table class to hold...

    Java using data structures The objective is to create your own Hash Table class to hold a list of employees and their ID numbers. I've provided the TableEntry class which will be each data object in the hash table. The list of employees will be provided as a .txt file and must be read with the code. please create a .txt file called Employees.txt with the info provided so that the java code can read it in. Employees.txt: (No WhiteSpace...

  • I need help with this code This is what I need to do: Implement the Stack...

    I need help with this code This is what I need to do: Implement the Stack Class with an ArrayList instead of an array, including the following functions: • empty • push • peek • pop • overrided toString( ) function which returns all of the stack’s contents Things to note: • You no longer need a size. • You no longer need to define a constant DEFAULT_CAPACITY. Since ArrayLists grow dynamically. • Whenever possible, use ArrayList functions instead of...

  • PYTHON PROGRAMMING LANGUAGE (NEEDED ASAP) Using a structured approach to writing the program: This section will...

    PYTHON PROGRAMMING LANGUAGE (NEEDED ASAP) Using a structured approach to writing the program: This section will guide you in starting the program in a methodical way. The program will display a window with GUI widgets that are associated with particular functions: Employee Payroll O X -- - - - - - - - - - - Show Payroll Find Employee by Name Highest Lowest Find Employee by Amount Write Output to Fie Cancel - -------- ------------- Notice that some of...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT