Cc103data Structure Module Not For Sale With Cover
Cc103data Structure Module Not For Sale With Cover
1
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Overview
This unit enlightens the students about the basics of data structures and algorithms. It
also introduced the Python programming and showed how the primitive data structures are
implemented. The mobile engine for Python is also present to familiarize the students. Array
and its operations are also discussed.
Learning Objectives
In this unit, I will learn:
1. To define data structure;
2. To distinguish data structure from algorithm;
3. Understand the behavior of primitive from non-primitive data structures;
4. Implement array to python programs; and
5. Appreciate Python programming and its data structures using mobile phone.
Setting Up
1. Assume you have a plate of spaghetti. Can you enumerate your procedures on how you
eat this messy food?
2. You did laundry, and it was already dry. How can you manage those clean clothes?
3. If you have a ten stack of chairs, how can you remove the chair number 6?
Lesson Proper
The data structures deal with how the data is organized and stored in the memory when
the program processes it and the algorithms are used to work data in these structures. It also
refers to a system for storing data. In other words, a data structure is an arrangement of data in
computer memory in such a way that it can quickly render the data accessible to the processor
for the necessary calculations.
An Algorithm is a set of instructions to process the data for a specific purpose.
Algorithms are implemented in the form of methods or functions or routines. An efficient
algorithm will be used to solve the problems quickly. One criterion of efficiency is the
algorithm's time, and another could be the memory it takes at run time.(
www.hashirharis.wordpress.com/category/python/)
Data Types
“The data structures are actually an implementation of Abstract Data Types or ADT. This
implementation requires a physical view of data using some collection of programming
constructs and basic data types.
2
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
• Data types are attributes or characteristics of data. It classifies data according to its
purpose.
• Data structures can have two categories, the primitive and non-primitive.
• The primitive is the simplest form of data representation, whereas the non-primitive is
more advanced.
Jaiswal(2017) stated that the primitive data structures are the basic data structures. They
are the building blocks for data manipulation and contain pure, simple values of a data.
3
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Array
Stack
Queue
4
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
The Python programming language was originally developed by Guido van Rossum in the
early 1990s, and has since become a prominently used language in industry and education. The
second major version of the language, Python 2, was released in 2000, and the third major
version, Python 3, released in 2008.
Python is formally an interpreted language. Commands are executed through a piece of
software known as the Python interpreter. The interpreter receives a command, evaluates that
command, and reports the result of the command.
For Python, source code is conventionally stored in a file named with the .py suffix (e.g.,
hello.py).
Python Applications
Python can be used to different aspects and scenarios. The following are the list of
different ways where you can apply Python.
Advantages of Python
There are many reasons you need to study Python, and the list below are some of its
advantages:
• Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it.
• Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner’s Language: Python is an excellent language for the beginner-
level programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.
(https://hashirharis.wordpress.com/category/python/)
5
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
User-defined Data-structures:
Arrays: It is similar to Lists, but the difference is it can store single element/datatype
Stack: Linear LIFO (Last-In-First-Out) Data structure
Queues: Linear FIFO (First-In-First-Out) data structure
Trees: Non-Linear data structures having a root and nodes
Linked Lists: Linear data structures that are linked with pointers
Graphs: Store a collection of points or nodes along with edges
Hash Maps: It is the same as Dictionaries.
6
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Installing Python
Windows Installation
7
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Save your file to your folder Python34/ and use .py extension name file.
How to Run
8
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
output
Due to pandemic situation, online learning and mobile learning are needed. Instead of using
the school computer laboratory, it is the new normal to use alternative device to sustain the
quality of education you need. In our case, when the students do not have their own laptop or
desktop, your mobile phone with QPython and Pydroid are recommended for you to perform
your laboratory exercises. QPython is the Python engine for android which contains some
amazing features such as Python interpreter, runtime environment and editor. It makes it easy
for you to use Python on Android and also it is open source or free. All you need to do is to
download it in https://apkpure.com/qpython-3l-python-for-android/org.qpython.qpy3
For different usage scenarios, QPython has two branches, namely QPython Ox and 3L.
QPython Ox is mainly aimed at programming learners, and it provides more friendly features
for beginners. The QPython 3L is mainly for experienced Python users, and it provides some
advanced technical features.
9
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
2. From your phone, Click the QPython icon and the new screen will show
3. Click Console if you want an instant calculations and Click Editor if you want to type
your code. To save the file, Click the icon Save, the screen below will show.
4. To run the file, Click the Play button and you will see the screen below
.
10
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Python Identifiers
“A Python identifier is a name used to identify a variable, function, class, module or other
object .”( www.studocu.com/de/document/wheaton-college/computer-literacy/uebungen/python-
tutorial/2712597/view).
• The identifier is also starts with a lowercase letter or capital letters or it has an
underscore (_) followed by letters or numbers (0 to 9).
• Punctuation characters like %, @, and $ within identifiers are not valid.89=]]
• It is also case sensitive programming language where Power and power are two
dissimilar identifiers” (”hashirharis.wordpress.com/category/python/).
• Class names begins with the capital letter and other identifiers start with a lowercase
letter.
• An identifier with a single leading underscore specifies as private identifier.
• An identifier with two leading underscores specifies a strongly private identifier.
• The identifier with two trailing underscores ends defined as special name”(
Reserved Words
The following are the Python reserved words and cannot be used as constant or variable or
any other identifier names.
11
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
• Python don’t have braces. The blocks of code are signified by line indentation which
is strictly required.
• The number of spaces in the indentation is variable, and all statements must be
indented all within the block.
Quotation in Python
• It accepts single (‘), double (“) and (‘’’ or “””) quotes to represent string literals, as
long as the same type of quote starts and ends the string.
• The triple quotes are used to span the string across multiple lines. The following
examples are valid:
• A hash tag sign (#) is used to begin in a comment. All typescripts/characters after the
# and ip to the end of the physical line are part of the comments.
12
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Output:
13
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
14
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Python Strings
Strings are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. “Subsets of strings can be taken
using the slice operator ([] and [:]) with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end. The plus (+) sign is the string concatenation operator and
the asterisk (*) is the repetition operator(www.studocu.com/de/document/wheaton-
college/computer-literacy/uebungen/python-tutorial/2712597/view).
Try This!
Output:
15
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Array
An array is a data structure, which can store a fixed-size collection of elements of the same
data type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Python can also handle containers with specified data types. Array can be handled in python
by module named “array “. It can be useful in manipulating a specific data type value.(
www.datacamp.com/community/tutorials/data-structures-python)
Operations on Array
1. array(data type, value list) :- This function is used to make an array with data type and
value list specified in its arguments.
2. append() :- This function is used to add the value at the end of the array in its arguments.
3. insert(i,x) :- This function is used to add the value at the location specified in its argument.
Try This!
16
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Output:
4. pop() :- This function removes the element at the location mentioned in its argument, and
returns it.
5. remove() :- This function is used to remove the first occurrence of the value mentioned in
its arguments.
6. index() :- This function returns the index of the first occurrence of value mentioned in
arguments.
Try This!
Output:
17
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
References
18
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
NAME: ___________________________________DATE:_____/_____/2020__
SECTION:_BSIT-__________________________SCORE:_______/30_______
QUIZ
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
2. I discovered that_________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
3. How does Python implement data structures?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
19
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Hello
Students
Of
Data Structure
and Algorithms
Hello Students of Data Structure and Algorithms
20
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Requirements:
21
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Overview
This unit kills four birds with one stone: You develop a strong understanding of
the stacks and queues, strengthen your abilities in working with arrays, and develop a
moderate facility with linked lists.
Learning Objectives
At the end of the lesson, you are expected to:
1. create a program using array-based lists;
2. create programs using linked lists; and
3. create a program using doubly linked list.
Setting-Up
1. What linked lists are and when you should use them
2. How to use collections.deque to implement queues and stacks
3. How to implement your own linked list and node classes, plus relevant methods
4. What the other types of linked lists are and what they can be used for
Lesson Proper
Linked list
Linked lists are an organized set of items. Linked lists are distinct from lists because they
retain items in memory. Although lists use a single block of memory to store their data
references, related lists store references as one of their own components.
Main Concepts
Each element of a linked list is called a node, and every node has two different fields:
1. Data contains the value to be stored in the node.
2. Next contains a reference to the next node on the list.
Here’s what a typical node looks like:
22
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
A linked list is a
collection of nodes. The first node is called the head, and it is used as the starting point for
any iteration through the list. The last node must have its next reference pointing to None to
determine the end of the list. Here’s how it looks:
Practical Applications
Linked lists represent a variety of real-world purposes. These will be used for the creation
of queues or stacks (spoiler alert!) as well as diagrams. These are often beneficial for even more
complicated functions, such as life-cycle management for an application to operating system.
Queues or Stacks
Queues and stacks only vary in how items are recovered. You'll need a First-In / First-Out
strategy (FIFO) with a line. This assumes the first item to be recovered added in the chart is the
first item to:
You can see the front and rear components of the queue in the image above. These can move
to the far end as you add new items to the list. They'll be pulled from the front of the list as you
grab objects.
You use a Last-In / Fist-Out method (LIFO) for a stack, implying the last item placed in the list
is the first one to be retrieved:
23
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Within the example above it indicates that at the bottom is the first element placed on the
stack (index 0), and at the top is the last element placed. The last item inserted (at the top) would
be the first to be retrieved because stacks use the LIFO method.
One of the most convenient ways to implement those data structures is to insert and retrieve
elements from the edges of queues and stacks, linked lists.
Graphs
Graphs can be used to display object relationships, or to represent different network types.
A graphic depiction of a graph, for example — say a directed acyclic graph (DAG)—might
look like this:
24
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
There are different methods of applying graphs such as the above, but one of the more
common is to use an adjacency chart. An adjacency list is a set of linked lists in which each
graph vertex is placed alongside a selection of linked vertices:
In the table above, the left column lists every vertex in the line. The right column includes
a set of related lists that store the other vertices in the left column which are bound to the
corresponding vertex. This adjacency list may also be described with a dictum in code:
This dictionary's keys are the vertices of the source, and a list is the meaning for any
word. Typically the set is enforced as a connected array
Implementing graphs using adjacency lists is very effective in terms of both speed and
memory as contrasted with, for example, an adjacency matrix. For this function connected
lists are so useful to execute graphs.
Performance Comparison: Lists vs Linked Lists
Implementing graphs using adjacency lists is very effective both in terms of speed and
memory, as contrasted with an adjacency matrix, for example. Lists attached for this purpose
are so useful for executing graphs.
As the gap in memory use between the lists and the related lists is too small, when it comes
to time complexity, it is easier to concentrate on their output disparities.
25
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Introducing collections.deque
In Python, the collections module contains a specific object you can use for linked lists
called deque(pronounced "deck"), which stands for double-ended queue.
Collections.deque uses a connected list application in which items may be viewed, added
or deleted from the beginning or end of a list with constant O(1) output.
How to Use collections.deque
There are quite a few methods which come with a deque object, by default. However,
you'll just focus on a couple of them in this post, mainly for incorporating or deleting
components.
Next, building a related chart. To do so with deque, you may use the following piece of
code:
The code above should generate a list of empty connections. If you want it to be filled in
at development, you may give it an iterable as input:
26
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
You may transfer any iterable as an input while initializing a deque object, including a string
(also an iterable) or a list of objects.
Now that you know how to create a deque object, by adding or removing elements, you
can interact with that. You can create a linked list with abcde and add a new element f like this:
Both append () and pop() add or subtract items from the related list on the right side.
Moreover, you may also use deque to add or delete items from the list easily from the left
side, or head:
27
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Using the deque object, adding or removing elements from both ends of the list is fairly
straightforward. Then you're able to know how to build a list or a stack using
collections.deque.
Now you are in queue with Mary, John, and Susan. Know, because queues are FIFO, the
first person who has joined the queue will be the first one to get out.
28
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Now assume that some time will pass and that a few tables will become available. You want
to bring people out of the queue in the appropriate order at this point. Then you'd put something
like this:
Each time you call popleft(), (the head item is removed from the linked list, mimicking a
real-life queue.
Stacks
What if then you wanted to build a stack? Ok, the principle is pretty much the same as for
the list. The only difference is that the stack uses the LIFO approach , which means the last
element to be inserted into the stack should be removed first.
If you want this action to be transformed into a stack so you could do something like this:
29
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
References
https://devsday.ru/blog/details/15450
https://www.tuicool.com/articles/fmaMFvY
https://realpython.com/linked-lists-python/
https://flosshub.org/aggregator/sources/13?page=36
https://www.flosshub.org/aggregator?page=115
moz-extension://a071a1d5-e026-4c58-a261-ddf2e8898cdb/html/block_page.html
https://digitechbuy.com/fkeujms/create-circular-queue-in-python.html
https://www.codementor.io/@codementorteam/a-comprehensive-guide-to-
implementation-of-singly-linked-list-using-c_plus_plus-ondlm5azr
https://www.cs.auckland.ac.nz/compsci105s1c/lectures/Bruce/19-LinkedList(3).pdf
https://www.softwaretestinghelp.com/linked-list/
https://smartcatcontrol.com/lgdrlg8/7aff9.php?qp=implement-queue-using-linked-list-
geeksforgeeks
http://core.loyc.net/collections/dlist.html
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.27.4867
https://www.sitepoint.com/ruby-interview-questions-linked-lists-and-hash-tables/
30
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
1. Create a method to retrieve an element from a specific position: get(i) or even llist[i].
31
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
32
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
UNIT 3. RECURSION
Overview
Often considered one of the more conceptually difficult concepts within the field of
Computer Science is recursion. In this unit, you will take an in-depth look at recursion,
learning the recursive steps, the role that recursion plays in common data structures, and what
happens inside the computer when a recursion function is invoked. By the end of this unit,
you will recognize situations that require recursion and be able to apply it appropriately
Learning Objectives
At the end of the unit, you should have the capacity to:
Setting Up
1. What is recursion?
2. What are the properties of recursion?
3. How to implement recursion in python?
Lesson Proper
What is recursion?
In literal definition, “It is the determination of a succession of elements by operation on one or
more preceding elements according to a rule or formula involving a finite number of steps” (
https://www.merriam-webster.com/dictionary/recursion)
In mathematical, a recursive method is one that is characterized by a base case and itself.
While recursion is amazing, recursive arrangements are not generally the most productive. In a
few occasions, in any case, recursion is the execution of decision as it permits us to handily build
up an answer for a confused issue that may some way or another be hard to unravel.
33
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Recursive definitions
• However, things being what they are, many programming construct are characterized as
far as themselves
• Luckily, the proper reason for these definitions is to such an extent that no infringement
of the guidelines happens
• These definitions are called recursive definitions and are frequently used to characterize
interminable sets
• This is on the grounds that a thorough list of such a set is inconceivable, so some others
intends to characterize it is required
• Thus, a method is called recursive if the body of the method calls the method itself, either
straightforwardly or by implication.
Properties of recursion
A recursive method can go unbounded like a circle. To maintain a strategic distance from
unbounded running of recursive method, there are two properties that a recursive method
must have :
• Base case − there must be at any rate one base measures or condition, to such an extent
that, when this condition is met the method quits calling itself recursively.
• Progressive action − the recursive calls should advance so that each time a recursive
call is made it comes nearer to the base case.
• If the method has boundaries, they should be introduced to their relating contentions
• In expansion, we have to realize where to continue the calling method once the called
method is finished
• Since methods can be called from different methods, we additionally need to monitor
neighborhood factors for scope purposes
• Because we may not know ahead of time what number of calls will happen, a stack is a
progressively proficient area to spare data
• So we can describe the condition of a method by a lot of data, called an actuation record
or stack outline
34
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
• This is put away on the runtime stack, and contains the accompanying data:
– Values of the method’s parameters, addresses of reference variables (including
arrays)
– Duplicates of local variables
– The return address of the calling method
– A dynamic connect to the calling method’s actuation record
– The method’s return value if it is not void
• Every time a method is called, its actuation record is made and placed on the runtime
stack
• So the runtime stack always contains the current state of the method
• As a representation, consider a method fun1() called from main()
• It thus calls method fun2(), which calls method fun3()
• The present status of the stack, with method fun3()executing, is manifest in fig 3.1
• Once fun3()completes, its record is popped, and method fun2()can resume and access
data in its record
• If fun3()calls another method, the new method has its actuation record pushed onto the
stack as fun3() is suspended
35
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
• Essentially, when a method calls itself recursively, it pushes a new actuation record of
itself on the stack
• This suspends the calling instance of the method, and permits the new
actuation to carry on the procedure
Consider the basic problem of printing the numbers from 1 to n in reverse order. The
iterative solving for this problem is fairly basic when using a loop build. Be that as it may, it
can likewise be settled recursively, that is, utilizing a recursive method. Assume we have applied
the following tail recursive method in python:
Def printrev( n ):
if n > 0 :
print( n )
printrev ( n-1 )
36
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
contain the contents of local variables and only the statements of the function actually
executed. Each recursive call to printrev() is shown inside its own box with the boxes
positioned at the point where the function was invoked.
These recursive calls precede until a value of zero is passed to the method, at which
time the body of the if statement is skipped and execution arrives at the end of the method.
Similarly as with any method call, when execution arrives at the end of the method or the return
statement, execution comes back to the area where the method was initially called. For this
situation, the call to printrev(0) was done using inside the printrev(1) instance. Along these lines,
execution comes back to the principal proclamation after that conjuring. After execution comes
back to the printrev(1) instance, the end of that method is reached and again execution is come
back to the area where that example was conjured. The outcome is a chain of recursive returns or
recursive loosening up back to the original printrev(4) function call.
What changes would be required to make a recursive method to print the similar
numbers in increasing order instead of reverse order? We can alter the location of the
recursive call to change the action of the recursive solution. Consider a non-tail recursive
print method:
Def printinc( n ):
if n > 0 :
printinc( n-1 )
37
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
print( n )
In this form, the recursive call is done ahead the value of n is printed. The outcome is
a series of recursive calls former to any other action is done. The actual printing of the values
is carry through after each instance of the method returns, as shown in figure 3.2(b).
Indirect recursion
• The earlier topics have concentrated on circumstances where a method, f(), calls itself
recursively which are examples of direct recursion.
• But, in certain circumstances, the method may be invoked not by itself, but by a method
that it calls, forming a chain:
F()→ g() → f()
• This is called as indirect recursion
• the chains of calls may be of discretionary length, such as:
F() → f1() → f2() → ∙∙∙ → fn() → f()
• It is likewise conceivable that a given method may be a part of multiple chains, based
on various calls
• So our past chain may resemble:
Nested recursion
• Another fascinating sort of recursion happens when a method invoke itself and is also
one of the arguments of the call
• Consider this example:
• From this definition, it is given that the method has solutions for n = 0 and n > 4
38
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
• On the other hand, for n = 1, 2, 3, and 4, the method determines a value depend on a
recursive call that requires assessing itself
• This is called nested recursion
• That signifies “recursion inside recursion”.
• Another model is the renowned (or perhaps infamous) ackermann function, defined as:
• first proposed by wilhelm ackermann in 1928 and later changed by rosza peter, it is
portrayed by its fast development
• to get a sense of this development, think about that a(3,m) = 2m+3 – 3, and
Excessive recursion
• Recursive algorithms will in general show straightforwardness in their usage and are
regularly simple to peruse and follow
• But, this straightforwardness has few downsides
• Generally, as the number of method calls raise, a program undergo some performance
decrease
• Besides, the amount of stack space required increments drastically with the amount of
recursion that happens
• This can prompt program crashes if the stack comes up short on memory
• More frequently, the expanded execution time produce poor program performance as
an example of this, consider the fibonacci numbers
39
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
• They are first referenced regarding sanskrit poetry as far back as 200 bce
• Leonardo pisano bigollo (also known as fibonacci), popularized them to the western
world in his book liber abaci in 1202 ce
• The initial few terms of the sequence are 0, 1, 1, 2, 3, 5, 8, … and can be produced
utilizing the method:
• This disclose us that that any fibonacci number after the initial two (0 and 1) is
characterized as the sum of the two past numbers
• But, as we move further on in the flow, the amount of calculation necessary to produce
successive terms becomes enormous
• This is because every computation ultimately has to depend on the base case to
calculate the values, since no intermediate values are recalled
• The following algorithm executes this definition; once more, notice the modesty of the
code that negates the underlying incapability.
Def fib(n):
if n < 2:
return n
else:
return fib(n-2) + fib(n-1)
• If we apply this to compute fibo(6)(which is 8), the algorithm starts by computing fibo
(4) + fibo (5)
• The algorithm then have to compute fibo (4) = fibo (2) + fibo (3), and lastly the first
term of that is fibo (2) = fibo (0) + fibo (1)= 0 + 1 = 1
• The whole procedure can be shown using a tree to represents the computation:
40
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Number of addition operations and number of recursive calls to compute fibonacci numbers
• Notice that it takes right around 3 million calls to determine the 31st fibonacci
number
• This exponential development makes the algorithm inadmissible for anything besides
small values of n
• Fortunately there are adequate iterative algorithms that can be utilized unquestionably
more successfully
Backtracking
• Backtracking is a way to deal problem solving that utilizes a systematic search among
potential pathways to a solution
• As each path is analyzed, if it is determined the pathway isn’t suitable, it is disposed
and the algorithm comes back to the earlier branch with the goal that an alternate path
can be investigated
• Thus, the algorithm must have the capacity to come back to the past position, and
ensure that all pathways are inspected
• Backtracking is utilized in various applications, including compiling, optimization
problems and artificial intelligence
• Below is an example of searching all possible order of arrangements of a given set of
letters.
• When we pick a couple we apply backtracking to confirm if that exact pair has just
been made or not.
41
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
• If not already made, the pair is added to the result list else it is disregarded.
Drawbacks of recursion
42
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
– Using up too many assets (e.g., var declarations) for each function call
Def func(num):
print(num)
amlist = []
amlist.append("*")
num = num + 1
func (num)
Func (1)
43
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
References:
Drozdek ,adam (2013). Data structures and algorithms in c++ fourth edition
https://www.geeksforgeeks.org/types-of-recursions/
https://www.merriam-webster.com/dictionary/recursion
https://www.tutorialspoint.com/data_structures_algorithms/recursion_basics.htm
44
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
45
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Write a recursive method to output a reversed string input from the user.
46
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Write a program with a recursive method that will compute a factorial of a number given by a
user.
47
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Overview
This unit covers the discussion on trees such as binary tree, healp, binary search tree
.and balancing a tree
Learning Objectives
Setting Up
1. What is binary tree?
2. What is heap?
3. How to implement binary search tree in Python?
What is a tree?
A tree is a structure of data that is displayed similar to the structure of the real tree. But the
tree structure in real life has its leaves (or nodes) and branches located in the top while the tree
described in this lesson is opposite, the construction is upside down the nodes (or leaves) and
branches are downward and the root of the tree is at the top. Trees can contain a large volume
of connected data which is somehow do not contain a cycle.
Shows the representation of the real tree and the tree in data structure
48
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
A binary tree represents structure in which every part of branches in the structure contains
two or more children which we call it as nodes, these nodes can be called right node or left
node, we can also call it as left child or right child, Binary tree supports binary search tree and
heap, A binary tree can be characterized in dissimilar methods with independent structures of
data such as list or dictionary and class for a node.
The code below will create of Binary Tree that look like these:
/ \
2 3
/ \ / \
4 5 6 7
class Node(object):
self.value = value
self.left = None
self.right = None
49
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
class BinaryPuno(object):
self.root = Node(root)
# Set up tree:
tree = BinaryPuno(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
The subtree in the left of a node contains just node with keys lesser than the node’s key at the
right. The subtree right of a node contains just node with keys more superior than the node’s
key in left. The subtree in right and left must have be another binary search tree
12
/ \
10 11
/ \ \
13 14 20
/ \ /
15 16 25
50
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
To perform Binary Tree searching we will input a number and our program will determine
which of this number is the closest number in our tree we will create a function
“def closest_value” to perform these action, below is the entirety of our example
class NodeOfTree(object):
self.val = x
self.left = None
self.right = None
w = ugat.val
if not bata:
return w
s = closest_value(bata, target)
myTree = NodeOfTree(12)
myTree.left = NodeOfTree(10)
myTree.right = NodeOfTree(11)
myTree.left.left = NodeOfTree(13)
myTree.left.right = NodeOfTree(14)
myTree.left.right.left = NodeOfTree(15)
myTree.left.right.right = NodeOfTree(16)
myTree.right.right = NodeOfTree(20)
myTree.right.right.left = NodeOfTree(25)
51
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
print(result)
Output
20
Balanced Binary Search Tree is a binary search tree which can balance and stabilize itself,
while this tree can adjust and correct itself to be able to maintain a logarithmic low height
allowing it to speed up operations particularly the insertions and the deletions.
The code below performs Balanced Binary Search Tree it accomplishes the
displaying(printing) of the searched values of the tree, and then balances and orders it by
moving and jumping (Traversing) from one node to another, this is in the form of preorder or
prearrange, in order or in Arrange and post order or postArrange.
class Node(object):
self.value = value
self.left = None
self.right = None
class BinaryPuno(object):
self.root = Node(root)
52
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
if traverse_type == "preArrange":
else:
return False
"""Root->Left->Right"""
if start:
return traverse
"""Left->Root->Right"""
if start:
return traverse
53
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
"""Left->Right->Root"""
if start:
return traverse
tree = BinaryPuno(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
print("preArrange")
print(tree.print_tree("preArrange"))
print("inArrange")
print(tree.print_tree("inArrange"))
print("postArrange")
print(tree.print_tree("postArrange"))
Output:
preArrange
1->2->4->5->3->6->7->
inArrange
4->2->5->1->6->3->7->
54
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
postArrange
4->5->2->6->7->3->1->
What is a Heap?
The Heap is the information structure essentially used to present the priority line. to utilize
this to Python we will use and import the "heapq" module. The property of this information
structure in python is that each time the smallest of load component is popped at whatever
point components are pushed or popped, and the structure is kept up. The heap [0] component
likewise restores the littlest component each time.
The following are the operations of the Heap shown by the comments(#) and the code
below
NOTE: when you put the hashtag (#) in your code with any text on it the Python will just
ignore it
import heapq
lis1 = [1,5,3,7,11,15]
#Organizing lis1 Array as Heaps or in other terms convert the created list into heap
heapq.heapify(lis1)
#print the created heaped list/NOTES the end= is use to connect the print item below
print(list(lis1))
heapq.heappush(lis1,87)
print("the heaped list below inserts the number 87 it did becase of heappush")
55
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
print(list(lis1))
heapq.heappushpop(lis1,100)
print("the heaped list inserted the number 100 but pops the number 1 in the list")
print(list(lis1))
######################################################
lis2= [2,4,6,8,10,12]
heapq.heapify(lis2)
print(list(lis2))
heapq.heapreplace(lis2,200)
print("The following are the 2nd heaped list inserts the ")
print("200 in the center and removes the first number which is number 2")
print(list(lis2))
print(heapq.nlargest(3,lis2))
56
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
print(heapq.nsmallest(3,lis
References
https://pythonspot.com/python-tree/
https://www.geeksforgeeks.org/binarytree-module-in-python/
https://docs.python.org/2/library/heapq.html
https://gist.github.com/pavlin-policar/63e237b5e0b9c8dc1b47b0e4f780a88f
https://docs.python.org/2/library/heapq.html
57
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Write a python program that will create a binary tree shown below.
50
/ \
45 47
/ \ / \
32 34 35 38
/ \ / \ / \ / \
20 21 22 23 24 25 26 27
/ \ / \ /\ / \
11 12 13 14 16 17 18 19
58
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Create a Binary Tree use the answers in the multiplication table of 6 as the nodes of your
binary tree then display the number closest to number 15
59
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
60
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Learning Objectives:
At the end of this lesson, I can:
1. Develop and implement the practical sorting algorithms; and
2. Use breadth-first, depth-first, and best-first search to introduce data structures for
graphs, and search approaches.
Setting Up
1. What are the different sorting algorithim?
2. What is Decision Tree?
3. What is Graphs Data Structure?
Learning Proper
Sorting
Sorting a process of a collection of items arranged or ordered each item and its successor
satisfies a prescribed relation. The objects may be fundamental values like integers and reals,
or more complex types like student records or dictionary entries. In either case, the items are
ordered based on the value of a sort key. The key is the value itself when sorting simple types,
or when sorting complex models, and it can be a Particular component or a
component combination. We encounter many examples of day-to-day sorting in life. Consider
the listings of a phone book, the definition in a dictionary, or the terms in an index,
all organized in alphabetic order to make it much easier to find an entry.
There are many different algorithms for sorting the data and among few popular ones are
Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort
A simple solution to the problem of sorting is the bubble sort algorithm, which rearranges
the values several times by iterating over the list, allowing more massive amounts to bubble to
the top or end of the list. To illustrate how the algorithm of bubble sorting works,
suppose we have four play cards that we want to order from the smallest to the most
significant face value. As shown here, we start by laying the cards face up on a table:
61
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
The algorithm involves numerous card transfers, each pass starting with the first card and
ending one card earlier than the previous iteration. The cards in both the first and second
positions compared during each move. If the first one is greater than the latter, then the two
cards will be swapped.
Next, they compare the cards in positions two and three. When the first is more significant
than the second, otherwise, they will be swapped. Otherwise, we'll leave it as it was.
For each successive pair of cards, this process continues until the card with the highest face
value positioned at the end.
62
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
The next two passes over the cards shown below. In the second move, the card put in the
next-to-last slot with the second-largest face value. The first two cards will be positioned
correctly on the third and final pass.
(Pass 2) Repeat the process on the first three cards. Compare the 5
and 8. Since five is less than 8, leave them as is.
(Pass 3) Repeat the process on the first two cards. Compare the 5 and 3. Since five is more
significant than 3, swap the two cards.
After swapping the two cards, all of the cards are now in their proper order, from smallest to
largest.
63
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
Selection Sort
A second sorting algorithm, which builds on the bubble sort and works in a manner close to
what an individual would use to sort a list of values, is called the kind of selection. We can
use the play cards set again to demonstrate the algorithm and start by placing five face-up
cards on a table to be sorted in ascending order.
Instead of swapping the cards, we did the bubble sort; we'll scan through the cards and select
the smallest of those on the table and put it in our hand. We identify the three as the lowest,
for our set of cards:
We take the three and put it in our hand, leaving the rest of the cards on the table:
64
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
The process repeated, and we mark the five as the next smallest face value:
We pick up the five and move it to the proper sorted location on the right side as there are no
cards left on the table with a lower face value.
The process continued until all the cards are picked up and placed in our hands from smallest
to most significant in the correct sorted order. The method we've used to sort the set of
five cards is similar to the selection sort algorithm approach. But the algorithm preserves both
the sorted and unsorted values within the same sequence-structure when
implementing insertion sort in code.
The selection sort, which improves on the kind of bubble, makes several passes over the
series, but unlike the bubble sort, after each pass, it only makes one swap. The selection sort
algorithm to implemented given in Listing 3.
the result pick up the last pick up the next Pick up the next
our hand
65
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
66
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
References
1. http://home.ustc.edu.cn/~huang83/ds/Data%20Structures%20and%20Algorithms%20
Using%20Python.pdf
2. https://www.tutorialspoint.com/python_data_structure/python_graph_algorithms.htm
3. https://jeffe.cs.illinois.edu/teaching/algorithms/book/05-graphs.pdf
4. https://learn.saylor.org/course/view.php?id=39§ionid=410
5. https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/
67
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE
68