Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
37 views
14 pages
Stack
Uploaded by
khushirk80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Stack For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
37 views
14 pages
Stack
Uploaded by
khushirk80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Stack For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Stack For Later
You are on page 1
/ 14
Search
Fullscreen
@. know about different data Structures. {@ understand about stacks in Python {© paiform operations on stack. ‘@ ienpiornent stack with the help of list ustig ifferent Data structures provide a method of arranging and storing data so that it can be feassel and efectively They establish a relationship between the dats and the operations that can be performed List, dictionary, tuple, and set are the built-in data structures of Python. Users can also create theit owné: structures in Pythen, giving them complete control over their functionality. The most common user-ds ddata structures inchude stack, queue, tree, and linked list, which are also available in other progranni lanigoages. Hence, the data structure isa well organised way to maintain data, In Python, data structures can be of two types: Linear data structures and Non-linear data structs Linear data stractures store data items in a sequential order, whereas in non-linear data structures, ‘elements are not linked in a sequential order. Any pair or group of data elements can be linked and aces: without following a specific order in a non-linear data structure. In this chapter, you will learn the bass a linear data structure called stack. 5.4 Stack ‘Take a look at the pile of books on your table. You. will be able to Fthe ples hy pick up the book at th f the also place a new book only atthe top of the pile. This pile of hooks is also called @ ‘i ee ba ois. in ye" programming, the similar concept can be implemented by vsin, schagastack ig @ data structure such as a stack. " ~ = Stack of Books _.{ You ean pick the item fo" |. the top position. rence | fefotlows Last in Fist Ot | (UFO) order Stack of Dishes A stack is & linear data structure that sal performed at one end of the stack, the fap of the stack.5.2.2 Pop Operation The pop operation means removing a data bee ‘The pop operation can also be performed at the tP of the . one because you only have the pop operation is only element from the stack. The popped element is always the top access to the top-most element. Note that, useful when the stack is not empty. 5.2.3 Some Important Terms Related to Stacks Apart from push and pop operations, some important te! related to stacks are: Growing a Stack: A stack is a dynamic data structure because it grows when elements are added to it. Shrinking a Stack: The size of a stack shrinks when the elements are deleted from “ stack. Overflow: When you try to push a new element into an already full stack, the condition of overflow oc, ‘Underflaw: When you try to pop an element from an empty stack, the condition of underflow occurs, rms that are aM ip Pop Operation 5.3 Implementation of Stacks using a List : In Python, a stack can be implemented using a Python built-in list data stracture. The functions relat eee a list are easy to use for performing stack operations. The basic operations that can be performed onasd Ot are: poppe + Creating a Stack + Adding Elements to a Stack (Push) + Deleting elements from a Stack (Pop) + Traversing a Stack @® Let's Know More Some important applications of sas are: creating an undo featue nt pplication, evaluating prefix, past. ‘Or Infix expressions, reversing a st 5.3.1 Creating a Stack S0H130 00. To create a stack, you need to add elements to a list data stra ji inbuil e faanction list() can be used, To declare a stack as alist the iiataris gle ben tbs Sabi = Syntax: mm oat stack = [] stack = list() In order to access the elements of stack, the index clement ofthat ack, sack{1] refers to the second sane Ue: FOr example, stack{o} refers ode 3 ment, stack!2] refers to the shy 450 ae 5.3.2 Adding Elements to a Stack Othe third element. and" Me sta, ‘To add a new element to a stack, or to perform the Push operation, the append«) function i used, Note that, as.a list is used to implement the a stax built-in function append() of list is sede te ‘Syntax: , stack.append(a) Here, a is the element to be inserted ont ‘ © the top of the Stack, 0 ® Let's know More H's possible that a sk be leaget than the curentbiackot "2 ft holds. tn such cases, speed se since fists are employed Aceess. to. random elemests. Pg begins. implicit memory lo" | ‘resulting in longer append)| | to ck abe #98 BePeTonmed while Bashing ana 5 "Ment Onto a stag ke ekifthe stack is full, z yo sack full, splay an error and exit, rae is not full, increment the toto ‘ Sa data clement to the stack, where topis Point to the next. empty sg} Pointing. PAY space, 5? 533 peleting Elements from a Stack sparta element froma stack, the pop() functions used, ‘This operation i also called ion i also called the pop operation. “btack. pop (x) La: _stack.pop[4] gucap remove an clement from the stack by passing the lop element directly to the pop() function. Giherwise,-you can also give the index of the top element of the stack. ‘Tae pop() function returns the upped clement from the stack. Note that, you cn pop out only the top clement from the stack. Algorithm the steps to be performed while deleting an element from a stack ‘the stack is empty, display an error and exit, the stack is not empty, access and return the data element at the top. & Dectesse the value of top by 1. 334 Traversing a Stack Heal means visiting-the elements of alist at le 86 only the top element of it. In order to get stack is a LIFO type data structure, You once. Since, i” fement of the stack without removing it, + the topmost el — sacle sing sti Pyton wth the ely of the following Efe opw sce the practical implementation of st rm stack dmpienentation using List : hon programto demonstrate ment, in the stack n () function topushel® epend(“enenent?) meeeStack.append(*Elenent2") Stack. append(’Element3’}° print("Initial stack‘) print(stack) : P # pop() fucntion to pop element from stack in bere ordel print(*\nElements popped out from stack:*) print(stack.pop()) print(stack.pop()) print("\nStack after elements are popped out:') print(stack) “Output: Initial stack ['Elementi", ‘Element2', ‘Element3*} Elements popped out from stack: 2 Element3 Element2 Stack after elements are popped: {'Elementa"] Inthe above example, the stack oj _fanction pushes the element Program host=[ ] ch="y" “def push(host); ‘bn = Ant(input(“Enter hostel nusber: *y) ts =int(input("Enter total students: ")) = th= int (inpat("Enter total roons: *)) temps (hn, ts, tr] host. append tenp) def pop(host) : if(host == []}: print("NoRecord™) else: ee : * print( "Deleted Record i: def display(hosty »peratious will be performed from only one side that is top. The append into the stack and the pop() function Temoves the element from the stackeo print ("Hostel Number\tyo¢, al s 4 dn range(1-. i. : Te anetnocttinn rea, MM 8\ttotay 1. Ney" Rooms") hosts wiite(ch=="Y" oF chestyry, 2D. Nee pets 5 24) print(2. Add Record\nny print("2. Delete Recond\ne) prant(“3. Display Record\nvy print("4: Exit") opwint (input( "Enter the Choice” flop ==): » push(host) elif(op == 2): pop(host) elif(op== 3): display(host) elif(op==4): break ch» input ("Do you want to enter more(¥/N)?") _ Add Record Delete Record : Display Record Exit er the choice: 1 r hostel number: 401 total students: 42 nter total rooms: 20 ¢ you want to enter more(¥/N)? ¥ Delete Record Display Record the choice: 3 otal Rooms 2 Ostel Number Total students ¥ You want to enter more(v/N)? Add Record Delete recordy Enter the choicet.2 Deleted Record is: bo you want to ente @ €9¢¢%¢ © eo Oo oo » bree k Oty ene . When you try to pop an element MO an alrea, tren, 40, 20] p nore (Y/N)? N ES ring data so that it can be accosseq Mig vod of arranging and st Data structures provide a meth effectively. List, dictionary, tuple, and set are the built The most common user-defined data struct
‘Statement 1 ‘#Function Calling # ase Courrtriyat) SL Indian’ ; usa! UK" "Caniaaa”, “sh For tn range(@,ten(c); : - Push(Country, cf iy) print (Country) Required Output; Hndfan’ ‘OK: ‘Sui Laika’) >” Code-2 ea © def pop(Couhtryy - if poe functions to add a new package ang q, ackage) Perations oF‘peguired Ootput; ‘Sri Lanka UK ! Indi ‘Under flow a Sey ee coder ta Cf |. appenc it ins of statement 1 ae + insert() ‘i fill he statement 2, to insert she stern ik, extendd) The wppéndl i Bo hs te element from Country ist, renee Ny é Bi he soem check the ak val iu 2 wuntey = [] Steeles empay, i len(country)==0 A, Countryisimpty() 4 il the statement 4, to delete an element hone io i pool} rom the stack. Bop) fii, del country 1) Hill the statement 5, to call the pop function. _ de pop(C) ell pop(Countey) wy etpnton iE insert() ee 2 i. len{country) dit pop) ¢, it pop(Country} “Given below are two statements: One is labelled as Assertion (A) and the other is abelled as Reason ®). iv, Country.delete(1) poe ‘Assertion (A): TOP is a pointer to the stack’s current location. Reéson (R): Insertion and Deletion takes place from Top of the tack, - Considering the above statements, choose the correct answer from the options given below: “a, Both (A) and (R) are true, and (R) “Both (A) and (R) are true, but (®) €. (A) is true but (R) is false. (A) is false bot (R) is true. Given below are two statements: One it “Assertion (A): Pop operation on stack cannot Reason (R); Ifthe stack is empty. te print error 0 caidering the above statements 2008 Ihe correct a Both (A) and (R) are true, and (R) 1 explanation of (A) tion of (A). loth (A) and (R) are true, but @ (A) is true but (R) i false. i } | js correct explanation of (A). is not the correct explanation of (A). jon (A) and the other is labelled as Reason (R). labelled as Asserti perform on empty stack underflow and exit the program. nswer from the options given below: js correct jg not the correct explanacP Lab Activity) emented using alist data structure? 1. Answer the following questions" empty stack if stacks imple a. How to create an at b. Howto add the elements (0 stack? hatha stack? c. Howto delete or remove the elements aaa How to traverse ot display the elements © ing the following code. 7” reated by usi : tack can be ct a. Creating an empty stack: An empty s oe ek ig i oapky stock = t 2 ist( ) . . b haan vat ina stack; You can add element ip @ stack by using the append; ) ta, jing an ele : shown below: st append(12) Here element'10'is added onto a stack named ‘st. Deleting elements from the stack: You can delete the elements from the stack as shown blog st.pop( ) a Digan cement of the stack: You can display all the elements of a stack as shown bc L = len(st) for i in range(L-1, -1, -1): ths you have to display elements in reverse aw print(st[1]) i# (st = [): print(*Stack 1s empty.") from a stack student. Ans. st ={] “ def push(st): o9 = lnput(“Enter the nane of a student ) st-append(sn) def pop(st): if(st == (]): Print ("Stack 45 ampty,») else: print (“Deleted sp 3. Write the code for pabtten ne roe er) 10) and. 2 push(rolino) ~ add roll ny, us P°P0) methods in Python; def Push(roline): WStack.apperd(ret gy def Pop(Mystacky,if len(Mystack) > 9: MyStack.pop() else: print(*Stack is empty.*) 4, Write addclient(clientname) and remove lent from a stack “clientdetail”, Ang, Clientdetall = [] def addclient(cn): clientdetail -append(en) def remove(): 4) methods in Python to ade a new clientand delete an existing on Af len(clientdetail)>0: ‘clientdetail.pop() se: print "Stack is enpty.") i jer marae
You might also like
Chapter 3 Stacks
PDF
No ratings yet
Chapter 3 Stacks
28 pages
Most Expected 2 Marks Most Expected Questions Stack Computer Science Class 12
PDF
100% (2)
Most Expected 2 Marks Most Expected Questions Stack Computer Science Class 12
28 pages
Advanced Data Structures
PDF
No ratings yet
Advanced Data Structures
78 pages
Stacks Preeti Arora
PDF
100% (1)
Stacks Preeti Arora
6 pages
Stack
PDF
100% (1)
Stack
14 pages
CSC KV CHN - Stack With Worksheet
PDF
No ratings yet
CSC KV CHN - Stack With Worksheet
10 pages
399 33 Powerpoint-Slides Chapter12
PDF
No ratings yet
399 33 Powerpoint-Slides Chapter12
69 pages
Python 1
PDF
No ratings yet
Python 1
4 pages
Data Structure For Class 12 CS 083 Python
PDF
No ratings yet
Data Structure For Class 12 CS 083 Python
24 pages
Stack Class XII
PDF
100% (1)
Stack Class XII
16 pages
Data Structure
PDF
No ratings yet
Data Structure
10 pages
cs12 - Data Structures Stack Using List
PDF
No ratings yet
cs12 - Data Structures Stack Using List
7 pages
Stack
PDF
No ratings yet
Stack
27 pages
Data Structure - Stack
PDF
No ratings yet
Data Structure - Stack
7 pages
NOTES DataStructure Stacks 2022 23
PDF
No ratings yet
NOTES DataStructure Stacks 2022 23
8 pages
STACKS Data Structures
PDF
No ratings yet
STACKS Data Structures
11 pages
Python Stack Heap 1703351915
PDF
No ratings yet
Python Stack Heap 1703351915
17 pages
Stacks
PDF
No ratings yet
Stacks
23 pages
Stack & Queue
PDF
No ratings yet
Stack & Queue
20 pages
Stack ADT
PDF
No ratings yet
Stack ADT
13 pages
05 Data Structures
PDF
No ratings yet
05 Data Structures
11 pages
Data Structure
PDF
No ratings yet
Data Structure
13 pages
Revised STACK in Python XII CS
PDF
No ratings yet
Revised STACK in Python XII CS
15 pages
DataStructure Stack
PDF
No ratings yet
DataStructure Stack
41 pages
Data Structures IN Python: Prepared By: Jyoti Gupta PGT (Computer Science) KV Sliet Longowal
PDF
No ratings yet
Data Structures IN Python: Prepared By: Jyoti Gupta PGT (Computer Science) KV Sliet Longowal
29 pages
Class 12 DS 1
PDF
No ratings yet
Class 12 DS 1
3 pages
Stack Using List
PDF
No ratings yet
Stack Using List
6 pages
Dsa (Week 5)
PDF
No ratings yet
Dsa (Week 5)
67 pages
Data Structure Using in Python
PDF
No ratings yet
Data Structure Using in Python
32 pages
Chapter No#4 Done
PDF
No ratings yet
Chapter No#4 Done
15 pages
Data Sucture12 PDF
PDF
No ratings yet
Data Sucture12 PDF
16 pages
Data Structures5
PDF
No ratings yet
Data Structures5
11 pages
SYCS Data Structure Practical Manual
PDF
No ratings yet
SYCS Data Structure Practical Manual
34 pages
Data Structure in Python
PDF
No ratings yet
Data Structure in Python
36 pages
CH Datastructure Stack
PDF
No ratings yet
CH Datastructure Stack
2 pages
Lecs 103
PDF
No ratings yet
Lecs 103
15 pages
Data Structure - Stack-1
PDF
No ratings yet
Data Structure - Stack-1
43 pages
Python Data Struct
PDF
No ratings yet
Python Data Struct
24 pages
3 Stack: in This
PDF
No ratings yet
3 Stack: in This
14 pages
Stack Questions
PDF
No ratings yet
Stack Questions
23 pages
Data Structures in Python - For App
PDF
No ratings yet
Data Structures in Python - For App
2 pages
Stack 12csc
PDF
No ratings yet
Stack 12csc
30 pages
Data Structure Stack and Queue 1
PDF
No ratings yet
Data Structure Stack and Queue 1
10 pages
Notes of Stack
PDF
No ratings yet
Notes of Stack
2 pages
Stack Data Structure
PDF
No ratings yet
Stack Data Structure
30 pages
Addition of Sparse Matrices
PDF
No ratings yet
Addition of Sparse Matrices
24 pages
Data Structures
PDF
No ratings yet
Data Structures
11 pages
Image To PDF 20230905 14.38.26
PDF
No ratings yet
Image To PDF 20230905 14.38.26
8 pages
Stack
PDF
No ratings yet
Stack
10 pages
Data Structures Stack
PDF
No ratings yet
Data Structures Stack
40 pages
Together With
PDF
No ratings yet
Together With
5 pages
Data Structure
PDF
No ratings yet
Data Structure
10 pages
DATA STRUCTUREhjhhnhmm
PDF
No ratings yet
DATA STRUCTUREhjhhnhmm
5 pages
Data Structures
PDF
No ratings yet
Data Structures
7 pages
Data Structure
PDF
No ratings yet
Data Structure
24 pages
Data Structure Stack
PDF
No ratings yet
Data Structure Stack
24 pages
Stack Question Banksolution
PDF
No ratings yet
Stack Question Banksolution
10 pages
Unit - 2 Linear Data Structures (Stacks)
PDF
No ratings yet
Unit - 2 Linear Data Structures (Stacks)
15 pages
Xiics Stack
PDF
No ratings yet
Xiics Stack
13 pages