0% found this document useful (0 votes)
12 views10 pages

Stack

Uploaded by

sarahstudies2211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Stack

Uploaded by

sarahstudies2211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

w1.writerow([‘S.

No’, ‘Name’, ‘Marks’])


f1.close()

writerows(rows): Writes multiple rows (sequence) to the writer’s file


object
e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
w1.writerows([[1, ‘Ronit’, 84],[2,’Nihir’,90]])
f1.close()

Data structures - Stacks

❖ Introduction to Python data structure stack


❖ Implementation of stack using List
❖ Push function
❖ Pop Function
❖ Display function
❖ Checking stack underflow

Introduction to Python data structure-Stack

A data structure is a way of store, organize, or manage data in efficient and productive manner.

The python data structure stack is a linear data structure. It follows the principle of LIFO (Last In
First Out). The representation of data is something like this:

133
By observing the above image you can understand the following:

1. The data can be inserted or deleted from the top only


2. Elements can be inserted or deleted any time
3. The insert operation is known as push
4. The delete operation is known as pop
5. When the top element is inspected, it is known as a peek or inspection
6. When we have a fixed-length list and we are trying to push an element in a list, it raises one
error that is known as overflow
7. When the list is empty and we are trying to pop an element, it will raise an error that is
known as underflow

Push function
A function to push an element. To push the element append() method is used as well as the
position of the top should be changed. Observe the following code:

def push(stk,e):
stk.append(e)

Pop Function
The pop function requires validation to check whether the stack is underflow or not if it is not then
use the logic to delete the element from the top. Have a look at this code:

def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
return e
Display function
Write a function to check the element is inserted or not, observe this code:

def display(stk):
if stk==[]:
print("Stack Underflow")
134
else:
for i in (stk[::-1]):
print(i)
Applications of the stack:
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward features in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and
histogram problems.
• String reversal is also another application of stack. Here one by one each character gets
inserted into the stack. So the first character of the string is on the bottom of the stack and
the last element of a string is on the top of the stack. After performing the pop operations
on the stack we get a string in reverse order.

Mind Map

BOARD PATTERN QUESTIONS


Considering the dictionary storing the price of vegetables,
veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
a) Write python function to build a stack costly by pushing the names of vegetables whose
price is > 40 from dictionary veg.
b) Pop and display the items in stack costly
Note:Write only 2 functions pushcostly(veg,costly) and popcostly(costly).Write appropriate
statements in the main part to call the functions.

def pushcostly(p,s):
for i in p:
if p[i]>40:
s.append(i)
def popcostly(s):
if s==[]:
print("Stack underflow")
else:
135
print("costly vegetables")
while(s):
print(s.pop())
return
veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
costly= []
while True:
print ('''Menu
1.push
2.pop and display
3.exit''')
ch=int (input ("enter your choice"))
if ch==1:
pushprod(veg,costly)
elifch==2:
popdisplay(costly)
else:
break

WORKSHEET
LEVEL – 1
Answer the following questions(1 marks)
1. A stack is one of the following types of data structure?
a) Linear b) Dynamic c) Circular d) All of these
2. A condition raise due to the stack is full is known as ___________.
a) Underflow b) Overflow c) List is full d) Completely Filled
3. 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
4. Which of the following is not a compound data structure?
a) Stack
b) Queue
c) Array
d) Tree
5. Inspecting the value at the stack’s top without removing it.
a) peak operation
b) insert operation
c) pop operation
d) push operation
6. Which of the following statement is incorrect for stack?
136
a) Peek <stack>[top]
b) Push <stack>.append(<item>)
c) Pop <stack>.pop()
d) Plus <stack>plus()
Answer the following questions (2 marks)
1. What are the underflow and overflow conditions?

Answer the following questions (3 marks)


1. Write a python function to delete an element from the stack.
2. Write a function to inspect an element from the stack.
3. 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.

Answer the following questions (5 marks)


1. Vedika has created a dictionary containing names and marks as key-value pairs of 5 students.
Write a program, with separate user-defined functions to perform the following operations:
• Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
• Pop and display the content of the stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}
Then the output will be: Umesh Vishal Ishika

LEVEL 1 ANSWERS
Answer the following questions(1 marks)
1 a) Linear
2 b) Overflow
3 a) Underflow
4 c) Array
5 a) peak operation
6 d) Plus <stack>plus()
Answer the following questions(2 marks)

137
1 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.
Answer the following questions(3 marks)
1 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
2 def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
3 def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()

138
Answer the following questions(5 marks)
1 def push(stk,item):
stk.append(item)

def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)

while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break

LEVEL – 2

Answer the following questions(1 marks)


1. Stack data structure is following ____________ principle.
2. The peek operation refers to accessing/inspecting the top element in the stack. (True/False)
3. Stack overflow condition is raised in ____________ operation where as Stack underflow
condition is raised in _____________ operations.
4. Stack is a ___________ data structure.
a) Static
b) Dynamic
c) Double
139
d) Single
5. While implementing Stack using list when we want to delete element we must use pop
function as__________
a) list.pop(pos)
b) list.pop(0)
c) list.pop()
d) list.push()
6. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, in
what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Answer the following questions (2 marks)
1. What do you mean by data structure? Explain your answer with a suitable example.
2. Write a python function named is_underflow() to check a stack is an underflow.
3. Write a function to push an element into the stack.
Answer the following questions (3 marks)
1. Write a function to display the stack elements.

LEVEL 2 ANSWERS
I Answer the following questions (1 marks)
1 LIFO
2 True
3 Push , Pop
4 b) Dynamic
5 c) list.pop()
6 b) DCBA
II Answer the following questions (2 marks)
1 The systematic way of organization, storing, accessing and retrieving data including
well-defined operations, behaviour and properties is known as data structure.
Examples:
String – Contains sequence of characters
List – Contains sequence of different data types
2 def is_underflow(stk):
if stk==[]:
return True

140
else:
return False
3 def push(stk,e):
stk.append(e)
top = len(stk)-1

III Answer the following questions (3 marks)


1 def display(stk):
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])

LEVEL – 3

Answer the following questions (1 marks)


1. The insert operation in the stack is known as pop. (True/False).
2. You can replace any element position in the stack. (True/False)
3. If the name of linear list of 10 elements is LIL, then its element will be referenced
a) LIL[0],LIL[1],LIL[2]………LIL[9]
b) LIL[0],LIL[1],LIL[2]………LIL[10]
c) LIL(0),LIL(1),LIL(2)………LIL(9)
d) LIL(0),LIL(1),LIL(2)………LIL(10)
4. LIFO Full form –
a) logical in first out
b) First in first out
c) last in first out
d) last in logical out
5. Which of the following statement(s) about stack data structure is/are NOT correct?
a) Stack data structure can be implemented using linked list
b) New node can only be added at the top of the stack
c) Stack is the FIFO data structure
d) The last node at the bottom of the stack has a NULL link

141
Answer the following questions(2 marks)
1. Define stack.
2. Expand the following:
a) LIFO
b) FIFO
3. What do you mean by the LIFO structure? Support your answer with real-life examples.

LEVEL 3 ANSWERS
Answer the following questions(1 marks)
1 False
2 False
3 a)LIL[0],LIL[1],LIL[2]………LIL[9]
4 c) last in first out
5 a)Stack is the FIFO data structure

II Answer the following questions(2 marks)

1 A stack is a data structure that allows adding and removing elements in a particular 2
order. Every time an element is added, it goes on the top of the stack; the only
element that can be removed is the element that was at the top of the stack.
2 LIFO: Last-In First-Out FIFO: First-In First-Out 1+1
3 LIFO is one of the principle 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

142

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy