0% found this document useful (0 votes)
37 views14 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
0% found this document useful (0 votes)
37 views14 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
You are on page 1/ 14
@. 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?) meee Stack.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 stack eo 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 record y 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 explana cP 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