COS 102 Compiled
COS 102 Compiled
di★
n
Dr Isaac Olúwafé.mi E.lé.sè.moyò.
u
x M
O u . wò. University, Ilé.-Ifè.
. báfé.mi Awóló
L
★
June 2, 2026
Problems
2/23
Traffic congestion in a busy city like Lagos: Vehicles waste time
and fuel at junctions. A computer system could use sensors and
algorithms to adjust traffic lights dynamically.
di★
n
x Mu
★ Lu
Figure:
3/23
Real-World Domains
di★
n
x Mu
★ Lu
Environment: Inefficient waste management or high energy
consumption in cities.
4/23
How to identify problems
5/23
Problem Definition and Analysis
i★
▶ Define the goal — What should the desired outcome be?
d
n
▶ List constraints — Time, budget, hardware limits, rules.
x Mu
▶ Break it down (decomposition) — Divide into
★ Lu
sub-problems (e.g., input, processing, output).
▶ Identify inputs and outputs — What data goes in? What
result comes out?
▶ Consider edge cases — What happens with unusual inputs
(empty list, very large numbers)?
▶ Model it — Use diagrams, flowcharts, or simple math.
6/23
Example: Cook Noodles
▶ Current state: You are hungry and have no prepared food.
▶ Goal: To have a bowl of fully cooked, seasoned, and
safe-to-eat noodles ready for consumption within the allotted
time.
i★
▶ Inputs: 1 pack of instant noodles, 500ml of water, seasoning
d
packets, A pot or heat-safe bowl, a stove or electric kettle, a
n
Mu
fork/spoon, Electricity or gas for heating, Cooking
x
instructions.
★ Lu
▶ Output: A hot, edible meal.
▶ Analysis:
▶ Heat water until it reaches the boiling point (100°C).
▶ Submerge noodles in boiling [Link] for the chemical
change (hydration/softening) to occur.
▶ Drain excess water and
▶ add seasoning.
7/23
Example: Build a simple calculator for two numbers
8/23
Designing a student attendance system
9/23
Characteristics of Well-Defined Problems
i★
A well-defined problem has clear starting conditions, a clear goal,
d
n
and known rules or operations to reach the solution. It usually has
Mu
one (or a verifiable) correct answer and follows structured steps
x
called algorithm.
★ Lu
10/23
Key characteristics
11/23
Examples of well-defined problems
12/23
Well-defined vs. Ill-defined (poorly defined) problems
i★
Goal Clear (e.g., "sort list A to Z") Vague (e.g., "make the app
Verifiability
L
★ correctness
Easy to check
gle "correct" way
Subjective or hard to measure
13/23
Ill-Defined Example - Improve traffic in Lagos - too broad.
i★
Well-defined version: "Given current traffic data from 50 junctions,
d
n
minimize average waiting time by adjusting signal timings every 5
minutes."
x Mu
★ Lu
14/23
Introduction to Solvable vs. Unsolvable Problems
15/23
Solvable examples
16/23
Unsolvable problems
i★
(finish) or run forever (infinite loop)?
d
n
x Mu
★ Lu
No general algorithm can solve this for all possible programs and
inputs.
17/23
Some unsolvable problems are not unsolvable, they are simply non
computable.
di★
u n
x M
★
limL3xu2 + 5x − 4 =
3
x →∞ 2x 2 −x +1 2
18/23
▶ Some programs clearly halt (print "Hello" and stop).
▶ Some clearly loop forever (while true: print "loop").
di★
▶ But for arbitrary programs, we cannot always predict without
n
Mu
running them — and running them might take forever if they
x
loop!
★ Lu
19/23
Introduction to Computational Complexity Basics
Even among solvable problems, some are easy (fast) and some are
extremely hard (take too much time even on supercomputers).
Computational Complexity studies how the running time or
resources grow as the input size (n) increases. Polynomial time
di★
n
x Mu
Lu
(P): Problems solvable quickly — time grows like n, n2, n3, etc.
★
(practical for large n).
20/23
NP (Nondeterministic Polynomial): Problems where a proposed
solution can be verified quickly (in polynomial time), but finding
the solution may be very hard. Example: Sudoku — checking if a
di★
n
x Mu
★ Lu
filled grid is correct is fast, but solving a hard puzzle by
trial-and-error can take enormous time.
21/23
P vs NP question
22/23
Everyday analogy
di★
n
x Mu
u 20 cities exactly once (Traveling
Finding the shortest routeLvisiting
★
Salesman Problem) — guessing a route is easy to check, but
finding the best one is hard for large numbers.
23/23
Problem-Solving Methods
di★
n
Isaac O. Elesemoyo
x Mu
★ Lu
June 2, 2026
Outlines
Algorithm
Actions in Algorithms
di★
n
x Mu
★ Lu
Four Fundamental Characteristics
i★
sub-problems once and store results. Examples: Knapsack
Problem, Fibonacci, Bellman-Ford.
n d
Mu
▶ Greedy Algorithms — Make the locally optimal choice at each
x
★ Lu
step hoping to reach a global optimum. Examples: Dijkstra’s
shortest path, Huffman coding, Kruskal’s MST.
▶ Backtracking — Incrementally build a solution and abandon
(‘backtrack’) partial solutions that fail constraints. Examples:
N-Queens, Sudoku solver, graph colouring.
▶ Brute Force / Exhaustive Search — Try all possible solutions.
Guaranteed optimal but prohibitively slow for large inputs.
▶ Graph Algorithms — BFS, DFS, A*, Prim’s. Fundamental for
navigation, networking, and AI planning.
Heuristics
What is a Heuristic?
di★
A heuristic (from Greek ‘heuriskein’ — to discover) is a practical,
n
x Mu
experience-based technique that finds a good-enough solution
quickly, without the guarantee of optimality. Heuristics trade
★ Lu
mathematical certainty for computational speed.
Key Characteristics of Heuristics
di★
Salesman Problem (TSP), vehicle routing, protein folding,
job-shop scheduling. For a 50-city TSP instance, an exhaustive
n
Mu
search would require evaluating approximately 3 × 102 routes -
x
★ Lu
more than the number of atoms in the observable universe. No
computer could solve this exactly in any reasonable timeframe.
Heuristics make such problems tractable.
Classic Heuristic Examples
Scalability
instances
★ Lu
Poor for very large NP-hard Excellent for large-scale prob-
problems lems
Predictability Deterministic and repeatable Can be stochastic or variable
Resource Us- High memory/time for com- Lower resource requirements
age plex problems
Use Case Well-structured, smaller prob- Ill-structured, time-critical
lems problems
Examples Linear Programming, exact Genetic Algorithms, Simu-
TSP solvers lated Annealing
Overview
1. Linear Search
2. Binary Search
3. Bubble Sort
4. Factorial (Iterative) di★
n
5. Fibonacci Sequence
x Mu
6. Check Palindrome
★ Lu
7. Find Maximum
8. Reverse Array
9. Selection Sort
10. Insertion Sort
Linear Search: Textual Algorithm
Algorithm 1 LinearSearch(A, x)
di★
for i ← 0 to n − 1 do n
if A[i] = x then
x Mu
return i
★ Lu
end if
end for
return −1
Binary Search: Textual Algorithm
1. Set the lower bound to the first index and the upper bound to
the last index.
i★
2. While the lower bound is not greater than the upper bound:
d
n
Mu
2.1 Compute the middle index.
x
2.2 If the middle element equals the target, return its index.
half. ★ Lu
2.3 If the middle element is less than the target, search the right
Algorithm 2 BinarySearch(A, x)
low ← 0, high ← n − 1
while low ≤ high do
mid ← ⌊(low + high)/2⌋
di★
if A[mid] = x then n
return mid x Mu
Lu
else if A[mid] < x then
★
low ← mid + 1
else
high ← mid - 1
end if
end while
return −1
Bubble Sort: Textual Algorithm
Algorithm 3 BubbleSort(A)
for i ← 0 to n − 2 do
di★
for j ← 0 to n − i − 2 do n
x Mu
if A[j] > A[j + 1] then
Lu
swap A[j] ↔ A[j + 1]
★
end if
end for
end for
Factorial: Textual Algorithm
Algorithm 4 Factorial(n)
if n = 0 then
return 1 di★
n
end if
x Mu
result ← 1
for i ← 1 to n do ★ Lu
result ← result ×i
end for
return result
Fibonacci Sequence: Textual Algorithm
1. If n is 0 or 1, return n.
2. Initialize two variables:
▶ a=0
di★
▶ b=1 n
x Mu
3. Repeatedly compute the next Fibonacci number as a + b.
L u
4. ★
Update a and b accordingly.
5. Continue until the n-th Fibonacci number is obtained.
6. Return the final value.
5. Fibonacci Sequence
Algorithm 5 Fibonacci(n)
if n ≤ 1 then
return n
di★
end if n
a ← 0, b ← 1
x Mu
for i ← 2 to n do
temp ← a + b ★ Lu
a←b
b ← temp
end for
return b
Check Palindrome: Textual Algorithm
Algorithm 6 IsPalindrome(S)
left ← 0, right ← length(S) - 1
while left < right do
di★
n
Mu
if S[left] ̸= S[right] then
return false x
end if
★ Lu
left ← left + 1
right ← right - 1
end while
return true
Find Maximum: Textual Algorithm
Algorithm 7 FindMax(A)
max ← A[0]
di★
for i ← 1 to n − 1 do n
if A[i] > max then x Mu
max ← A[i]
★ Lu
end if
end for
return max
Reverse Array: Textual Algorithm
Algorithm 8 ReverseArray(A)
left ← 0, right ← n − 1 di★
n
while left < right do
x Mu
swap A[left] ↔ A[right]
left ← left + 1★ Lu
right ← right - 1
end while
Selection Sort: Textual Algorithm
Algorithm 9 SelectionSort(A)
for i ← 0 to n − 2 do
minIndex ← i
di★
n
Mu
for j ← i + 1 to n − 1 do
x
if A[j] < A[minIndex] then
Lu
minIndex ← j
★
end if
end for
swap A[i] ↔ A[minIndex]
end for
Insertion Sort: Textual Algorithm
Algorithm 10 InsertionSort(A)
for i ← 1 to n − 1 do
key ← A[i]
di★
n
Mu
j ←i −1
x
while j ≥ 0 and A[j] > key do
A[j + 1] ← A[j]
★ Lu
j ←j −1
end while
A[j + 1] ← key
end for
What is a Flowchart?
i★
▶ Visual representation of an algorithm or process
n d
▶ Uses standardized shapes connected by arrows
Mu
▶ Helps in planning, debugging, and explaining logic
x
Lu
▶ Independent of any programming language
★
Common Flowchart Symbols
Start / End
Oval/Terminator
Process Step
Rectangle
di★
n
x Mu
Lu
★Decision?
Diamond
Parallelogram
Flowchart Symbols & Their Meanings
Shape Purpose
Oval / Terminator i★
Start or End of the program
d
Rectangle n
Processing / Calculation step
Diamond x Mu
Decision (Yes/No question)
Parallelogram
★ Lu Input or Output
Arrow Direction of flow
Example 1: Check Even or Odd Number
Start
Read Number n
di★
n
x Mu
★ Lun mod 2 = 0?
Yes No
End
Example 2: Find Maximum of Two Numbers
Start
Read A and B
di★
n
x Mu Is A > B?
★ Lu
Yes No
Max = A Max = B
Print Max
End
Best Practices for Flowcharts
Problem: Find a short route that visits every city exactly once and
returns to the starting city.
Textual Algorithm
1. Choose a starting city. di★
n
2. Mark the city as visited.
x Mu
3. L u city.
Find the nearest unvisited
4. Move to that city ★
and mark it as visited.
5. Repeat until all cities have been visited.
6. Return to the starting city.
Travelling Salesman Problem (Nearest Neighbor)
Algorithm 11 NearestNeighborTSP
current ← startCity
mark current as visited
di★
while unvisited cities exist do n
Mu
next ← nearest unvisited city
x
visit next
current ← next ★ Lu
end while
return to startCity
Knapsack Problem (Greedy Heuristic)
Algorithm 12 GreedyKnapsack
Sort items by value/weight ratio
for each item do
di★
if item fits in knapsack then n
add item
x Mu
Lu
update remaining capacity
★
end if
end for
return selected items
Knapsack Problem
Problem:
You have a knapsack that can carry at most 15 kg.
The available items are:
Item Weight (kg)
d i★ ($)
Value
n 40
Mu
A 2
B x3 50
C
★Lu 5 100
D 4 60
E 6 120
Algorithm 14 LargestDegreeColoring
Sort vertices by degree
di★
for each vertex do n
x Mu
Assign lowest valid color
end for
★ Lu
return coloring
Job Scheduling (SPT Heuristic)
Algorithm 15 ShortestProcessingTime
Sort jobs by processing time
di★
n
Mu
for each job do
schedule job x
end for
★ Lu
return schedule
Route Finding (A* Search)
i★
1. Place the start node in the open list.
d
2. unestimated cost.
Select the node with the lowest
M
3.
ux
Expand its neighboring nodes.
L
4. ★ and heuristic estimate.
Compute actual cost
5. Update the best path information.
6. Repeat until the goal node is reached.
Route Finding (A* Search)
Algorithm 16 AStar
add start node to OpenList
while OpenList is not empty do
current ← node with lowest f-cost
if current = goal then
di★
return path n
end if
x Mu
Lu
for each neighbor do
★
update path cost
compute heuristic estimate
add neighbor if necessary
end for
end while
return failure
Thank You!
di★
n
Mu
Questions?
x
★Lu
Analogies: Definition, Structure, and Use
COS 102 lecture notes, reorganized and lightly expanded
1. What Is an Analogy?
An analogy is a comparison between two different things, based on shared similarities, used to explain or clarify a concept. It
maps a familiar idea (the source) onto an unfamiliar one (the target) so the structure of the familiar idea carries over.
Example: "The brain is like a computer" — this helps people reason about how the brain stores and processes information by
borrowing the logic of a system they already understand.
Note: An analogy is a reasoning tool, not a proof. It transfers plausibility from the source domain to the target domain;
it does not establish that the target domain actually works the same way. Treat conclusions drawn purely from analogy
as hypotheses to verify, not settled facts.
3. Structure of an Analogy
• Source domain: the familiar concept.
• Target domain: the concept being explained.
• The mapping: connects features of the source to corresponding features of the target.
Worked example: "An atom is like a solar system."
Third example — Source vs. Target domain: "Computer memory is like a library."
Analogy Metaphor
Function Explains similarities in detail (tool for States one thing is another, for effect
reasoning) (figure of speech)
Purpose Used for understanding Used mainly for expression
Nature Logical comparison Figurative comparison
8. Analogical Reasoning
Analogical reasoning is the process of drawing conclusions based on similarities. It follows a general pattern: A is related to
B; C is related to what?
Example: Doctor : Hospital :: Teacher : ? → Answer: School.
Reasoning: a doctor works in a hospital just as a teacher works in a school — the underlying relation ("works in") is held
constant while the terms change.
Note: This is the same logical form used in verbal analogy questions (Section 5.4) and in IQ/aptitude testing. Formally:
if relation R holds between A and B, and the same relation R plausibly holds between C and an unknown D, analogical
reasoning proposes D as the term that completes it. The reasoning is only as strong as the claim that R genuinely
transfers from (A,B) to (C,D).
9.2 Science
• Electric current = Water flow.
• DNA = Blueprint.
12. Advantages
• Easier learning: makes difficult ideas understandable.
• Better retention: people remember familiar comparisons.
• Creative thinking: helps generate new ideas.
• Knowledge transfer: the ability to take understanding from one familiar situation and apply it to a new, unfamiliar
one.
13. Limitations
• Oversimplification: many analogies ignore important details.
• Incomplete comparison: an analogy usually highlights only some aspects of a concept.
• Potential misconceptions: two things may appear similar but differ significantly.
Note: Sections 11 and 13 overlap: Over-Complication and Cultural Misalignment are failure modes in how an analogy
is deployed, while Oversimplification and Incomplete Comparison are structural limits of analogy as a reasoning
method — even a well-chosen analogy will hide some of the target's real behavior.
14. Summary
• Analogies connect familiar ideas with unfamiliar concepts, making learning clearer and more effective.
• Analogies are "cognitive bridges" between the known and the unknown.
• They are powerful tools for teaching, persuasion, and innovation.
• Rule of thumb: use familiar examples, keep it simple, and make sure the underlying logic actually holds.
Comprehensive Guide to Analogical
Reasoning
Structure, Classifications, and Domain Applications
1. Introduction to Analogy
An analogy is a powerful cognitive tool and linguistic device that establishes a comparison between two
different things based on their underlying similarities. Its primary function is to explain, clarify, or conceptualize
an unfamiliar idea by mapping it onto a familiar one.
Analogies serve as foundational pillars across multiple domains of human intellect and expression, including
teaching, learning, professional communication, structured problem-solving, and scientific discovery.
Stores data: Hard drives, solid-state media, and Store memories: Neural networks and synaptic
RAM hold digital information systematically. connections encode and preserve experiences.
Processes information: The Central Processing Unit Processes thoughts: The cerebral cortex actively
(CPU) executes logical operations and computations. integrates cognitive tasks, reason, and analytics.
Has input devices: Keyboards, mice, and sensors Receive sensory input: Eyes, ears, skin, and other
receive telemetry and commands. sensory organs gather environmental data.
Produces output: Monitors, speakers, and printers Produces actions: Motor commands result in
deliver processed data visually or physically. physical movement, speech, and behavioral
responses.
To construct or evaluate an analogy rigorously, it must be broken down into three essential components:
• Source Domain: The familiar concept or system that acts as the baseline reference point.
• Target Domain: The novel or complex concept currently being examined or explained.
Structural Case Study: Rutherford-Bohr Model (An Atom is like a Solar System)
Sun located at the absolute center Nucleus located at the absolute center
Planets orbit continuously around the sun via Electrons orbit continuously around the nucleus via
gravitational pull electrostatic forces
3. Analogical Reasoning
Analogical reasoning is the specific cognitive process through which logical conclusions are systematically
drawn based on identified similarities between relational networks.
This is often mathematically and textually represented as: A : B :: C : D (read as "A is to B as C is to D").
Reasoning: The relationship established in the first pair is [Professional] : [Primary Workplace]. A doctor
works inside a hospital; applying this exact relational logic to the target domain dictates that a teacher
works inside a school.
Analogies are categorized into distinct structural frameworks depending on how the comparison is structured
and expressed.
Extended Analogy Develops and sustains multiple overlapping Simple Extended, Allegory
points of complex structural comparison
throughout a narrative.
Literal Analogy Compares entities that belong natively to the Antonyms, Opposites, Object-
exact same categorical class. and-Classification
Source to Product "A sculptor molds their clay similarly Highlights the exact operational
to how a baker kneads their dough." relationship between a skilled artisan,
their unformed raw material, and the final
tangible asset generated through
disciplined manual effort.
Antonyms "The weather went from hot to cold Hot and cold are polar opposites along a
as quickly as an elevator goes up linear temperature scale, directly mirroring
and down." how up and down represent opposing
physical directions along a vertical axis.
5.1 Mathematics
• Number Line = Straight Road: Visualizes values as discrete physical milestones along a uniform,
continuous linear path.
• Equation = Balanced Scale: Reinforces the requirement that any mathematical modification executed on
one side must be perfectly mirrored on the other to preserve equilibrium (LHS = RHS).
• Electric Current = Water Flow: Voltage acts as water pressure, current as the volumetric flow rate of
water, and resistors function like narrow constrictions inside a pipe.
• DNA = Blueprint: Conceptualizes deoxyribonucleic acid not simply as chemical bases, but as a dense,
structured master architectural plan containing all necessary instructional specifications for building an
organism.
• Database = Filing Cabinet: Represents tables, indices, and keys as structured drawers, folders, and
indexed files.
• Internet = Postal System: Equates data packets to addressed physical letters, routers to regional sorting
offices, and IP addresses to explicit geographical drop points.
• Memory (RAM) = Library: Represents storage locations as indexed bookshelves, where fetching item
data requires an explicit address lookup.
• Abstraction = Driving a Car: Users regularly interact with simplified control configurations (steering
wheel, pedals) without needing to understand the internal mechanisms of engine combustion or
transmission layout.
In modern life, users are continuously surrounded by "black-box" systems—complex setups where the internal
operational mechanics are hidden from public view, exposing only a clear user interface.
The intricate engineering details remain completely obfuscated beneath the chassis:
The Takeaway: Operating a modern personal computer or digital interface relies on this exact
abstraction layer. A user edits a document or executes software commands utilizing an intuitive UI
without needing to comprehend electronic logic gates, kernel memory allocation, or physical silicon
transistor switching loops.
1. Introduction to Analogies
An analogy is a comparison between two different things based on underlying similarities to explain, clarify, or
contextualize a concept. By drawing a parallel between an unfamiliar or complex topic and a familiar one,
analogies serve as powerful cognitive tools across various domains.
Analogies are widely used in teaching, learning, professional communication, systematic problem-solving, and
scientific discovery. They allow individuals to transition from known concepts to new insights by highlighting
structural or functional commonalities.
CLASSIC EXAMPLE
• Improve Understanding: Learners retain and internalize concepts much better when new information is
directly connected to their existing knowledge and familiar real-world experiences.
• Enhance Memory: Analogies convert abstract ideas into concrete, often visual scenarios, making them easier
to mentally store and recall later.
• Support Problem-Solving: Solutions, structures, or logic from a thoroughly understood problem domain can
be systematically mapped and applied to resolve unfamiliar but structurally similar challenges.
• Source Domain: The familiar concept, object, or system used as the reference point.
Books Data
Functional Analogies
A Functional Analogy is strictly based on similarity in operation, purpose, or role rather than physical appearance.
• Explanation: While a biological heart and a mechanical pump look entirely different, both share the identical
functional role of circulating fluids through a system.
• Cause to Effect: Maps a specific action directly to a predictable, similar outcome (Action → Outcome).
• Effort and Result: Links the scale of work invested to the corresponding achievement gained (Work →
Achievement).
• Simple Extended: Consists of multiple parallel comparisons systematically built out from a single foundational
analogy.
• Multi-factor authentication
Synthesized Analogy:
"An ATM is like a vending machine for banking services." Just as a vending machine handles inventory,
processes payment, and dispenses products securely without human intervention, an ATM automates complex
banking transactions through an intuitive self-service portal.
General Limitations
• Oversimplification: Many analogies completely ignore or obscure critical details and nuances essential for
comprehensive technical mastery.
• Incomplete Comparison: An analogy typically illuminates only a few isolated aspects of a target concept,
leaving other parts unaddressed.
• Potential Misconceptions: Two systems may appear highly similar on the surface but differ fundamentally
upon deep analysis.
• The False Analogy: Comparing two things that are not actually alike in the specific, relevant way required to
validate the premise.
• Over-Complication: If the explanatory analogy is more obscure or harder to understand than the original target
concept, it completely fails its purpose.
• Over-stretching: Forcing and pushing the comparison way too far past its logical limits until the parallel breaks
down entirely.
Analogies serve as powerful "cognitive bridges" that connect familiar, well-understood ideas with
unfamiliar, complex concepts. By mapping the structure or relationships of a known domain onto a
new one, analogies make learning clearer, faster, and significantly more intuitive.
These cognitive tools are particularly invaluable in technical fields such as Computer Science,
Software Engineering, and Artificial Intelligence, as well as in general pedagogy. They assist
students and professionals alike in deciphering highly abstract logical frameworks by grounding
them in concrete real-world experiences.
The eight classical categories of analogical reasoning used in instruction and cognitive analysis:
1. Functional 5. Simple
2. Structural 6. Extended
3. Verbal 7. Literal
4. Symbolic 8. Figurative
While both concepts are used to draw comparisons, they serve fundamentally different linguistic and
cognitive purposes. An analogy is primarily a tool for logical reasoning and structured
explanation, whereas a metaphor is a figure of speech designed for vivid expression and
immediate effect.
1. Simple Analogy
2. Structural Analogy
Based strictly on the similarity in physical structure, organizational hierarchy, or the complex
relationships among internal parts.
Uses signs, symbols, representations, or conceptual metaphors to convey deep, abstract meaning
through a highly familiar vehicle.
4. Verbal Analogy
Expressed directly through words and structured proportional relationships between terms,
highly common in standardized aptitude and reasoning tests.
In technical instruction, bridging the gap between physical objects and virtual system structures
helps demystify abstract data layers.
• Easier Learning: Simplifies highly abstract, complex, or intimidating topics, making them
approachable.
• Better Retention: Learners retain knowledge far longer when it is anchored to pre-existing,
familiar mental models.
• Knowledge Transfer: Builds the fundamental intellectual capacity to take a structured solution
from one domain and apply it effectively to an entirely new, unfamiliar situation.
"To teach well, start with what is known, construct a reliable bridge, and safely guide the learner to the unknown."
Module 1: Analogies
What is an Analogy?
Structure of an Analogy
Analogical Reasoning
Everyday Life:
Driving a car is like using a computer — you
interact with controls (steering wheel, pedals)
without needing to understand what's
happening underneath (engine, fuel injection).
Limitations:
Analogy Metaphor
Module Summary
Reduces complexity
Improves understanding
Enhances productivity
Levels of Abstraction
Everyday Examples
Abstraction in Technology
Module Summary
Declarative Programming
Imperative Programming
Definition: Works by changing the program's state
through assignment statements, performing tasks
step by step. The main focus is how to achieve the
goal.
Pros Cons
Advantages/Disadvantages of High-Level
(Structured) Languages:
| Advantages | Disadvantages |
|---|---|
| Easy to read and understand; user-friendly | Machine-
independent code takes time to convert to machine
code |
| Easier to maintain and debug | Depends on
changeable factors like data types |
| Problem-based, not machine-based | Development
can take longer since it's more language-dependent
than assembly |
| Requires less effort/time to develop | — |
About Python
Applications:
Arithmetic Operators:
| Operator | Name | Example |
|---|---|---|
| + | Addition | 10+5 = 15 |
| - | Subtraction | 10-5 = 5 |
| * | Multiplication | 10*5 = 50 |
| / | Division | 10/5 = 2.0 (always returns a float) |
| // | Floor Division | 10//3 = 3 (discards the
fraction) |
| % | Modulus | 10%3 = 1 (the remainder) |
| ** | Exponentiation | 10**2 = 100 |
Logical Operators:
Type Casting
count = 100
count_str = str(count) # converts int to
string
String Slicing
Modifying Strings
Concatenating Strings
Escape Characters
\n — Newline
\t — Tab
\\ — Backslash
String Methods
List
Allows duplicates
Tuple
Definition: An immutable, ordered collection of items
— similar to a list but cannot be changed after
creation. Created with parentheses () .
Set
Dictionary
Conditional Statements
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Loops
Module 8: Functions
What is a Function?
def greet():
print("Hello, welcome to the Python
lecture.")
greet() # calling the function
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Tom", age=45,
city="London")
Recursive Functions
def factorial(n):
if n == 0 or n == 1: # base case
return 1
else: # recursive
case
return n * factorial(n - 1)
Lambda Functions
square = lambda x: x * x
print(square(4)) # 16