Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Stack 12csc

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Takhellambam Sylvia

COMPUTER SCIENCE

(Based on COHSEM Class 12)

Unit 1: DATA STRUCTURES USING PYTHON

Chapter 2: Stack

Stack (List Implementation): Introduction to stack (LIFO Operations), operations on


stack

(PUSH and POP) and its implementation in python. Expressions in Prefix, Infix, and
postfix

notations, evaluating arithmetic expressions using stack, conversion of Infix


expression to

postfix expression

Table of Contents

 The Data Structure

 Stack

 Operations in stacks in python: PUSH and POP

 Implementing stacks in python

 Types of Stacks – Item nodes in python [Out of Syllabus- just for


understanding]
 Applications of Stacks in python

o Reversing a line using stacks in python

o Polish Strings using stacks in python

 Expressions in Prefix, Infix and postfix notations

 Conversion of infix Expression to Postfix (Suffix) Expression

 Algorithm to convert infix Expression to postfix form

 Evaluation of a postfix Expression using stacks in python

1
Takhellambam Sylvia

 Evaluation of prefix expression using stacks in python [Out of Syllabus]

 Advantage of postfix Expression over infix Expression in python [Out of


Syllabus]
1. Data Structure:

 The systematic way of organization, storing, accessing, and retrieving data


including well-defined operations, behaviour and properties is known as data
structure.

Examples:
1. String – Contains sequence of characters
2. List – Contains sequence of different data types

2. Stack

 A stack is a linear data structures in python in which addition and deletion of


elements can be done at one end only. A stack is known as LIFO (Last In First
Out) data structure. LIFO means element last inserted would be the first one
to be deleted or remove.

 The stack is used in many fields in our routine life. Some examples are:
1. Browsers History
2. Mobile Phone Call log
3. Undo and redo commands in software

we can say that a stack is a list of data that follows these rules:

3. Operations in stacks in python: PUSH and POP

1. Data can only be removed from the top (pop), i.e., the element at the top of
the stack. The removal of element from a stack is technically called POP
operation.

2. A new data element can only be added to the top of the stack (push). The
insertion of element in a stack is technically called PUSH operation

Consider figure below that illustrates the operations (push and pop) on a stack.

2
Takhellambam Sylvia

Figure: Stack Operation – PUSH and POP

Some Other Stack Terms in python

There are some other terms related to stacks, such as peek, overflow and Underflow.

Example:

Let’s have an example of a bounded stack of capacity 4 which is initially empty, and
drawing pictures of the stack after each of the following steps. Initially the stack is
empty.

3
Takhellambam Sylvia

Solution.

 Stack is empty (top = None )

 Push ‘a’ top = 0

 Push ‘b’ top = 1

 Push ‘c’ top = 2

4
Takhellambam Sylvia

 pop top = 1

 push ‘d’ top = 2

 pop ‘d’ top = 1

 Push ‘e’ top = 2

 Push ‘f’ top = 3

5
Takhellambam Sylvia

 Push ‘g’ top = 3

[OVERFLOW because the stack is bounded, it cannot grow. If it could


grow, then there would have been no OVERFLOW until no memory is
left. In python, (for stacks implemented through lists) since lists can
grow, OVERFLOW condition does not arise until all the memory is
exhausted.]

 Pop top = 2

 pop top = 1

 pop top = 0

6
Takhellambam Sylvia

 pop top = none

 Pop top = none

4. Implementing stacks in python

In python, you can use lists to implement stacks. Python offers us a convenient set
of methods to operate lists as stacks.

The functions associated with stack are:

 empty() – Returns whether the stack is empty – Time Complexity: O(1)

 size() – Returns the size of the stack – Time Complexity: O(1)

 top() / peek() – Returns a reference to the topmost element of the stack –


Time Complexity: O(1)

we can use: <stack> [top]

7
Takhellambam Sylvia

where < stack> is a list; top is an integer having value equal to len
(<stack>) -1.

 push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity:
O(1)

we can use: <stack>. append (<item>)


when <item> is the item being pushed in the stack.

 pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

we can use: <stack>. Pop ( )


it removes the last value from the stack and returns it.

## Menu Driven Program to implement Stack Operations Using List##

def push (stk, item):

Program Code:

STACK IMPLEMENTATION

#Let us create an empty stack -A function named isEmpty to check whether the
stack glassStack is empty or not.

def is Empty (stk):


if stk == [ ] # or if length(stk)==
return True
else:
returns False

#A function named Push to insert (PUSH) a new element in stack

def push (stk, item):


stk. append (item)
top = len (stk) -1

def pop (stk):


if is Empty (stk):
return “underflow”
else:
item = stk. Pop ( )
if len (stk) == 0:
top = None
else:
top = len (stk) -1

8
Takhellambam Sylvia

return item

def peek (stk):


if is Empty (stk):
return “underflow”
else:
top = len (stk) -1
return stk [top]

def Display (stk) :


if is Empty (stk) :
print (:stack empty”)
else:
top = len (stk) -1
print (stk[top], “<- top” )
for a in range (top- 1, -1, -1 ) :
print (stk [a])

#_main_
stack = [ ] # initially stack is empty
top = None

While True:
print (“STACK OPERATIONS”)
print (“1. Push”)
print (“2. Pop”)
print (“3. Peek”)
print (“4. Display stack”)
print ( “5. Exit”)
ch = int (input (“Enter your choice (1-5) :” ) )
if ch == 1 :
item = int (input (“Enter item:” ) )
push (stack, item)
elif ch == 2 :
item = pop (stack)
if item ==”underflow”
print (“underflow” : stack is empty !” )
else:
print (“popped item is”, item)
elif ch == 3:
item = peek (stack)
if item ==”underflow”

9
Takhellambam Sylvia

print (“underflow! Stack is empty!”)


else:
print (“Topmost item is”, item)
elif ch == 4:
Display (stack)
elif ch == 5:
break
else:
print (“Invalid choice!”)

Sample run of the above program is as shown below:

10
Takhellambam Sylvia

5. Types of Stacks – Item-nodes in python

An item stored in a stack is also called item- node sometimes. In the above
implemented stack, the stack contained item-nodes containing just integers. If you
want to create stack that may contain logically group information such as member
details like: member no, member name, age etc. For such the item-node will be a list
containing the member details and then this list will be entered as an item to the
stack. (See figure below)

 For stack of figure (a), the stack will be implemented as stack of integers as
item-node is of integer type.

 For stack of figure (b), the stack will be implemented as stack of strings as
item-node is of string type.

11
Takhellambam Sylvia

 For stack of figure (c), the stack will be implemented as stack of lists as item-
node is of list type.

6. Applications of Stacks in python

There are several applications and uses of stacks. The stacks are basically applied
where LIFO (Last in First Out) scheme is required

6.1 Reversing a line using stacks in python

A simple example of stack application is reversal of a given line. We can accomplish


this task by pushing each character on to a stack as it is read. When the line is
finished, characters are then popped off the stack, and they will come off in the
reverse order as shown in Figure below. The given line is: Stack.

12
Takhellambam Sylvia

6.2 Polish Strings using stacks in python

Another application of stacks is in the conversion of arithmetic expressions in high-


level programming language into machine readable form. As our computer system
can only understand and work on a binary language, it assumes that an arithmetic
operation can take place in two operands only e.g., A+ b, c D, D/A etc. But in our
usual from an arithmetic expression may consist of more than one operator and two
operands

For example:

(A + B) C (D/(J + D)).

These complex arithmetic operations can be converted into polish string using
stacks which then can be executed in two operands and operator form.

Polish string, named after a polish mathematician, Jan Lukasiewicz, refers to the
notation in which the operator symbol is placed either before its operands (prefix
notation) or after its operands (postfix notation) in contrast to usual form where
operator is placed in between the operands (infix notation).

7. Expressions in Prefix, Infix and postfix notations

Following table shows the three types of notations:

8. Conversion of infix Expression to Postfix (Suffix) Expression

While evaluating an infix expression, there is an evaluation order according to

13
Takhellambam Sylvia

which

I. Brackets or Parenthesis,

II. Exponentiation,

III. Multiplication or Division- [Same priority- From left to right]

IV. Addition or Subtraction- [Same priority- From left to right]

An infix expression may be converted into postfix from either manually or using a
stack. The manual conversion requires two passes: one for inserting braces and
another for conversion. However, the convert an infix expression into a postfix
expression manually are given below:

 Determine the actual evaluation order by inserting branches.

 Convert the expression in the innermost branches into postfix notation by


putting the operator after the operands.

 Repeat step (ii) until entire expression is converted into postfix notation.

Example: Convert (A+B) × C /D into postfix notation.

Solution:

Step 1: Determine the actual evaluation order by putting braces

= ((A+B) ×C)/D

Step 2: Converting expressions into innermost braces

= ((AB+) ×C)/D

=(AB+C×) / D

= AB +C × D /

Example: Convert((A+B) *C / D + E^F)) / G into postfix will be

=((((AB+B) *C) / D) +(E^F))/G

Converting expressions in the braces, we get

=((((AB+) *C)/D) + (EF^))/G

=(((AB+C*)/D) + EF^)/G

=((AB+C*D/) +EF^)/G= (AB + C * D/EF ^ +)/G

=AB + C * D/EF ^ +G/

14
Takhellambam Sylvia

Example: Give postfix from of the following expression

A* (B+(C+D) * (E+F)/*H

Solution: Evaluation order is

(A*(B+((C+D) * (E+F))/G)) *H

Converting expression in the braces, we get

=(A*(B+[(CD+) *(EF+)]/G)) *H

= (A*(B+ (CD+EF+ *)/G)) * H

= (A* (B+ (CD+EF+ *G/)) * H

= (A* (BCD + EF + *G/+)) * H

= ABCD+EF + *G/ + H

= ABCD +EF +*G/+ *H*

Example: Give postfix from for A+[(B+C) + (D+E) * F]/G

Solution:

Evaluation order is: A +[{(B+C) + ((D+E) * F)}/G

Converting expressions in braces, we get

=A + [{(BC +) + (DE+) * F}/G]

= A+ [{(BC +) + (DE + F *)}/G]

=A + [{BC + DE +F * +}/G]

= A + [BC +DE +F * +G/]

=ABC +DE +F * +G / +

While converting from infix to prefix form, operation is put before the operands. Rest
of the conversion procedure is like that of infix to postfix conversion.

9. Algorithm to convert infix Expression to postfix form

 The following algorithm transforms the infix expression X into its equivalent
postfix expression Y.

15
Takhellambam Sylvia

 The algorithm uses a stack to temporarily hold operators and left parentheses.

 The postfix expression Y will be constructed from left to right using the
operands from X and the operators which are removed from STACK.

 We begin by pushing a left parenthesis onto STACKS and adding a right


parenthesis at the end of X. The algorithm is completed when STACKS is
empty.

Algorithm for Infix to postfix conversion using stacks in python

Suppose X is an arithmetic expression written in infix notation. This algorithm finds


the equivalent postfix expression Y.

1. Push “(“onto STACKS, and add “) “to the end of X.

2. Scan X from left to right and REPEAT Steps 3 to 6 for each element of X until
the STACKS is empty:

3. If an operand is encountered, add it to Y.

4. If a left operand is encountered, push it onto STACKS.

5. If an operator is encountered, then:

6. Repeatedly pop from STACKS and add to Y each operator (on the top of
STACKS) which has the same precedence as or higher precedence than
operands.

7. Add operator to STACKS.

‘ ‘ ‘ End of if structure’ ‘ ‘

6. If a right parenthesis is encountered, then:

7. Repeatedly pop from STACK and add to Y each operator (on the top of STACK)
until a left parenthesis is encountered.

8. Remove the left parenthesis. [Do not add the left parenthesis to Y].

‘ ‘ ‘ End of if structure’ ‘ ‘

‘ ‘ ‘ End of step 2 Loop’ ‘ ‘

7. END

Convert A+ (B*C-(D/E^F)*G)*H) into postfix will be

Solution:

16
Takhellambam Sylvia

17
Takhellambam Sylvia

10. Evaluation of a postfix Expression using stacks in python

As postfix expression is without parenthesis and can be evaluated as two operands


and an operator at a time, this becomes easier for the compiler and the computer to
handle. Evaluation rule of a postfix expression states:

 While reading the expression from left to right, push the element in the stack
if it is an operand;

 Pop the two operands from the stacks, if the element is a binary operator. In
case of NOT operator, pop one operand from the stack and then evaluate it
(two operands and an operator).

 Push back the result of the evaluation. Repeat it till the end of the expression.

**For a binary operator, two operands are popped from stack and for a unary
operator, one operand is popped. Then, the result is calculated using operand(s) and
the operator, and pushed back into the stack. **

Algorithm Evaluation of postfix expression using Stack

Step 1: INPUT postfix expression in a variable, say postExp

Step 2: For each character in postExp, REPEAT Step 3

Step 3: IF character is an operand

THEN PUSH character on the Stack

ELSE POP two elements from the Stack, apply the operator on

the popped elements and PUSH the computed value onto the Stack

Step 4: IF Stack has a single element

THEN POP the element and OUTPUT as the net result

ELSE OUTPUT “Invaild Postfix expression”

*** You can choose any format: ***

18
Takhellambam Sylvia

Example: Evaluation the postfix expression AB + C × D / IF A =2, B =3, C =4 and D =5.

Solution. The expression given is AB + C × D/

Starting from left to right

19
Takhellambam Sylvia

Example:2

Example 3:

456*+

11.Evaluation of prefix expression using stacks in python

The prefix expression is also without parentheses. The prefix expression are
evaluated by the compiler by using two stacks:

 One stack (symbol stack) for holding the symbols of the expression (all the
operators and operands/values of the expression are considered symbols)
and

20
Takhellambam Sylvia

 Another stack (number stack or operand-value stack) for holding the numbers

 numbers or values (i.e., the operands).

Algorithm −

Step 1: Start from the last element of the expression.

Step 2: check the current element.

Step 2.1: if it is an operand, push it to the stack.Step 2.2: If it is an operator, pop two
operands from the stack. Perform the operation and push the elements back to the
stack.

Step 3: Do this till all the elements of the expression are traversed and return the top
of stack which will be the result of the operation.

Example: 1. (+ -927)

21
Takhellambam Sylvia

Example 2: ( /+33-+47*+123)

12.Advantage of postfix Expression over infix Expression in python

 An infix expression is difficult for the machine to know and keep track of
precedence of operators.

 On the other hand, a postfix expression itself determines the precedence of


operators (as the placement of operators in a postfix expression depends
upon its precedence).

 Therefore, for the machine, it is easier to carry out a postfix expression than
an infix expression.

22
Takhellambam Sylvia

SUMMARY

Stack is a data structure in which insertion and deletion is done


from one end only, usually referred to as TOP.

Stack follows LIFO principle using which an element inserted in


the last will be the first one to be out.

PUSH and POP are two basic operations performed on a stack


for insertion and deletion of elements, respectively.

Trying to pop an element from an empty stack results into a


special condition underflow.
In Python, list is used for implementing a stack and its built-in-
functions append and pop are used for insertion and deletion,
respectively. Hence, no explicit declaration of TOP is needed.
Any arithmetic expression can be represented in any of the three
notations viz. Infix, Prefix and Postfix.

While programming, Infix notation is used for writing an


expression in which binary operators are written in between the
operands.
A single traversal from left to right of Prefix/ Postfix expression
is sufficient to evaluate the expression as operators are correctly
placed as per their order of precedence.
Stack is commonly used data structure to convert an Infix
expression into equivalent Prefix/Postfix notation.

While conversion of an Infix notation to its equivalent


Prefix/Postfix notation, only operators are PUSHed onto the Stack.

When evaluating any Postfix expression using Stack, only


operands are PUSHed onto it.

23
Takhellambam Sylvia

24
Takhellambam Sylvia

Important Data Structure Stack Questions 1-mark questions:

[1] A ____________ is a way to store, organize, or manage data in efficient and


productive manner.

Ans: Data Structure

[2] A stack is one of the following types of data structure?

a) Linear b) Dynamic c) Circular d) All of these

[3] Stack data structure is following ____________ principle.

Ans: LIFO

[4] In stack data can be inserted or deleted from ____________ only.

Ans: Top

[5] The insert operation in the stack is known as pop.

(True/False) Ans:False

[6] You can replace any element position in the stack.

(True/False) Ans: False

[7] The peek operation refers to accessing/inspecting the top element in the stack.
(True/False)

[8] A condition raise due to the stack is full is known as ___________.

a) Underflow b) Overflow c) List is full d) Completely Filled

[9] While popping the element from the stack, a condition will be raised, this
condition is known as ____________.

a) Underflow b) Overflow c) List is Empty d) Blank List

[10] Stack overflow condition is raised in ____________ operation whereas Stack


underflow condition is raised in _____________ operations.

Ans: Push, Pop

Short answer questions (2 Marks – Questions) –

[1] What do you mean by data structure? Explain your answer with a suitable
example

Ans.: The systematic way of organization, storing, accessing, and retrieving data
including well-defined operations, behaviour and properties is known as data

25
Takhellambam Sylvia

structure.
Examples:
1. String – Contains sequence of characters
2. List – Contains sequence of different data types

[2] What do you mean by the LIFO structure? Support your answer with real-life
examples.

Ans.: LIFO is one of the principles to access data from a data structure. It stands for
Last In First Out. It refers to the item which is inserted last will be access first. So,
the top element will be accessed first.
Example:
1. Books in the shelf
2. Stack of coins
3. Pile of chairs
4. Bangles on woman’s wrist

[3] Enlist a few of the fields where you feel a stack is used in real life.

Ans.: The stack is used in many fields in our routine life. Some examples are:
1. Browsers History
2. Mobile Phone Call log
3. Tubewell boring machine
4. Undo and redo commands in software

[4] What are the basic operations that can be performed on the stack?

Ans.: There are two basic operations can be performed on the stack:
1. Push – Inserting an element
2. Pop – Deleting an element

[5] What are the underflow and overflow conditions?

Ans.: Underflow is the condition which occurs when stack is empty while trying to
delete elements. Overflow is the condition which occurs while inserting an element
when memory is exhausted.

[6] Write steps on how you implement stack?

Ans.: The steps are:


1. Create a stack
2. Push an element
3. Pop an element
26
Takhellambam Sylvia

4. Traverse/Display an element

[7] Write a python function named is underflow () to check a stack is an underflow.

Ans:

def is underflow(stk):

if stk==[]:

return True

else:

return False

[8] Write a function to push an element into the stack.

Ans:

def push (stk, e):

stk.append(e)

top = len (stk)-1

[9] Write a python function to delete an element from the stack.

Ans:

def pop_stack(stk):

if stk==[]:

return "UnderFlow"

else:

e = stk.pop()

if len(stk)==0:

top = None

else:

top = len(stk)-1

return e

[10] Write a function to display the stack elements.

Ans:

def display(stk):

27
Takhellambam Sylvia

if stk==[]:

print("Stack is Empty")

else:

top = len(stk)-1

print(stk[top],"-Top")

for i in range(top-1,-1,-1):

print(stk[i])

[11] Write a function to inspect an element from the stack.

Ans:

def peek(stk):

if stk==[]:

return "UnderFlow"

else:

top = len(stk)-1

return stk[top]

[12] Write functions AddPlayer(player) and DeletePlayer(player) in python to add


and remove a player by considering them as push and pop operations in a stack.

Ans:

def AddPlayer(player):

pn=input("enter player name:")

player.append(pn)

def DeletePlayer(player):

if player==[]:

print("No player found")

else:

return player.pop()

[13] Evaluate the following postfix expression

782*4/+

28
Takhellambam Sylvia

Ans:

=7 8 2 * 4 / +

= 7 16 4 / +

=74+

= 11

Assignment

Q. Find the output of the following code:

a) result=0

numberList=[10,20,30]

numberList.append(40)

result=result+numberList.pop()

result=result+numberList.pop()

print(“Result=”,result)

b) answer=[];

output='' answer.append('T')

answer.append('A')

answer.append('M')

ch=answer.pop()

output=output+ch

ch=answer.pop()

output=output+ch

ch=answer.pop()

output=output+ch

print(“Result=”,output)

Q. Evaluate the following postfix expression

10 20 + 25 15 - * 30 /

Q. Q. Evaluate the following postfix expression using a stack and show the

29
Takhellambam Sylvia

contents of stack after execution of each operation

15 3 2 + / 7 + 2 *

Q. Convert the following infix expression into postfix:

1.(A*B)/C

2.A-(B*C)+D/E

3.V*W*X+Y-Z

Q. Convert the following infix expression into prefix:

1.A+B-C*D

2. A*((C+D)/E)

3.A*B+C+D*E

30

You might also like