Quiz 3 Material
Quiz 3 Material
2
Definition
Proposition:
• A proposition is a declarative sentence that is either true (T) or false (F)
but not both.
3
Propositions
Examples:
• 2+2 = 4.
• It is Sunday today.
• “3 + 2 = 5” and “Dubai is a city in the UAE”
• “The grass is green” or“ It is hot today”
• “Discrete Mathematics is not difficult for me”
--------------------------------------------------------------------------------------------
Here, AND, OR, NOT are called LOGICAL CONNECTIVES.
If a proposition is true, we say that it has a truth value of “True ”.
If a proposition is false, its truth value is “ false".
The truth values “true” and “false” are, respectively, denoted by the letters T
and F.
4
Symbolic Representation
SYMBOLIC REPRESENTATION
Propositions are symbolically represented by letters such as p, q, r,..
EXAMPLES:
• P = “Abu Dhabi is the capital of the UAE”.
• q =“17 is divisible by 3”.
5
Logical Connectives
6
Examples
7
Truth Table
8
Negation
9
Conjunction
10
Disjunction
11
Exclusive OR
12
Conditional Statements
13
Conditional Statements
14
Biconditional Statements
15
Bitwise Operations
• Computer bit operations correspond to the logical connectives. By
replacing true by a one and false by a zero in the truth tables for the
operators ∧, ∨, and ⊕, the tables shown for the corresponding bit
operations are obtained.
• We will also use the notation OR, AND, and XOR for the operators ∨,∧,
and ⊕, as is done in various programming languages.
16
Bitwise Operations: Example
Exercise
•EXAMPLE : Find the bitwise OR, bitwise AND, and bitwise XOR of the bit
strings 01 1011 0110 and 11 0001 1101. (Here, and throughout this book, bit
strings will be split into blocks of four bits to make them easier to read.)
•Solution: The bitwise OR, bitwise AND, and bitwise XOR of these strings
are obtained by taking the OR, AND, and XOR of the corresponding bits,
respectively. This gives us
17
Truth Table Examples
18
Answer 1
19
Answer 2
20
Answer 3
21
Translation from English to Logic Symbols
22
Translation from English to Logic Symbols: Example
Let p and q be propositions:
• p = “you get an A on the final exam”
• q = “you do every exercise in this book”
• r = “you get an A in this class”
23
Translation Symbolic Proposition to English
Let p, q, and r be the propositions:
• p = “you have the flu”
• q = “you miss the final exam”
• r = “you pass the course”
A NOT-gate (or inverter) is a circuit with one input and one output
signal. If the input signal is 1, the output signal is 0. Conversely, if the
input signal is 0, then the output signal is 1.
25
AND Gate
An AND-gate is a circuit with two input signals and one output signal.
If both input signals are 1, the output signal is 1. Otherwise the
output signal is 0. Symbolic representation & Input/Output Table
26
OR Gate
An OR-gate is a circuit with two input signals and one output signal.
If both input signals are 0, then the output signal is 0. Otherwise,
the output signal is 1.
Symbolic representation & Input/Output Table
27
Combinational Logic Circuit
A Combinational Circuit is a compound circuit consisting of the basic
COMBINATIONAL
logic gates such as NOT, AND, OR. CIRCUIT:
28
Combinational Circuit: Example
Exercise
Determine the output for a given input:
Indicate the output of the circuit below when the input signals are P = 1,
Q = 0 and R = 0
29
Combinational Circuit: Example
Output S = 1
30
CLO1: Logical Equivalences, Tautology, Contradiction,
Predicates and Quantifiers
CIS 2203- Applied Discrete Math- Week 4
CONTENTS
• Logical Equivalence
• Tautology
• Contradiction
• Predicates
• Universal Quantifiers
• Existential Quantifier
• Rules of Inference
32
Logical Equivalence
33
Logical Equivalence: Example
34
Tautology
Tautology
Tautology: A tautology is a statement form that is always
true regardless of the truth values of the statement
variables. A tautology is represented by the symbol “t”.
35
Tautology: Example
Use truth table to show that ( p ∧q ) ∨(~ p ∨( p ∧~q )) is a tautology.
36
Contradiction
37
Contradiction: Example1
38
Contradiction: Example2
Use truth table to show that:
(p ∧~q)∧(~p∨q) is a contradiction.
39
Notes
Note
• Most statements are neither tautologies nor contradictions.
40
Logical Equivalence Involving Tautology
41
Logical Equivalence Involving Contradiction
LOGICAL EQUIVALENCE INVOLVING
CONTRADICTION
42
Propositional Functions
P(x) = x + 5 > x
variable predicate
43
Propositional Functions
Example :“x > 3”
Predicate “is greater than 3” refers to a property that the subject of the
statement :
• Can denote the statement by p(x) where p denotes the predicate “is greater
than 3” and x is the variable.
p(x): also called the value of the propositional function p at x .
Once a value is assigned to the variable x, p(x) becomes a proposition and has a
truth value 5
44
Propositional Functions
45
Propositional Functions
46
Propositional Functions
Propositional functions
Functions with multiple variables:
• P( x, y) is defined as x + y == 0
Then,
• P(1,2) is false,
• P(1,-1) is true
• P( x, y, z) is defined as x + y == z
Then,
• P(3,4,5) is false
• P(1,2,3) is true
47
Quantifiers
A quantifier is “an operator that limits the variables of a proposition”
•Two types:
• Universal ” ”. Express the extent to which a predicate is true .
• Existential “”. A predicate is true for there is one or more elements under consideration.
48
Universal Quantifiers
49
Universal Quantifiers
Universal quantifiers
50
Universal Quantifiers
51
Existential Quantifiers
Existential quantification
Represented by an backwards E: It means “there exists”
• Let P(x) = x+1 > x
•English translation: “there exists (a value of) x such that P(x) is true”
•English translation: “for at least one value of x, x+1>x is true”
52
Existential Quantifiers
Existential quantification
• Let P(x) = x+1 > x
• There is a numerical value for which x+1>x
• In fact, it’s true for all of the values of x!
• Thus, x P(x) is true
53
Existential Quantifiers
54
Comparison :Universal and Existential Quantifiers
55
Translation from English using Quantifiers
• Translate the statements:
• “All hummingbirds are richly colored”
• “No large birds live on honey”
• “Birds that do not live on honey are dull in color”
• “Hummingbirds are small”
• Assign our propositional functions
• Let P(x) be “x is a hummingbird”
• Let Q(x) be “x is large”
• Let R(x) be “x lives on honey”
• Let S(x) be “x is richly colored”
• Let our universe of discourse be all birds
56
Translation from English using Quantifiers
Translating from English
• Translate the statements:
• “All hummingbirds are richly colored”
• x (P(x)→S(x))
• “No large birds live on honey”
• ¬x (Q(x) R(x))
• Alternatively: x (¬Q(x) ¬R(x))
• “Birds that do not live on honey are dull in color”
• x (¬R(x) → ¬S(x))
• “Hummingbirds are small”
• x (P(x) → ¬Q(x))
57
Rules of Inference
• In logic, a rule of inference is a logical form consisting of a function
which takes premises, analyzes their syntax, and returns a conclusion
(or conclusions).
• For example, the rule of inference called modus ponens takes two
premises, one in the form "If p then q" and another in the form "p", and
returns the conclusion "q".
Example:
Suppose that the conditional statement “If it snows today, then we will
go skiing” and its hypothesis, “It is snowing today,” are true.
Then, by modus ponens, it follows that the conclusion of the conditional
statement, “We will go skiing,” is true.
58
CLO2: Algorithm
CIS 2203- Applied Discrete Math-Week 6
CONTENTS
• Algorithm definition
• Properties of Algorithms
• Write an Algorithm
• Algorithms VS Programming
• Simple Algorithms:
-Arithmetic Operations
-Minimum
-Maximum
60
What is an Algorithm
• Definition: An Algorithm is a well-defined, step-by-step procedure that allows a computer to solve a
problem.
• Algorithms are finite processes that if followed will solve the problem.
• Although there are many ways that algorithms can be compared, we will focus on two factors that are of
primary importance to many data processing algorithms:
Time complexity: how the number of steps required depends on the size of the input
Space complexity: how the amount of extra memory or storage required depends on the size of the input
61
Algorithm Example
Problem: Write the steps to make tea for two.
Algorithm:
1. Get a clean, empty tea pot
2. Fill the tea pot with 2 cups of water
3. Turn on the stove to high
4. Put the tea pot on the stove
5. Wait until water is boiling
6. Add two spoons of tea leaves into tea pot
7. Set heat of stove to Low
8. Keep on Low heat for 5 minutes
9. Turn off stove
10. Tea is ready!
62
Algorithm Example
Problem: Write the steps to make tea for two.
Algorithm:
1. Get a clean, empty tea pot
2. Fill the tea pot with 2 cups of water
3. Turn on the stove to high
4. Put the tea pot on the stove
5. Wait until water is boiling
6. Add two spoons of tea leaves into tea pot
7. Set heat of stove to Low
8. Keep on Low heat for 5 minutes
9. Turn off stove
10. Tea is ready!
63
Properties of Algorithm
There are several properties that algorithms generally share. They are useful to keep in mind when
algorithms are described. These properties are:
1. Input: an algorithm has input values from a specified set
2. Output: from each set of input values an algorithm produces output values from a specified set. The output values are the
solution to the problem
4. Correctness: an algorithm should produce the correct output values for each set of input values
5. Finiteness: an algorithm should produce the desired output after a finite (but perhaps large) number of steps for input in
the set
6. Effectiveness: it must be possible to perform each step of an algorithm exactly and in a finite amount of time
7. Generality: the procedure should be applicable for all problems of the desired form not just for a particular set of input
values.
64
Writing an algorithm:
The following keywords help to write an algorithm to solve
speci c problem. However there are some other words that
can replace these words.
Term Meaning Example
Get Input from keyboard Get name
Algorithm:
1. get two integers, x and y
2. calculate the result z by adding the two integers, x and y and store
result into variable z
3. Return z
66
Algorithm Vs Programming:
• What Is Programming?
• Programming is the process of taking an algorithm and encoding it into a notation, using a
programming language such as python so that it can be executed by a computer. Although
many programming languages and many different types of computers exist, the important
first step is the need to have the solution.
67
Algorithm Vs Programming:
An Example
Let’s look at a very simple algorithm called FindMax ().
Problem definition: Given a list of positive numbers, return the max number in the list.
68
Algorithm Vs Programming:
Find the max value in a list
Algorithm Programming (Python Code)
69
Example: Add two numbers
Algorithm Programming (Python code)
70
Example: Finding the minimum value in a list
Algorithms VS Programming
Algorithm Programming (Python code)
71
Find the Summation
Example: Finding the summation of a list of numbers
Write an algorithm that sums all elements in a list of integers. Name the function that implements this as
Summation. Note: Initialize the list to at least 10 elements, for example: listA = {2,4,6,8,10,12,14,16,18,20}
listA = {22,41,6,8,10,12,14,16,18,
20}
print (Summation(listA))
72
Exercises
1. Write an algorithm and a python code to find the average of a list of real numbers
2. Write an algorithm to find the factorial of an integer
Factorial of an integer n = n.(n-1).(n-2)…2.1
for example 5! = 5.4.3.2.1 = 120
3. Write an algorithm and a python code to find student grade according HCT grading
system.
73
CLO2: Searching Algorithms
CIS 2203- Applied Discrete Math-Week7
CONTENTS
76
Searching Algorithms
• Searching: Finding the position of a value within a list
• Problem: “Locate an element x in a list of distinct elements
a1, a2, …, an, or determine that it is not in the list.”
77
Linear Search Algorithm
• Linear (sequential) search: simply checks the items in sequence until the
desired item is found
• This technique iterates over the sequence, one item at a time, until the
specific item is found or all items have been examined.
78
Linear Search Algorithm
79
Python Code For Linear Search Algorithm
Returns True/False
80
Python Code For Linear Search Algorithm
Returns Index
81
Linear Search Complexity
The complexity of the linear (sequential) search is
Suppose you are doing a sequential search of the list [15, 18,2,19,18,0,8,14,19,14].
How many comparisons would you need to do in order to find the key 18 ?
1. 10
2. 5
3. 4
4. 2
Suppose you are doing a sequential search of the ordered list [3,5,6,8,11,12,14,15,
17,18].
How many comparisons would you need to do in order to find the key 13?
1. 10
2. 5
3. 7
4. 6
82
Binary Search Algorithm
• To reduce the time complexity, we can use the binary search instead of the linear
search.
• It is possible to take greater advantage of the ordered list if we are clever with our
comparisons.
• In the sequential search, when we compare against the rst item, there are at
most n−1 more items to look through if the rst item is not what we are looking
for.
• Instead of searching the list in sequence, a binary search will start by examining
the middle item. If that item is the one we are searching for, we are done. If it is
not the correct item, we can use the ordered nature of the list to eliminate half of
the remaining items.
83
Binary Search Algorithm
1. Get the list from the user.
2. Get the search element from the user.
3. Calculate the middle index
4. Compare the search element with the element in the middle index.
5. If both are matched, then return the element index and stop searching.
6. If both are not matched.
1. If the target value is greater than the number in the middle index, then pick sub list elements to the right
of the middle index, and start with Step 3
2. If the target value is less than the number in the middle index, then pick the sub list elements to the left of
the middle index, and start with Step 3.
7. Repeat steps 3, 4 and 5 until search element is compared with last element in the list.
8. If last element in the list also doesn't match, then return -1.
84
Binary Search Python code
Return True/False
85
Binary Search Python code
Return Index
86
Search Algorithm Exercises
Activity:
1. Linear Search
1. Write the linear search algorithm
2. Write python code for linear search that return True if the key is found, otherwise
return False.
3. Write python code for linear search that return the index if the key is found,
otherwise return -1.
Activity:
1. Binary Search
1. Write the binary search algorithm
2. Write python code for binary search that return True if the key is found, otherwise
return False.
3. Write python code for binary search that return the index if the key is found,
otherwise return -1.
87
CLO2: Sorting Algorithms
CIS 2203- Applied Discrete Math-Week8
CONTENTS
90
Sorting Algorithm
Given a list of values and a function that compares two values, order the values in the list from
smallest to largest.
The values might be integers, or strings or even other kinds of objects. We will examine two
algorithms:
• Selection sort, which relies on repeatedly selecting the next smallest item
• Insertion sort, which relies on removing entries one at a time and then insert each of them
into a sorted part (initially empty)
91
Selection Sort Algorithm
• 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.
• The smallest element is selected from the unsorted array and swapped with
the leftmost element, and that element becomes a part of the sorted array.
This process continues moving unsorted array boundary by one element to the
right.
92
Selection Sort Algorithm
- Push the Min to the beginning of the list
https://www.youtube.com/watch?v=GUDLRan2DWM
93
94
Selection Sort Python Code
Use the following demo to demonstrate the Selection sort process: https://visualgo.net/en/sorting
95
Insertion Sort Algorithm
https://www.youtube.com/watch?v=i-
96 SKeOcBwko
Insertion Sort Algorithm
Algorithm
1. Get a list
2. Pick the rst element in the unsorted list.
3. If the list has one element, terminate.
4. Pick next element
5. Compare with all elements in the sorted sub-list
6. Shift all the elements in the sorted sub-list that is greater than the value to be
sorted
7. Insert the value
8. Repeat until list is sorted
https://www.youtube.com/watch?v=i-
97 SKeOcBwko
Insertion Sort Algorithm
98
Insertion Sort Python Code
Use the following demo to demonstrate the Insertion sort process: https://visualgo.net/en/sorting
99
Sorting Algorithms Exercises
Selection sorting
1.Write an algorithm for selection sort.
Insertion sorting
1.Write an algorithm for Insertion sorting
10
0
Week 9- CLO3: Algorithm Analysis
102
CONTENTS
- Introduction
- Computational Time-complexity
- Running Time of algorithms- Best, Worst and Average Cases
- Counting operations of an Algorithm
- Asymptotic Analysis notation ( big O, big Ω, big ϴ)
- Growth rates of functions
- Time Complexity of an Algorithm
- Asymptotic Analysis( comparative Analysis)
10
3
Introduction
• In CLO2, we learnt about algorithms, including some for sorting and searching
operations.
• We further learnt that there can be more than one possible algorithm for solving a given
problem.
• How do we know which is the most efficient algorithm from several algorithms that
solve the same problem?
10
4
Computational Complexity of Algorithms
• How can the efficiency of an algorithm be analyzed?
1. By measuring the time used by a computer to solve a
problem using the algorithm, when input values are of a
specified size.
This is called Time Complexity.
10
6
How to measure Running Time of algorithms?
• Most algorithms transform input objects into output objects.
Sorting
• Best case running time is usually not useful as it ignores other situations.
10
8
Mathematically analyzing algorithms
• Then, we express the efficiency of the algorithm using growth functions and time-
complexity.
10
9
• De ne a set of primitive operations such as:
• Assigning an identi er to an object
• Determining the object associated with an identi er
• Performing an arithmetic operation (for example, adding two
numbers)
Counting Primitive Operations
• Comparing two numbers
• Accessing a single element of a Python list by index
• Calling a function (excluding operations executed within the
function)
• Returning from a function.
• Formally, a primitive operation corresponds to a low-level
instruction with an execution time that is constant.
11
0
• Instead of trying to determine the speci c execution time of each
primitive operation, we will
Counting simply count
Primitive how many primitive operations
Operations
are executed, and use this number n as a measure of the running time of
the algorithm.
• The implicit assumption of “operation count” is the running times of
different primitive operations will be fairly similar. Thus, the number, n, of
primitive operations an algorithm performs will be proportional to the
actual running time of that algorithm.
11
1
Primitive Operations
11
2
Counting the operations of an Algorithm
For the purpose of our course, the following primitive operations are not being
considered (in counting the number of operations):
• Indexing an array A[5] not counted
• Displaying output - print(x) not counted
• Function calling- FindMax(lst) not counted
• print(max) not counted
• Function declaration – def FindMax(lst) not counted
11
3
Counting Assignment Operations
11
5
Counting operations in if/else statement
11
6
Counting operations in if/else statement
11
7
Counting operations in a loop
• To count the operations of a loop, we must first determine how
many times a loop is executed.
• For example the loop defined below executes exactly 5 times
for i in range(5)
The loop starts with i = 0
The loop ends when i = 5
After each iteration the value of i increased by 1 i i
At each iteration the program checks if i < 5,
when the condition is true the program
<
enters the loop 5
when the condition is false, the program exits
the loop
The table shows the iterations of the loop.
0 0 True
11
A total of six comparisons are performed, 5 True, 1 False < (enter
8
Counting operations in a loop
• How many times does the loop comparison execute?
An easy way to calculate is :
(end – start) = number of times the comparison is
evaluated to true
+ 1 = comparison is evaluated to false. For example
For example, both the loops below execute 5i times
i true +
1 times false
<
for i in range(5) (5-0) + 1 7
for i in range (2,7) (7-2) + 1
2 2 True
11
< (enter
9
Counting operations in a loop
• In the example below the loop executes n times
for i in range(n)
The loop starts with i = 0 i i
The loop ends when i = n <
(end – start ) = how many times the comparison to enter
the loop is true (n – 0) = n times true n
+ 1 false comparison to exit the loop
Therefore, a total of (n +1) comparisons 0 0 True
are performed in the loop
< (enter
for i in range(n) (n + 1) n loop)
1 1 True
< (enter
12
0
Counting operations in a loop
• Consider the example below, lets determine how many
times each statement is executed
for i in range(n): n + 1
sum = sum + i n
count = count + 1 n
Since the comparison to enter the loop is true n number of times, each
statement with the loop is executed n times.
12
1
Counting the operations in a loop
def isPrime(number):
prime = true
for i in range(2,number):
if(number % i == 0):
prime = false
return prime
12
4
Counting the operations in a loop
def isPrime(number): 0
prime = true 1
for i in range(2,number): (n – 2) + 1
if(number % i == 0): (n – 2)
prime = false (n – 2)
return prime 0
12
5
f(n) = 3n - 4
Counting the operations in a loop
def isPrime(number):
for i in range(2,number):
if(number % i == 0):
return false
return true
12
6
Counting the operations in a loop
def isPrime(number): 0
for i in range(2,number): (n – 2) + 1
if(number % i == 0): (n – 2)
return false 0
return true 0
f(n) = 2n - 3
12
7
Counting the operations in a loop
def FindMax(lstNumbers):
max = numbers[0]
for n in lstNumbers:
if n > max:
maxn = n
return max
12
8
Counting the operations in a loop
def FindMax(lstNumbers): 0
max = numbers[0] 1
for n in lstNumbers: n +1
if n > max: n
max = n n
return max 0
12
9
f(n) = 3n + 2
Counting the operations in a loop
def twoConditionalLoops(n):
for i in range(0,n):
sum = sum + i;
for i in range(0,n):
count = count + 1;
13
0
Counting the operations in a loop
def twoConditionalLoops(n): 0
for i in range(0,n): n+1
sum = sum + i; n
for i in range(0,n): n+1
count = count + 1; n
0
13
1
f(n) = 4n + 2
Counting the operations in a loop
def twoNestedForLoops(n): 0
for i in range(0,n): n+1
sum = sum + i n
13
2 return sum 0
Counting the operations in a loop
def NestedWhileLoops(n):
i=0
sum = 0
while (i < n):
j=1
while (j < n):
sum = sum + i
13
3
Counting the operations in a loop
def NestedWhileLoops(n): 0
i=0 1
sum = 0 1
while (i < n): n+1
j=1 n
def FindMax(lstNumbers): 0
maxn = numbers[0] 1
for n in lstNumbers: n +1
if n > maxn: n
maxn = n n
return maxn
The time required for this algorithm is proportional to n
13
f(n) = 3n+2 0
5
Counting the operations of an Algorithm
Example : Let us re-visit the algorithm Max that returns the larger of two numbers
---------------------------------------------------------------
Total number of operations: 3
13
6
General Rules for Estimation of Running Times
Loops: The running time of a loop is at most the running time of the
statements inside of that loop times the number of iterations.
If/Else: Never more than the running time of the test plus the larger of
running times of S1 and S2.
13
7
Measuring Operations as a Function of Input Size
To capture the order of growth of an algorithm’s running time, we will
associate, with each algorithm, a function f (n) that characterizes the
number of primitive operations that are performed as a function of
the input size n.
13
8
Growth Rate of functions
• In all the examples so far, we have seen how algorithmic operations can be written in
terms of functions of n, i.e. f(n) where n is the input size.
• The function that grows the fastest represents the slowest algorithm
• ( because, as n grows, f(n) also grows and therefore the algorithm performance
becomes slower).
13
9
Algorithm Growth Rates
14
0
Chart for Growth Rates of some important functions
14
1
14
2
Commonly Used Terminology for Complexity of
Algorithms
14
3
14
4
The Seven Functions used in the analysis of algorithms
14
5
• Best-case analysis
• is used to describe the way an algorithm behaves under optimal
conditions.
• Average-case analysis
• quite challengingon the Worst-Case Input
Focusing
• requires to de ne a probability distribution on the set of inputs
• Worst-case analysis
• much easier
• requires only the ability to identify the worst-case input, which is
often simple
• typically leads to better algorithms
14
6
14
7
1
4
9
15
0
15
Time Complexity
The complexity of an algorithm is a measure of the amount of time and/or space required by
an algorithm for an input of a given size (n).
The commonly used notation for calculating the running time complexity of the
algorithm is as follows:
1. Big O notation: Big O is used to measure the performance or complexity of an
algorithm. In more mathematical term, it is the upper bound of the growth rate of a
function. if a function f(x) grows no faster than a function g(x), then f is said to be a
member of O(g).
2. Big Ω notation: The notation Ω(n) is the formal way to express the lower bound of an
algorithm's running time. It measures the best case time complexity or the best
amount of time an algorithm can possibly take to complete.
3. Big θ notation: The notation θ(n) is the formal way to express both the lower bound
and the upper bound of an algorithm's running time.
15
1
Asymptotic notation : big O
The complexity of an algorithm is a measure of the amount of time and/or space required by
an algorithm for an input of a given size (n).
15
2
Growth of functions
15
3
Growth of functions
15
4
Growth of functions
- Now let’s look at a graph of y = x2
C=1 C=2
1 5 2 4 When k > 1,
2 8 6 12 g(x)=x2 + x overtakes f(x)=x2 + 4
3 13 12 24
4 20 20 40 |f(x)| <= c |g(x)|
5 29 30 60 Where c=2
K>1
|f(x)| <= c |g(x)| F(x) is big O(g(x))
Where c=1
K>3
F(x) is big O(g(x))
15
7
Explain the de nition:
-Going back to our functions f(x)= X2+4 and g(x)=
X2+X from previous slide
- Let C = 1 and k = 4, then:
|(f(x)| ≤ C| g(x)|, x > k |f(x)| ≤ |g(x)|, for x > 4
So we can say that f(x) is Big-O of g(x)
15
8
15
9
Growth of functions
- Can we say, g(x) > f(x), for all values of x > 0?
- What about when 0 < x ≤ 4?
- What about when x > 4?
- What we can say is:
g(x) > f(x) for all values of x > 4 OR
f(x) < g(x) for all values of x > 4
- We write this mathematically as:
f(x) ≤ g(x) for x > 4
16
0
1
6
1
- What if we change g(x) to g(x)=x2
- For C = 1 and k >=1, we can no longer say |f(x)| ≤ |g(x)|
C =2
x Cg(x) f(x) Cg(x)
|f(x)| <= c |g(x)| when c=2 and
C=2 C =1 k>= 2
1 2 5 1 F(x) big O(g(x))
2 8 8 4
3 18 13 9
4 32 20 16 C =1
5 50 29 25 |f(x)| >= c |g(x)| when c=1 and
k>= 1
F(x) big omega g(x)
16
1
1
6
2
Big-O
- Plot of f(x)=X2+4 and 2g(x) =2x2
- 2g(x)
- f(x)
16
2
Asymptotic notation: Big-Omega Ω
16
3
let’s re-visit our f(x) and g(x) functions:
- f(x)= x2 + 4 and g(x) = x2
This time let C=1 and k >=1
|f(x)| ≥ C|g(x)| |f(x)| ≥ |g(x)|, for k >=1
This means f(x) is Big-Omega of g(x) or Ω(g(x))
16
4
x Cg(x) f(x) Cg(x)
C =1
C=2 C =1 |f(x)| >= c |g(x)| when c=1 and
1 2 5 1 k>= 1
F(x) big omega g(x)
2 8 8 4
3 18 13 9
4 32 20 16
5 50 29 25
16
5
Big-Omega
x Cg(x) f(x)
C =1
1 1 5
2 4 8
3 9 13
4 16 20
5 25 29
16
6
Asymptotic notation: Big-Theta (ϴ)
- Big-Theta notation (ϴ)
Let f and g be functions from the set of integers or
the set of real numbers.
We say that f(x) is ϴ(g(x)) if f (x) is O(g(x)) and f (x)
is Ω(g(x)).
16
7
1
6
8
Big-Theta
- Notice that values for C were different:
- For f(x) to be O(g(x)), C = 2 (ref. 14)
- For f(x) to be Ω(g(x)), C = 1 (ref. 14)
Since C can be different for Big-O and Big-Omega we can say for f(x) to be Big-Theta of
g(x)
C |g(x)| ≤ |f(x)| ≤ C |g(x)|
1 2
16
8
Big-Theta
- 2g(x)
- g(x)
- f(x)
16
9
1
7
0
Big-Theta
17
0
Asymptotic Analysis
Comparative Analysis
17
1
Comparative Analysis
17
2
Comparative Analysis
17
3
Asymptotic Analysis
Examples of Algorithm Analysis
17
4
Constant-Time
Operations
Example
Given an instance, named data, of the Python list class, a call to
the function, len(data), is evaluated in constant time.
This is a very simple algorithm because the list class maintains, for
each list, an instance variable that records the current length of the
list.
17
5
Constant-Time
Operations
Example
The expression data[j] is evaluated in O(1) time for a Python list.
Because Python’s lists are implemented as “array-based sequences”,
references to a list’s elements are stored in a consecutive block of
memory. The jth element of the list can be found, not by iterating
through the list one element at a time, but by validating the index, and
using it as an offset into the underlying array. In turn, computer
hardware supports constant-time access to an element based on its
memory address.
17
6
Linear-Time
Operations
the Problem of Finding the Maximum of a
Sequence
def nd_ max ( data ): """ Return
the maximum Python list . """ element from a nonempty
biggest = data [0]
for val in data : if val >
biggest biggest = val
return biggest
17
8
Prefix Average: Quadratic-Time
Algorithm
18
0
Prefix Average: A Linear-Time
Algorithm
18
1
Three-Way Set
Disjointness
18
2
Three-Way Set
Disjointness
def disjoint 1 ( A, B, C): """ Return
True if there to all three lists . """ is no element common
for a in A:
for b in B: for c in C:
if a == b == c: return
False
return True
If each of the original sets has size n, then the worst-case running time
of this function is O(n3).
18
3
Three-Way Set
Disjointness
def disjoint 2 ( A, B, C): """ Return
True if there to all three lists . """ is no element common
for a in A:
for b in B: if a == b:
for c in C: if a == c
return False
return True
18
4
Element Uniqueness
18
5
Element
Uniqueness
18
6
Element
Uniqueness
18
7
CLO4-Graphs
CIS 2203- Applied Discrete Math- Week 11
CONTENT 12. The Travelling Salesman Problems
1. Graphs - Defini on 13. Graph Coloring and Chroma c
2. Some Graph Models Numbers
3. Graph Terminology
4. Graph Connec vity
5. Types of Graphs
6. Special Types of Simple Graphs
7. Applica ons of Special Simple Graphs
8. Represen ng Graphs
9. Paths and Connec vity
10. Weighted Graphs and Shortest Path
Algorithms
11. Applica ons of Shortest Path Problems
19
0
–
1. Graphs Defini on
• A graph is a set of points, called nodes or vertices, which are
interconnected by a set of lines called edges.
• The study of graphs, or graph theory is an important part of a number
of disciplines in the fields of mathematics, engineering and computer
science.
19
1
1. Graphs - Definition
19
3
3. Graph Terminology
•If e = {u, v}, the edge e is called incident with the vertices u and v.
•The edge e is also said to connect u and v.
•The degree of a vertex in an undirected graph is the number of edges incident with it
and is denoted by deg(v). (In other words, you can determine the degree of a vertex in a displayed graph by counting the
lines that touch it.)
19
4
Example 1: Consider the following graph (unconnected) 3. Is there a pendant vertex in this graph?
:
Example 2 :
4. Which is the isolated vertex in this graph?
1. Write the vertex set and the edge set for the graph.
Solution:
a. Vertex set={v1,v2,v3,v4,v5,v6} 5. What is the neighbourhood of vertex v1?
b. edge set = {e1, e2, e3, e4, e5, e6, e7} Solution:
N(v1) = {v2, v3 }
2. Write the degrees of the vertices.
Solution:
deg(v1) = deg(v3) = 3 deg(v2) = 2
deg(v5) = deg(v6) = 3
19
5
Example 2: Which vertices in the following graph are isolated, which
are pendant, and what is the maximum degree (g) ?
f h
a d
e
g
b c f j
Solu on: Vertex f is isolated, and ver ces a, d and j are pendant. The
maximum degree is deg(g) = 5.
19
6
4. Graph Connectivity • A directed graph is strongly connected if
• A directed graph ( or digraph) is a set there is a path from every node to every
of vertices connected by edges, with each node other node
having a direction associated with it.
19
7
Examples for Graph Connectivity
3.Connectivity …
Are the following directed graphs strongly or weakly connected?
19
8
3. Connectivity...
Examples for Graph Connectivity
Example: Are the following graphs connected?
a b a
b
e e
d
d c
c
Yes. No.
a b a
b
e d e
c
d f
c
Yes. No.
19
9
5. Types of Graphs
A Simple graph is one in which each edge connects two different vertices and no two
edges connect the same pair of vertices.
A simple directed graph has no loops and no multiple edges
Example: Adjoining figure is a directed graph with three vertices
and three edges.
20
0
5. Types of Graphs
Undirected graphs that may include loops, as well as multiple edges connecting the
same pair of vertices are called pseudographs .
An edge that connects a vertex to itself is called a loop.
Example:
The adjoining pseudograph has both multiple edges and a loop.
20
1
Table: Types of Graphs
20
2
6. Special Types of Simple Graphs
2.3.Complete
• A complete graph on n vertices, denoted byand Bipartite graphs:
K is a simple graph that contains exactly one
n
displayed in the figure below. A simple graph for which there is at least one pair of distinct vertex not connected by
an edge is called non-complete.
• A bipartite graph is one whose vertex set V can be partitioned into two disjoint
subsets V and V such that every edge
1 2
V.
2
In the above figure, the graphs K ,K andK are not bipartite while, graphs K ,K andK are bipartite.
1 3 5 2 4 6
20
3
7. Some applications of special types of Graphs
• Bipartite graphs can be used to model many types of applications that
involve matching the elements of one set to elements of another, as in
matching job assignments to employees.
• Local Area Networks The various computers in a building, such as
minicomputers and personal computers, as well as peripheral devices
such as printers and plotters, can be connected using a local area
network.
• A local area network can be represented using a complete bipartite
graph K1,n, as shown in the figure (a) or in other ways as in figures b
and c.
20
4
Examples for Bipartite Graphs
Example 1: Is C3 bipartite?
v1 No, because there is no way to par on the ver ces into two
sets so that there are no edges with both endpoints in the same
set.
v2 v3
Example 2: Is C6 bipar te?
g
c e
b
f
f d d
g
e
G Yes !
20
6
CLO4-Graphs
CIS 2203- Applied Discrete Math- Week 12
8. Representing Graphs
The following ways can be used to represent a graph:
a. Adjacency List
b. Adjacency Matrix
c. Incidence Matrix
20
8
A. Adjacency Lists
Definition: An adjacency list can be used to represent a graph with no multiple edges by specifying
the vertices that are adjacent to each vertex of the graph.
Example 1:
Example 2:
20
9
B. The adjacency matrix
•Definition: Let G = (V, E) be a simple graph with |V| = n.
Suppose that the vertices of G are listed in arbitrary order as v1, v2, …, vn.
•The adjacency matrix A (or AG) of G, with respect to this listing of the vertices, is the nn
zero-one matrix with 1 as its (i, j)th entry when vi and vj are adjacent, and 0 otherwise.
21
0
B. Adjacency matrix:
21
1
B. Adjacency matrix:
Example Example
2: 3:
21
2
B. Adjacency matrix:
21
3
C. Incidence matrix
Definition: Let G = (V, E) be an undirected graph with |V| = n.
Suppose that the vertices and edges of G are listed in arbitrary order as v1, v2, …,
vn and e1, e2, …, em, respectively.
•The incidence matrix of G with respect to this listing of the vertices and edges is
the nm zero-one matrix with 1 as its (i, j)th entry when edge ej is incident with vi,
and 0 otherwise.
In other words, for an incidence matrix M = [mij],
mij = 1 if edge ej is incident with vi
mij = 0 otherwise.
21
4
C. Incidence matrix
Example 1: What is the incidence matrix M for
the following graph G based on the order of
2
a 1
vertices a, b, c, d and edges 1, 2, 3, 4, 5, 6? b
Solution:
d 3 5
4 c
1 1 0 0 1 0
1 0 1 0 0 0 6
M
0 0 0 1 1 1
0 1 1 1 0 0
Note: Incidence matrices of directed graphs contain two 1s per column for edges connec ng two
ver ces and one 1 per column for loops.
21
5
9. Paths and connectivity
• A path is a sequence of edges that begins at a vertex of a graph and travels
from vertex to vertex along the edges of the graph.
1)A path is simple if it does not contain the same edge more than once.
2)The path is a circuit if it begins and ends at the same vertex, that is, if u = v .
Applications of paths:
• Determining whether a message can be sent between two computers.
• Efficiently planning routes for mail delivery, garbage pickup, diagnostics in computer
networks
21
6
6. Paths and connectivity
Example: In the simple graph here:
21
7
10. Weighted Graphs and Shortest Path Algorithms
• Many problems can be modeled using graphs with weights assigned to
their edges.
• For example, an airline system graph model where cities are represented
by vertices, flights by edges and distances between edges are weights on
the edges.
• Graphs that have a number assigned to each edge are called weighted
graphs.
21
8
10. Weighted Graphs and Shortest Path Algorithms
• Shortest path: The shortest path length between two vertices i and j is the number
of edges comprising the shortest path (or a shortest path) between i and j.
• The length of a path in a weighted graph is the sum of the weights of the edges of
this path.
• Shortest path Problem: Determining the path of least sum of the weights between
two vertices in a weighted graph
• There are several different algorithms that find a shortest path between two
vertices in a weighted graph including brute force algorithms ( where all
possibilities are tried to reach the solution).
• The greedy algorithm Dijkstra’s algorithm is a popular one for shortest path
problems.
21
9
10. Weighted Graphs and Shortest Path Algorithms
22
0
10. Weighted Graphs and Shortest Path Algorithms
Example 2: Path between 1 and 8
22
1
10. Weighted Graphs and Shortest Path Algorithms
Example of No Path
22
2
Shortest Path using Dijkstra’s algorithm
Simple steps for Dijkstra’s algorithm:
1) Label the start vertex as 0.
2) Box this number (permanent label).
3) Label each vertex that is connected to the start vertex with its
distance (temporary label).
4) Box the smallest number.
5) From this vertex, consider the distance to each connected vertex.
6) If a distance is less than a distance already at this vertex, cross out
this distance and write in the new distance.
7) If there was no distance at the vertex, write down the new distance.
8) Repeat from step 4 until the destination vertex is boxed.
22
3
Shortest Path using Dijkstra’s algorithm
Example 1. How can we use Dijkstra’s algorithm to determine the shortest path?
Solu on:
1. Label vertex a as 0 and box it.
2. Label neighbors of a, the ver ces b and d with
4 and 2 respec vely.
3. Box the vertex d with 2 [as d is the shortest from above step]
4. Label vertex e( neighbor of d) with 5 [This is shorter than the length of a + b]
5. Label neighbor of b, the vertex c with 7 (4 +3).
6. Box the vertex c with 7.
7. Label the neighbor of e, the vertex z with 6( 5+ 1). This is shorter than the length
of 9 obtained from vertex c (7 +2).
8. Therefore the shortest length is 6 and retracing the path for this length, gives the
shortest path from a to z, which is a-d-e-z. a
2 d 3 e1 z
22
L=6
4
Shortest Path using Dijkstra’s algorithm
Example 2. How can we use Dijkstra’s algorithm to determine the shortest path star ng from the
end-point?
Solu on : Fig.1
4. From D, the connected ver ces are B and C. The distances at these ver ces are 9 at B (4 +5) and
5 at C (4 +1). [We have taken the shorter distance at C- i.e. instead of 6 we have E-D-C as 5]
Fig.3
5. Cross out the 6 at C and replace with 5. Box the 5 at C. See Fig. 3
22
5
Shortest Path using Dijkstra’s algorithm
Solu on con nued :
6. From C the connected ver ces are B and A. The distances are 8 at B(5 +3) and 14 at
A(5+9).
7. Cross out the 9 at B and replace with 8. Box the 8 at B. See Fig:4. Fig.4
Toronto
650
700 Boston
Chicago
600 200
New York
22
7
12. The Traveling Salesman Problem
The traveling salesman problem is one of the classical problems in computer science.
•A traveling salesman wants to visit a number of cities and then return to his starting point.
Of course he wants to save time and energy, so he wants to determine the shortest path
for his trip.
We can represent the cities and the distances between them by a weighted, complete,
undirected graph.
•The problem then is to find the circuit of minimum total weight that visits each vertex
exactly one.
•There is no polynomial time algorithm to solve the Travelling salesman problem.
•Brute force algorithms can be used to solve TSP if the number of vertices are less.
• A practical approach to the traveling salesperson problem when there are many vertices
to visit is to use an approximation algorithm.
• These are algorithms that do not necessarily produce the exact solution to the problem
but instead are guaranteed to produce a solution that is close to an exact solution.
22
8
13. Graph Coloring and Chromatic Number
• A coloring of a simple graph is the assignment of a color to each
vertex of the graph so that no two adjacent vertices are assigned
the same color.
• The objective is to minimize the number of colors while coloring a
graph.
• The smallest number of colors required to color a graph G is
called the chromatic number of that graph.
• For example in the adjoining graph, the chromatic number
is at least 3, as three colors have been used to color the
graph.
22
9
13. Graph Coloring and Chromatic Number
• THE FOUR COLOR THEOREM
The chromatic number of a planar graph is no greater than four.
(A graph is called planar if it can be drawn in the plane without any edges crossing)
Example: What is the chromatic number of graph G?
23
0
12. Graph Coloring and Chromatic Number
Example 1: What are the chromatic numbers of the graphs
G and H?
Sol: Sol:
Chromatic number of H is
Chromatic number of G is at least 4
at least 3
23
1
Applications of Graph Colorings
Scheduling
Frequency assignments
Pattern matching
Map Coloring
23
2