Friday, November 27, 2015

Stack implementation in Python 3.5

Stack is a data structure that follows the LIFO model last in first out, the data that is inserted last will come out first.

Program for implementation of stack in Python:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
stack = []

stackLength = input("Specify the limit of the stack: ")


class Stack:
    def push(self, value):
        if len(stack) != int(stackLength):
            stack.append(value)
            return
        else:
            print("Stack is full !")
            return

    def pop(self):
        if len(stack)!= 0:
            stack.remove(stack[len(stack)-1])
            return
        else:
            print("Stack is empty")
            return

    def length(self):
        return len(stack)

stackClassInst = Stack()
stackClassInst.push(100)
stackClassInst.push(200)
stackClassInst.push(300)
stackClassInst.push(400)
stackClassInst.push(500)
stackClassInst.push(600)
stackClassInst.push(700)
stackClassInst.push(800)
stackClassInst.push(900)
stackClassInst.push(1000)
stackClassInst.push(1100)

print(stack)

lengthofstack = stackClassInst.length();

print(lengthofstack,": is the length of the stack")

stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();

print(stack)

Firstly I took an empty array and I requested the input of stack's length using input.

Once I have input, once push method is called, I compared the length of stack array with the actual length from input.

If the length of the stack reaches the limit, stack is full message is printed.

Otherwise push continues and inserts data into the stack.

In pop, one can remove the elements from stack until it reaches the end of stack, once the end is reached, stack is empty message is printed.

The length method is used to calculate the length of the stack at any given time.

I enclosed push, pop and length methods into a class.

Output:


Specify the limit of the stack: 10
Stack is full !
[100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
10 : is the length of the stack
Stack is empty
[]

Process finished with exit code 0

Feel free to suggest on the post, happy learning.



No comments:

Comments

blog comments powered by Disqus