How do computers deal with brackets in any programming language

If there is one thing programming languages have in common, it’s their use of brackets. Different programming languages use different brackets for different reasons. In python, curly brackets ({}) are used for dictionaries and sets while square brackets are used for lists. One thing is for sure, once a bracket is opened, it has to be closed or else an error will be thrown. This raises an important question: How do computers check whether the brackets that are opened are closed properly and in the correct order?

Stack

A program can be coded to simulate how a computer might deal with brackets. We will work with a stack as it is an abstract data type that stores items where the Last In is the First Out (LIFO). This will be helpful later on when we have a code and trying to figure out if the brackets are properly used. For the sake of illustrating how a computer might deal with brackets, I have created a stack class with methods such as push() for adding items in a stack, pop() for removing items in a stack, clear(), size() and peep() for returning the last value in the stack. The different methods each perform different actions that will allow us to achieve FIFO.

class Stack:
    s = []
    limit = 10
    def __init__(self):
        self.s = []

    def get_s(self):
        return self.s

    def push(self,x):
        if len(self.s) >= Stack.limit:
            print("The stack is full")
        else:
            self.s.append(x)
        #example s = [1,2,3,4,5]

    def pop(self):
        if not self.s:
            print("Oops, your stack is empty")
        else:
            return self.s.pop()

    def clear(self):
        self.s = []

    def size(self):
        return len(self.s)
    def peep(self):
        if self.s:
            return self.s[-1]
        else:
            print("The stack is empty")
mystack = Stack()
mystack.push("Hello")
mystack.push("World")
mystack.push("1234")
size = mystack.size()
print("Size: ", size)
print("stack: ", mystack.s)
print("Popped: ", mystack.pop())
print("Peep: ", mystack.peep())<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

An instance of the class has been created in order to test that the stack actually works. If our class works properly, we should be able to push (add) values in a stack and pop() (remove) the last value put into the stack. The output of the code is illustrated below.

python 3.6 stack output
Python idle output of the stack file

In our code, we created an instance of the stack class named “mystack”. We then used the push() method to add “hello”, “world” and “1234” to our stack. The size() method was used to show us the size of the stack which is 3. Then, we popped an item from the stack. I mentioned earlier that our stack follows last in first out, therefore the “1234” should be popped from our stack. This is confirmed to us by using the peep() method to take a look at the last value in the stack and indeed it is not “1234”, it is “world”. Perfect, our stack works fine.

Brackets

In order to work out if our brackets are used properly in a code we need to come up with a function with a string of codes as a parameter that will determine whether or not the code’s brackets are used properly. Our function is illustrated below.

from stack import Stack
code = """#include <stdio.h>
int main()
{
    int number;

    // printf() dislpays the formatted output
    printf("Enter an integer: ");  

    // scanf() reads the formatted input and stores them
    scanf("%d", &number);  

    // printf() displays the formatted output
    printf("You entered: %d", number);
    return 0;
}"""
def check_brackets(code):
    brackets  = {"<": ">", "(":")", "{":"}", "[":"]"}
    lb = {'<', '(', '{', '['}     rb = {">", ")", "}", "]"}
    for i in code:
        if i in lb:
            mystack.push(i)
        if i in rb:
            if brackets[mystack.s.pop()] == i:
                a = "match"
            else:
                a = "mismatch"
    return a
[/sourcecode

The python code above makes use of the stack class illustrated earlier as we need to use stacks to figure out if the brackets are properly matched. For this reason, the stack class is imported on line 1. the variable “code” holds strings of code from C language which makes use of curly brackets, square brackets, parenthesis and less than and greater than signs.
A function called check_brackets() was created and within it we have a dictionary of left brackets, curly braces, parenthesis and less than sign that have a value that is their right bracket equivalent. For example: “[” has a value of “]”. The function loops over the left brackets and if any of the left brackets are in the code, that specific bracket is pushed (added) into our stack. Then, if the next bracket is a right bracket, and the last value in the stack is the key of that right bracket i.e. the dictionary’s right bracket is the value of the left bracket, then the program assigns “match” to our variable a. “mismatch” is assigned to a if that particular condition is not met. The function returns the value of a (match or mismatch). To see if our function actually works we will have to see the output of our program.

compiler python code output
Python Idle – output of our function check_brackets()

The previous image shows the output of the value returned by our function check_brackets(). The program has output “match” which means that the brackets in the C code are properly used.

Leave a comment