Partial preview of the text
Download DSA456 cheat sheet Midterm and more Exams Computer Science in PDF only on Docsity!
Recursion +s afuncton that calls itself until ‘Récesn't The process of whatever we are doing with ‘recursion fas tobe che seme ‘Each time we run the urction we make the problem smalle~ ‘Must containa base case, Run- time Stack:\Vhatever function is at the top of the call stackis the only cone that cen run. Once it's core sunning, you can remove it then the next function can un anc ‘when thats donerunning you repeat the above steps Linkedlist Append O(t) Pop O(n} Prepend 0(:) PopfistC(L) Get O(n) setvalue Oln) Insert ofr} Remeve O(n) Drawbacks and Caution oF Recursion: Recursion can consume a signizant amount of memory due to the tack rare overhead Poorly imelamented recursive algorithms car lead to stack overflow errs Hs essential to ensure a proper base case and terry ration conditen to acevent infritse You should ase recursion and only if the problem isnaturally recursive (you can state icin cerms ofitself)astrightfcrward iterative solution isnot aval Merge Sort and Algorithm: Merge sortisa clvide-and-cong, algorithm that divides tre input Into smaller subprabiems,sorss them, and then merges tr=m back together. Ithas atime complecty of C{n logn) andisa stablesorting algorthm, sts: Lists area fundamenta data structure in Python that allows storing ane rranipulating collections cf elements. Theyre ordered, mutable, and can contain clements cf cifferert cata types lists can be azcessed and rected using ndexctased operations. Linked List: linked lstis a cata sructure where elements, celled nodes, are linked together via pointers or refererces, Each node comzins data and a reference to thenedt rnodzin thelist Urlke arrays, linked lists do not require contiguous memory al ccation [Linkectist Class} # initial zea linkec list with a head rode containing the ger valie class LinkedLis: def_init_{self, value) snaw_node= Node{value) [Node Class] #in tale anode with che given value class Nede: def _nit_{elf, value): seltvalue= value selfnedt = None [Get] & Retrieve the node at he specified index in the Unkee ist def get self index! ifindex<0 a index > sel length retura None temp selfhead for _in nge(index): temp = temp.next return temp [Pop] # Remove and return tre lestrode from the linked list def papisel ifselflength =0: return None temp= selfhead pre =selfheee while temp. nent: Analyze the flloning function with respec: to number de* function name") # Loperation for iin “enget@numer) #n-Loperetens x= (+4) #n-Loperetens totaheprx) — fm-Loperetens return otal 1 operation Establish variables ard functions (mathematical ones} Let a represent the valuew= are finding the factorial for Let "T(n) represerttae number of operations needed to findn! using the ccce above. ‘Count ya." operations: For each line cf the code block above, we Fave courted the ‘number of operations. "he loop ‘uns 'r-t"timessirce the range goes from 02 rumbe~ 1 Thevefoee ary opersion that occurs wichin 12 loop will be courted'n-' times. Establish the Mathematical Exoresen fer Ta: Basedon the ccurts from Step 2,the wathematcal expression for Tin}is Tin) = 14 (tl + (red) + (ret = an-2 Simoify your Equater: The expression ‘Sn = 25 obtained in Step 3 afer simplified State your Frl result: "TKny"is‘OfA)* Applications of Staces ‘Stacks are used for managing function calls and recursion (vie the cll stack) ‘*Treyare also useful for undo- redo functional ty, expression evaluation, and backtracking algcrthms. 5 Applications of cueves: ‘Queues are commonly wed in scheduling algorithms, ‘manzging tasis, and implementing breadth-fst search (BFS, ‘*Treyare also apa ieblein simulations, handling recuests, and buffering systems 6. Stack Implementation: «Stacks cer be implemented using arays or linkec lists. ss ineraybased Implementation, afied-sze array is used to sore the stack elervents. “In linked list-based Implementation, nedes with data anda referenceto the nex: nodeare used. 7. Aray Implementation 0° stacks: An araytesed Implementation of stacks uses an array tc store the elerans. The tog ofthe stacks rmainained as an inde pointing o the astinserted elervent. STACK [Node class] class Nece: ef _ni_(slf value) # Initia ize anode ws te given value seffvalue= value seffnedt =None [Pust] def pushlself value|-# Add a new element with the given value tothe top ofthe tack new _nace = Nodetvelue) if self height == 0: #1 che stace is empty, update top to tie new element selftop =new_node else: # Otheraise, add thenew element on tapef te existing elements and apdate top new _noce.next= selitep sefftop =new_node seltheight += 1 return True [Append] # Add a new node with the given value at the end ofthe linked lst ‘ef apoendl self, value! rnew_nace = Nodetvelue) ifseltlength # If she ist is empty, update head and talto therew node seffhead= new_nod= sefftall= new_nace else: # Otherwise, add the new nede «the tall and update the tal sefftalnext = new_node sefftall= new_nace selflength + return Tru Tenqueve] def enqueuelself valuek:# Add a rewelemen: with the given value to the end ofthe aus rnew_nace = Nodetvelue) ifselfirs sone: # fthe queue is empty, update first and last to the new element seffirst= new_node sefflast= new_node else: # Otheraise, add thenew element after che last element and update last sefflastrext= new_node sefflast= new node sefflength + return True [Dequeue] def dequeusicel): # Remove and return the fs: 2lement from the queue ifsettlengch return None iffrt ifselflengch == 4: If che queue hes ory one element, update stand last to None selfirst= None sefflast= None else: #Otheraise, remove the first elementand updte fist selfirst=selffirs.nex: temp.next = Non= seflleneth return temp self ength =1 selflengt =1 ifselflergt selthead = None selta return temp det f{aumber|: det f1{0) reel cal for iin range(0, 5): return re the run time of f2(num) is O(1). This is becavse the functon performs a fed No. of operations, regard ess ofthe Input ste. he runame of f3{n) 15 o(7%2) which simplite: gerforms roughly half asm operations (9). This 's because of function algorithm that teretes through a list to find a soccific clement. ‘ithaca linear time complexity of O(n), wharer is the number of elements in the list, Furcton: Def research (ar I 5x) Fret Return -L Farr: ter [Pop] #Remove and return the lst node from the linked list def por( sel ifselflergty return None ithead pre= selthead while temp.next: selttalrext= None seltlength ifselflergta selthese selttal= None return tera [Prepend] #Adde new rode with the given vakie at the beginning of the liked Ist else! Otherwise, acc she new node before the head and update tretead def presend|self vale): new_node = Node(value) ifselflergty # f the lists empty, update head and tailto tre new node selthesc =new_ncce selftal= new_node else: new_node.next = seifhead seltheec =new_rcce seltlength #1. return True [Pop Fits! # Remove and return tre first node from the linked Ist def por Frstsel) ifselflergty return None selthesc temp.ned seltlength ifselflergta selttal= None return tera Nore the found tem moved to the ‘ont or thus allowing successive search for same item to be ‘more really foun), Given the folowing cass declarations fora doubly linked calf adjusting inked ls: cass SeifAdjusting it: dass Noce: ef _init_(oel, tru, suiliieasdiae