Python: Linked Lists and Recursion Damian Gordon.

Slides:



Advertisements
Similar presentations
LIST PROCESSING.
Advertisements

Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
CS 240: Data Structures Binary Representations. Binary Binary is a numerical system that is used to represent numeric values. Binary is a numerical system.
CS 206 Introduction to Computer Science II 10 / 01 / 2008 Instructor: Michael Eckmann.
Linked Lists. Example We would like to keep a list of inventory records – but only as many as we need An array is a fixed size Instead – use a linked.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
Patricia P ractical A lgorithm T o R etrieve I nformation C oded I n A lphanumeric. Compressed binary trie. All nodes are of the same data type (binary.
Introduction to Computer Science Recursive Link Operations MergeSort Unit 18.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
General Computer Science for Engineers CISC 106 Lecture 07 James Atlas Computer and Information Sciences 9/18/2009.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
Circular List Next field in the last node contains a pointer back to the first node rather than null pointer From any point in such a list it is possible.
Introduction to C Programming CE Lecture 21 Recursion and Linear Linked Lists.
Introduction to C Programming CE Lecture 22 Recursive Functions for Insertion and Deletion in Linear Linked Lists.
Binary Search Trees Section Trees Trees are efficient Many algorithms can be performed on trees in O(log n) time. Searching for elements.
Data Structures Using C++ 2E Chapter 6 Recursion.
 2003 Prentice Hall, Inc. All rights reserved Linked Lists Upcoming program has two class templates –Create two class templates –ListNode data.
Data Structures Using C++ 2E Chapter 6 Recursion.
Computer Science 111 Fundamentals of Programming I Number Systems.
Python: Modularisation Damian Gordon. Modularisation Remember the prime checker program:
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 9 Iteration: Recursion 5/02/09 Python Mini-Course: Day 3 - Lesson 9 1.
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
Fibonacci Numbers Damian Gordon. Fibonacci Numbers.
Iteration: WHILE Loop Damian Gordon. WHILE Loop Consider the problem of searching for an entry in a phone book with only SELECTION:
Searching Damian Gordon. Google PageRank Damian Gordon.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Question : How many different ways are there to climb a staircase with n steps (for example, 100 steps) if you are allowed to skip steps, but not more.
Python: Arrays Damian Gordon. Arrays In Python arrays are sometimes called “lists” or “tuple” but we’ll stick to the more commonly used term “array”.
Modularisation Damian Gordon. Modularisation Let’s imagine we had code as follows:
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
1 CSE 2341 Object Oriented Programming with C++ Note Set #21.
Linked Lists Revision Based on: v/
Binary Search Trees (BST)
Prime Numbers Damian Gordon. Prime Numbers So let’s say we want to express the following algorithm: – Read in a number and check if it’s a prime number.
Linked list: a list of items (nodes), in which the order of the nodes is determined by the address, called the link, stored in each node C++ Programming:
Linked List.  Is a series of connected nodes, where each node is a data structure with data and pointer(s) Advantages over array implementation  Can.
Python: Structured Programming Damian Gordon. Structured Programming Remember the modularised version of the prime number checking program:
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Doubly Linked List Exercises Sometimes it is useful to have a linked list with pointers to both the next and previous nodes. This is called a doubly linked.
Linked Lists Chapter Introduction To The Linked List ADT Linked list: set of data structures (nodes) that contain references to other data structures.
Recursion Damian Gordon. Recursion Recursion: Factorial Recursion is a feature of modularisation, when a module can call itself to complete a solution.
Python: Stacks and Queues (as a Linked List) Damian Gordon.
Python: Iteration Damian Gordon. Python: Iteration We’ll consider four ways to do iteration: – The WHILE loop – The FOR loop – The DO loop – The LOOP.
Given a node v of a doubly linked list, we can easily insert a new node z immediately after v. Specifically, let w the be node following v. We execute.
Recursion Damian Gordon. Recursion Factorial Fibonacci Decimal to Binary conversion Travelling Salesman Problem Knight’s Tour.
Python: Revision Damian Gordon. Python: Structured Programming Damian Gordon.
  A linked list is a collection of components called nodes  Every node (except the last one) contains the address of the next node  The address of.
PseudoCode: Revision Damian Gordon. Parameter Passing, Scope, Local and Global Variables Damian Gordon.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Python: Recursion Damian Gordon.
5.13 Recursion Recursive functions Functions that call themselves
Linked lists.
Linked Lists Damian Gordon.
Advanced Linked lists Doubly Linked and Circular Lists
COUNTING IN BINARY Binary weightings 0 x x x x 8
Recursion.
Queues: Implemented using Arrays
Python: Algorithms Damian Gordon.
Stacks: Implemented using Linked Lists
Chapter 17: Linked Lists.
Figure 4.1 a) A linked list of integers; b) insertion; c) deletion.
COUNTING IN BINARY Binary weightings 0 x x x x 8
Circular Queues: Implemented using Arrays
Some Common Issues: Print, Maths, Variables
Python: Stacks and Queues (as an Array)
COMPUTER PROGRAMMING SKILLS
Queues: Implemented using Linked Lists
Revised based on textbook author’s notes.
Linked lists.
Presentation transcript:

Python: Linked Lists and Recursion Damian Gordon

Linked Lists

HEAD

Linked Lists: Declaration class ListNode: def __init__(self, value, pointer): self.value = value self. pointer = pointer # END ListNode.

Linked Lists: Declaration node4 = ListNode(31, None) node3 = ListNode(37, node4) node2 = ListNode(62, node3) node1 = ListNode(23, node2)

Linked Lists: Printing print(node1.value) print(node2.value) print(node3.value) print(node4.value)

Linked Lists: Printing def PrintNodes(): print("[", nodeA.value, "] -> [",nodeB.value, "] -> [",nodeC.value, "] -> [",nodeD.value, "] -> NULL") # END PrintNodes.

Linked Lists: Printing def PrintNodes(): print("[", nodeA.value, "] -> [",nodeB.value, "] -> [",nodeC.value, "] -> [",nodeD.value, "] -> NULL") # END PrintNodes. [ 23 ] -> [ 62 ] -> [ 37 ] -> [ 31 ] -> NULL

Linked Lists: Printing def PrintNodesWithLoop(): global HeadNode Current = HeadNode if (Current != None): # THEN while (Current.pointer != None): # DO print(Current.value) Current = Current.pointer # ENDWHILE; print(Current.value) else: print("Empty list") # ENDIF; # END PrintNodesWithLoop.

Linked Lists: Printing def PrintNodesWithLoop(): global HeadNode Current = HeadNode if (Current != None): # THEN while (Current.pointer != None): # DO print(Current.value) Current = Current.pointer # ENDWHILE; print(Current.value) else: print("Empty list") # ENDIF; # END PrintNodesWithLoop.

Linked Lists: Printing def PrintNodesWithLoopAndCount(): global HeadNode Current = HeadNode CountNodes = 0 if (Current != None): while (Current.pointer != None): print(Current.value) Current = Current.pointer CountNodes = CountNodes + 1 # ENDWHILE; # Print out and count for last node CountNodes = CountNodes + 1 print(Current.value) print("Count:", CountNodes) else: print("Empty list") # END PrintNodesWithLoopAndCount.

Linked Lists: Printing Count: 4 def PrintNodesWithLoopAndCount(): global HeadNode Current = HeadNode CountNodes = 0 if (Current != None): while (Current.pointer != None): print(Current.value) Current = Current.pointer CountNodes = CountNodes + 1 # ENDWHILE; # Print out and count for last node CountNodes = CountNodes + 1 print(Current.value) print("Count:", CountNodes) else: print("Empty list") # END PrintNodesWithLoopAndCount.

Linked Lists: Create Empty List def CreateEmptyList(): global HeadNode HeadNode = None # END CreateEmptyList.

Linked Lists: Delete a List def DeleteAList(): global HeadNode HeadNode = None # END DeleteAList.

Linked Lists: Is the List Empty? def ListIsEmpty(): global HeadNode return HeadNode == None # END ListIsEmpty.

Linked Lists: Find A Node def FindANode(N): global HeadNode Current = HeadNode Continued 

Linked Lists: Find A Node while ((Current.pointer != None) and (Current.value != N)): # DO Current = Current.pointer # ENDWHILE; # Print out and count for last node if (Current.pointer == None): # THEN print(N, "is not in the list") else: print("Found value:", Current.value) # ENDIF; # END FindANode.  Continued

Linked Lists: Insert A Node def InsertANode(Pos, N): global HeadNode Current = HeadNode nodeX = ListNode(N, None) PositionCounter = 1 CountNodes = 0 Continued 

Linked Lists: Insert A Node if Pos == 0: HeadNode = nodeX nodeX.pointer = Current else: while (Pos > PositionCounter): Current = Current.pointer PositionCounter = PositionCounter + 1 nodeX.pointer = Current.pointer Current.pointer = nodeX # ENDIF; # END InsertANode.  Continued

Linked Lists: Delete A Node def DeleteANode(N): global HeadNode Previous = None Current = HeadNode Continued 

Linked Lists: Delete A Node if Current.value == N: # THEN HeadNode = Current.pointer else: while ((Current.pointer != None) and (Current.value != N)): # DO Previous = Current Current = Current.pointer # ENDWHILE; Previous.pointer = Current.pointer # ENDIF; # END DeleteANode.  Continued

Recursion

Recursion: Factorial 7! = 7 * (6 * 5 * 4 * 3 * 2 * 1) is 7! = 7 * 6! and 9! = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 9!= 9 * (8 * 7 * 6 * 5 * 4 * 3 * 2 * 1) 9! = 9 * 8! and N! = N * (N-1)!

Recursion: Factorial # PROGRAM RecursiveFactorial def RecursiveFact(n): if n==0: # THEN return 1 else: return n * RecursiveFact(n-1) # ENDIF; # END RecursiveFact. Continued 

Recursion: Factorial ######## MAIN PROGRAM ######### InputVal = int(input("Enter number: ")) print (RecursiveFact(InputVal)) # END RecursiveFactorial.  Continued

Recursion: Fibonacci The Fibonacci numbers are numbers where the next number in the sequence is the sum of the previous two. The sequence starts with 1, 1, And then it’s 2 Then 3 Then 5 Then 8 Then 13

Recursion: Fibonacci # PROGRAM RecursiveFibonacci def RecursiveFib(n): if n==1 or n==2: # THEN return 1 else: return RecursiveFib(n-1)+ RecursiveFib(n-2) # ENDIF; # END RecursiveFibonacci. Continued 

Recursion: Fibonacci ######## MAIN PROGRAM ######### InputVal = int(input("Enter number: ")) print (RecursiveFib(InputVal)) # END RecursiveFibonacci.  Continued

Recursion: Decimal to Binary Conversion How do we convert decimal numbers to binary? Let’s try the number 23… 23 / 2 = 11 and remainder is 1 11/2 = 5 and remainder is 1 5/2 = 2 and remainder is 1 2/2 = 1 and remainder is 0 1/2 = 0 and remainder is 1 >> So DEC 23 is BIN 10111

Decimal to Binary Conversion def DecToBin(n): if n < 0: # THEN return 'Must be a positive integer' elif n == 0: return '0' else: return DecToBin(n//2) + str(n%2) # ENDIF; # END DecToBin. Continued 

Decimal to Binary Conversion ########### MAIN PROGRAM ########### InputVal = int(input("Enter DECIMAL number: ")) print("The number", InputVal, "is",DecToBin(InputVal), "in BINARY") # END DecimalToBinaryConversion.  Continued

Linked Lists: Recursion How do we count the number of nodes in a linked list recursively? def RecursiveCount(Current): : return 1 + RecursiveCount(Current.pointer) :

Linked Lists: Recursion def RecursiveCount(Current): if Current == None: # THEN return 0 else: return 1 + RecursiveCount(Current.pointer) # ENDIF; # END RecursiveCount. print("Recursive Count:", RecursiveCount(HeadNode))

Linked Lists: Recursion How do we print out the nodes in a linked list recursively? def RecursivePrint(Current): : print(Current.value) RecursivePrint(Current.pointer) :

Linked Lists: Recursion def RecursivePrint(Current): if Current == None: # THEN return else: print(Current.value) RecursivePrint(Current.pointer) # ENDIF; # END RecursiveCount. RecursivePrint(Current)

Linked Lists: Recursion How do we find a node in a linked list recursively? def FindANode(Current, N): : return FindANode(Current.pointer, N) :

Linked Lists: Recursion def FindANode(Current, N): if (Current.pointer == None): # THEN return None elif (Current.value == N): # THEN print(N, "was found") return N else: return FindANode(Current.pointer, N) # ENDIF; # END FindANode. FindANode(Current, 37)

Linked Lists: Recursion How do we insert a node in a linked list recursively? def InsertANode(Current, Pos, N): : nodeX = ListNode(N, None) nodeX.pointer = Current.pointer Current.pointer = nodeX : return InsertANode(Current.pointer, Pos, N)

Linked Lists: Recursion def InsertANode(Current, Pos, N): if (Current.pointer == None): # THEN return None elif (Current.value == Pos): # THEN nodeX = ListNode(N, None) nodeX.pointer = Current.pointer Current.pointer = nodeX return N else: return InsertANode(Current.pointer, Pos, N) # ENDIF; # END. InsertANode. RetValue = InsertANode(Current, 37, 12345) RecursivePrint(Current)

Linked Lists: Recursion How do we delete a node in a linked list recursively? def DeleteANode(Current, N): : Current.pointer = DeleteANode(Current.pointer, N) :

Linked Lists: Recursion def DeleteANode(Current, N): if (Current != None): # THEN if (Current.value == N): # THEN Current = Current.pointer else: Current.pointer = DeleteANode(Current.pointer, N) # ENDIF; return Current # END DeleteANode. RetValue = DeleteANode(Current, 12345) RecursivePrint(Current)

etc.