You are on page 1of 142

IT122

Introduction to Data
Structures
Module 1
Joie Ann M. Mac
What is Data Structure?

• A data and the operations allowed on that data.

• A way to store and organize data

• logical relationships between individual data elements related to the solution of a


given problem.
Basic Data Structure

Basic Data Structures

Linear Data Structures Non-Linear Data Structures

Arrays Linked Lists Stacks Queues Trees Graphs Hash Tables


Types of Data Structure

• Linear: In Linear data structure, values are arrange in linear fashion.


• Array: Fixed-size
• Linked-list: Variable-size
• Stack: Add to top and remove from top
• Queue: Add to back and remove from front
• Priority queue: Add anywhere, remove the highest priority

array

Linked list
Types of Data Structure
• Non-Linear: The data values in this structure are not arranged in order .
• Hash tables: Unordered lists which use a ‘hash function’ to insert and search
• Tree: Data is organized in branches.
• Graph: A more general branching structure, with less strict connection conditions than for a
tree

queue
tree stack
Type of Data Structures

• Homogenous: In this type of data structures, values of the same types of data are
stored.
• Array

• Non-Homogenous: In this type of data structures, data values of different types are
grouped and stored.
• Structures
• Classes
Abstract Data Type and
Data Structure

• Definition:-
• Abstract Data Types (ADTs) stores data and allow various operations on the data to access and change it.
• A mathematical model, together with various operations defined on the model
• An ADT is a collection of data and associated operations for manipulating that data
Abstract Data Type

• ADTs support abstraction , encapsulation , and information hiding .

• Abstraction is providing only essential information outside the world .

• Encapsulation is binding the data, and the functions that use them
The Core Operations of ADT
• Every Collection ADT should provide a way to:
• add an item
• remove an item
• find, retrieve, or access an item

• Many, many more possibilities


• is the collection empty
• make the collection empty
• give me a sub set of the collection
IT122
Introduction to Python
Module 2
Joie Ann M. Mac
Brief History of Python
Python is a popular programming language. It was created by Guido
van Rossum, and released in 1991.

It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
What can Python do?
• Python can be used on a server to create web
applications.
• Python can be used alongside software to create
workflows.
• Python can connect to database systems. It can also read
and modify files.
• Python can be used to handle big data and perform
complex mathematics.
• Python can be used for rapid prototyping, or for
production-ready software development.
Python Syntax compared to other
programming languages
• Python was designed for readability, and has some similarities to
the English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope;
such as the scope of loops, functions and classes. Other
programming languages often use curly-brackets for this purpose.
http://docs.python.org/
The Python tutorial is good!
Running
Python
Installing

• Python is pre-installed on most Unix systems, including Linux and MAC OS X


• The pre-installed version may not be the most recent one (2.6.2 and 3.1.1 as of Sept 09)
• Download from http://python.org/download/
• Python comes with a large library of standard modules
• There are several options for an IDE
• IDLE – works well with Windows
• Emacs with python-mode or your favorite text editor
• Eclipse with Pydev (http://pydev.sourceforge.net/)
• VS CODE
The Basics
Python Syntax
As we learned in the previous page, Python syntax
can be executed by writing directly in the
Command Line:
Python Indentation
• Indentation refers to the spaces at the beginning of a
code line.
• Where in other programming languages the indentation
in code is for readability only, the indentation in
Python is very important.
• Python uses indentation to indicate a block of code.
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more
readable.
• Comments can be used to prevent execution when
testing code.
Python Variables
• Variables are containers for storing data values.
• Python has no command for declaring a variable.
• A variable is created the moment you first assign
a value to it.
Python Variables - Assign
Multiple Values
• Python allows you to assign values to multiple
variables in one line:
Output Variables
• The Python print() function is often used to output
variables.
Python Keywords
• Keywords are predefined, reserved words used in Python
programming that have special meanings to the compiler.
• We cannot use a keyword as a variable name, function name,
or any other identifier. They are used to define the syntax
and structure of the Python language.
Python Keywords
Python String
• Strings in python are surrounded by either single
quotation marks, or double quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with
the print() function:
Assign String to a Variable
• Assigning a string to a variable is done with the
variable name followed by an equal sign and the
string:
Python Booleans
• Booleans represent one of two values: True or False.
• In programming you often need to know if an expression
is True or False.
• You can evaluate any expression in Python, and get one
of two answers, True or False.
• When you compare two values, the expression is
evaluated and Python returns the Boolean answer:
Python Operators
• Operators are used to perform operations on
variables and values.
• In the example below, we use the + operator to
add together two values:
IT122
Python List
Module 3
Joie Ann M. Mac
List
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
List Items
• List items are ordered, changeable, and allow duplicate
values.
• List items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered
• When we say that lists are ordered, it means that the
items have a defined order, and that order will not
change.
• If you add new items to a list, the new items will be
placed at the end of the list.
Changeable
• The list is changeable, meaning that we can change,
add, and remove items in a list after it has been
created.
Allow Duplicates
• Since lists are indexed, lists can have items with the
same value:
List Length
• To determine how many items a list has, use
the len() function:
List Items - Data Types
• List items can be of any data type:

or
Access Items
• List items are indexed and you can access them by
referring to the index number:

• Print the second item of the list:


Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the second last
item etc.
Range of Indexes
• You can specify a range of indexes by specifying where
to start and where to end the range.
• When specifying a range, the return value will be a new
list with the specified items.
• Return the third, fourth, and fifth item:
Change Item Value
• To change the value of a specific item, refer to the
index number:
• Change the second item:
Insert Items
• To insert a new list item, without replacing any of the
existing values, we can use the insert() method.
• The insert() method inserts an item at the specified
index:
• Insert "watermelon" as the third item:
Append Items
• To add an item to the end of the list, use
the append() method:
• Using the append() method to append an item:
Extend List
• To append elements from another list to the current
list, use the extend() method.
• Add the elements of tropical to thislist:
Remove Specified Item
• The remove() method removes the specified item.
Remove "banana":
Sort List Alphanumerically
• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
Sort the list alphabetically:
Sort Descending
• To sort descending, use the keyword argument reverse =
True:
Sort the list descending:
Pop
• The pop() method removes the element at the specified
position.
Remove the second element of the fruit list:
IT122
Sorting Algorithm
Module 4
Joie Ann M. Mac
Objectives:
• Bubble Sort
• Insertion
• Selection Sort
What is Sorting Algorithm?
• Sorting refers to arranging data in a particular format. Sorting
algorithm specifies the way to arrange data in a particular order.
Most common orders are in numerical or lexicographical order.
• The importance of sorting lies in the fact that data searching can
be optimized to a very high level, if data is stored in a sorted
manner. Sorting is also used to represent data in more readable
formats. Below we see five such implementations of sorting in
python.
Sorting Terminologies
Bubble Sort
• Bubble sort is also referred as Sinking sort
• We repeatedly compare each pair of adjacent items and
swap them if they are in the wrong order
Bubble Sort
Compare the first and second element, if its in order, leave as it is
Bubble Sort
Compare the second and third element, Since 9 is greater than 3
Bubble Sort
Swap
Bubble Sort
Compare the third and fourth element
Bubble Sort
Bubble Sort
Compare until the last element
Bubble Sort
Repeat the process
Bubble Sort
• Until everything is ascending order
Bubble Sort
Bubble Sort
Selection Sort
• Selection sort is a simple sorting algorithm. This sorting
algorithm is an in-place comparison-based algorithm in
which the list is divided into two parts, the sorted part
at the left end and the unsorted part at the right end.
Initially, the sorted part is empty and the unsorted part
is the entire list.
Selection Sort
• Divide the elements into sorted and unsorted
Selection Sort
• For the sorted array, size is 0
Selection Sort
• Find the minimum array
Selection Sort
• Sort with 5
Selection Sort
• Consider 1 as sorted and increase the sorted array
Selection Sort
• Find the minimum
Selection Sort
• Swap with first element which is 7
Selection Sort
• Consider 2 as sorted and increase the size of sorted
Selection Sort
• And so on and so forth until everything is sorted
Selection Sort
Selection Sort
Insertion Sort
• Insertion sort is the simple method of sorting an array.
In this technique, the array is virtually split into the
sorted and unsorted part. An element from unsorted
part is picked and is placed at correct position in the
sorted part.
Insertion Sort
Insertion Sort
• Sort starts with the first element
Insertion Sort
• Check again the first element under unsorted array
Insertion Sort
Insertion Sort
• Insert it before 5
Insertion Sort
• Check the first element under unsorted array
Insertion Sort
• Place it in the sorted array and compare
Insertion Sort
• Place it in the sorted array and compare
Insertion Sort
• Repeat until everything will be sorted
Insertion Sort
Insertion Sort
IT122
Python Collections
Module 5
Joie Ann M. Mac
Objectives:
• Tuples
• Set
• Dictorionary
Creating Tuple
• A tuple is created by placing all the items (elements) inside
parentheses (), separated by commas. The parentheses are
optional, however, it is a good practice to use them.
• A tuple is a collection which is ordered and
unchangeable.
• Tuples are written with round brackets.
• A tuple can have any number of items and they may be of
different types (integer, float, list, string, etc.).
Creating Tuple
Create a Python Tuple With one
Element
• In Python, creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough.
• We will need a trailing comma to indicate that it is a tuple,
Indexing
• We can use the index operator [] to access an item in a tuple,
where the index starts from 0.
Negative Indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last
item and so on. For example,
Slicing
• We can access a range of items in a tuple by using the slicing
operator colon :.
Python Tuple Methods
• In Python ,methods that add items or remove items are not
available with tuple. Only the following two methods are
available.
• Some examples of Python tuple methods
Iterating through a Tuple in Python
• We can use the for loop to iterate over the elements of a
tuple. For example,
Advantages of Tuple over List in
Python
Since tuples are quite similar to lists, both of them are used in similar
situations.
However, there are certain advantages of implementing a tuple over a list:
• We generally use tuples for heterogeneous (different) data types and lists
for homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with a
list. So there is a slight performance boost.
• Tuples that contain immutable elements can be used as a key for a
dictionary. With lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will
guarantee that it remains write-protected.
Sets
• A set is a collection of unique data. That is, elements of a set
cannot be duplicate. For example,
• Suppose we want to store information about student IDs.
Since student IDs cannot be duplicate, we can use a set.
Create a Set in Python
• In Python, we create sets by placing all the elements inside
curly braces {}, separated by comma.
• A set can have any number of items and they may be of
different types (integer, float, tuple, string etc.). But a set
cannot have mutable elements like lists, sets or dictionaries,
as its elements.
• Set items are unchangeable, but you can remove items and
add new items.
Create a Set in Python
Duplicate Not Allowed
Add and Update Set Items in Python
• Sets are mutable. However, since they are unordered,
indexing has no meaning.
• We cannot access or change an element of a set using
indexing or slicing. Set data type does not support it.
• Add Items to a Set in Python
• In Python, we use the add() method to add an item to a set.
For example,
Add and Update Set Items in Python
Update Python Set
• The update() method is used to update the set with items other
collection types (lists, tuples, sets, etc). For example,
Remove an Element from a Set
• We use the discard() method to remove the specified element
from a set. For example,
Built-in Functions with Set
Iterate Over a Set in Python
Find Number of Set Elements
• We can use the len() method to find the number of elements
present in a Set. For example,
Python Set Operations(union)

Union of Two Sets


The union of two sets A and B include all the elements of
set A and B.
Python Set Operations (union)
Python Set Operations (intersection)
The intersection of two sets A and B include the common elements between set A and B.
Python Set Operations (intersection)
• In Python, we use the & operator or the intersection() method to
perform the set intersection operation. For example,
Python Set Operations (Difference
between two sets)
• The difference between two sets A and B include elements of
set A that are not present on set B.
Python Set Operations (Difference
between two sets)
• We use the - operator or the difference() method to perform the
difference between two sets. For example,
Python Set Operations (Set
Symmetric Difference)
• The symmetric difference between two sets A and B includes
all elements of A and B without the common elements.
Python Set Operations (Set
Symmetric Difference)
• In Python, we use the ^ operator or
the symmetric_difference() method to perform symmetric difference
between two sets. For example,
Python Set Operations (Check if two
sets are equal)
• We can use the == operator to check whether two sets are
equal or not. For example,
Python Dictionary
• Python dictionary is an ordered collection (starting
from Python 3.7) of items. It stores elements
in key/value pairs. Here, keys are unique identifiers that are
associated with each value.
Let's see an example,
• If we want to store information about countries and their
capitals, we can create a dictionary with country names
as keys and capitals as values.
Python Dictionary
Create a dictionary in Python

• Here's how we can create a dictionary in Python.


Add Elements to a Python Dictionary

• We can add elements to a dictionary using the name of the


dictionary with []. For example,
Change Value of Dictionary

• We can also use [] to change the value associated with a


particular key. For example,
Accessing Elements from Dictionary

• In Python, we use the keys to access their corresponding


values. For example,
Removing elements from Dictionary

• We use the del statement to remove an element from the


dictionary. For example,
IT112
Recursions
Module 6
Joie Ann M. Mac
Objectives:
• Recursions
• Recursions vs Iterations
• Sample Demo
What is Recursion?
• A way of solving a problem by having a function call itself

Three Properties of Recursions:


• Performing the same operation multiple times with different inputs
• In every step we try smaller inputs to make the problem smaller.
• Base condition is needed to stop the recursion, otherwise infinite loop will occur.
Programmer Joke 101:
Why Recursion?
1. Recursive thinking is really important in programming and it helps you break down big problems
into smaller one.
2. Prominent usage of recursion in data structures like trees and graphs
3. Big companies ask questions related to recursion during the interview.
4. Recursion is used in many algorithms
How Recursion works?
1. A method calls it self
2. Exit from infinite loop
Recursions vs Iterations

Recursion is defined as a process in which a function calls itself repeatedly. Recursion uses selection
structure. If the recursion step does not reduce the problem in a manner that converges on some
condition, called base condition, then an infinite recursion occurs. An infinite recursion can crash the
system. Recursion terminates when a base case is recognized.

Iteration is defined as the repetition of computational or mathematical procedure that continues until
the controlling condition becomes false. It uses repetition structure. If the loop condition test never
becomes false, then an infinite loop occurs with iteration
Recursions vs Iterations
When to avoid it?

- If time and space complexity matters for us.


- Recursion uses more memory. If we use embedded memory. For example an application that
takes more memory in the phone is not efficient
- Recursion can be slow
When to use it?

- When we use memorization in recursion


- When we can easily breakdown a problem into similar subproblem
- When we are fine with extra overhead (both time and space) that comes with it
- When we need a quick working solution instead of efficient one
- When traverse a tree
How to write recursion in 3
steps?
Factorial- Recursion
Factorial- Recursion
F ibonacci numbers - Recursion
F ibonacci numbers - Recursion
Problem 1

You might also like