[Concepts] Paper 4
- CHAPTER 9: SORTING ALGORITHMS
- CHAPTER 10: SEARCHING ALGORITHMS
- CHAPTER 11: ABSTRACT DATA TYPES
- CHAPTER 12: RECURSION
- CHAPTER 13: OBJECT-ORIENTED PROGRAMMING
- CHAPTER 14: FILE PROCESSING
- CHAPTER 15: EXCEPTION HANDLING
- [Python] Important Algorithms
CHAPTER 9: SORTING ALGORITHMS
9.1 BUBBLE SORT
9.1.1 How It Works
- Compare adjacent elements
- Swap if in wrong order
- Repeat for entire list
- Each pass places largest unsorted element at end
- Continue until no swaps needed
9.1.2 Pseudocode
<PSEUDOCODE>
9.1.3 Python Code
<PYTHON>
9.1.4 Complexity
- Best Case: O(n) - already sorted
- Worst Case: O(n²) - reverse sorted
- Space: O(1)
9.2 INSERTION SORT
9.2.1 How It Works
- Assume first element is sorted
- Take next element
- Insert into correct position in sorted portion
- Repeat until all elements sorted
9.2.2 Pseudocode
<PSEUDOCODE>
9.2.3 Python Code
<PYTHON>
9.2.4 Complexity
- Best Case: O(n) - already sorted
- Worst Case: O(n²) - reverse sorted
- Space: O(1)
CHAPTER 10: SEARCHING ALGORITHMS
10.1 LINEAR SEARCH
10.1.1 How It Works
- Start at first element
- Compare with target
- If match, return position
- If not, move to next element
- Repeat until found or end of list
10.1.2 Pseudocode
<PSEUDOCODE>
10.1.3 Python Code
<PYTHON>
10.1.4 Complexity
- Time: O(n)
- Space: O(1)
10.2 BINARY SEARCH
10.2.1 Prerequisites
- List MUST be sorted
10.2.2 How It Works
- Find middle element
- Compare with target
- If match, return position
- If target > middle, search right half
- If target < middle, search left half
- Repeat until found or sublist empty
10.2.3 Pseudocode
<PSEUDOCODE>
10.2.4 Python Code
<PYTHON>
10.2.5 Complexity
- Time: O(log n)
- Space: O(1)
CHAPTER 11: ABSTRACT DATA TYPES
11.1 STACKS
11.1.1 Characteristics
- LIFO: Last In, First Out
- Add and remove from only one end (top)
11.1.2 Operations
Push (Add):
<PSEUDOCODE>
Pop (Remove):
<PSEUDOCODE>
11.1.3 Python Implementation
<PYTHON>
11.1.4 Uses
- Interrupt handling
- Evaluating RPN expressions
- Procedure call stack
- Undo mechanisms
11.2 QUEUES
11.2.1 Characteristics
- FIFO: First In, First Out
- Add to rear, remove from front
- Can be circular
11.2.2 Operations
Enqueue (Add):
<PSEUDOCODE>
Dequeue (Remove):
<PSEUDOCODE>
11.2.3 Python Implementation
<PYTHON>
11.2.4 Uses
- Print queues
- Task scheduling
- Breadth-first search
11.3 LINKED LISTS
11.3.1 Characteristics
- Dynamic data structure
- Nodes contain data and pointer to next node
- Can grow/shrink easily
11.3.2 Node Structure
<PYTHON>
11.3.3 Linked List Operations
Insert:
<PYTHON>
Delete:
<PYTHON>
Search:
<PYTHON>
11.3.4 Uses
- Dynamic memory allocation
- Implementation of other ADTs
- Symbol tables
11.4 BINARY TREES
11.4.1 Characteristics
- Hierarchical structure
- Each node has at most two children
- Left child < parent, Right child > parent (in ordered tree)
11.4.2 Node Structure
<PYTHON>
11.4.3 Operations
Insert:
- Start at root
- Compare with current node
- Go left if smaller, right if larger
- Repeat until empty position found
Search:
- Start at root
- Compare with current node
- If match, found
- If target < current, go left; else go right
- Repeat until found or null pointer
Traverse (In-order):
<PYTHON>
CHAPTER 12: RECURSION
12.1 WRITING RECURSIVE ALGORITHMS
12.1.1 Essential Components
- Base Case: Condition that stops recursion
- Recursive Case: Function calls itself with modified parameters
12.1.2 Examples
Sum of Numbers:
<PYTHON>
Counting Characters in String:
<PYTHON>
Reverse String:
<PYTHON>
12.1.3 Tracing Recursion
<TEXT>
CHAPTER 13: OBJECT-ORIENTED PROGRAMMING
13.1 CLASSES AND OBJECTS
13.1.1 Defining Classes
<PYTHON>
13.1.2 Creating Objects
<PYTHON>
13.2 INHERITANCE
13.2.1 Basic Inheritance
<PYTHON>
13.2.2 Polymorphism
<PYTHON>
13.3 ENCAPSULATION
13.3.1 Private Attributes
<PYTHON>
13.4 GETTERS AND SETTERS
13.4.1 Purpose
Control access to private attributes.
<PYTHON>
CHAPTER 14: FILE PROCESSING
14.1 FILE OPERATIONS IN PYTHON
14.1.1 Opening Files
<PYTHON>
14.1.2 Reading Files
<PYTHON>
14.1.3 Writing Files
<PYTHON>
14.1.4 Closing Files
<PYTHON>
14.2 RANDOM FILE ACCESS
14.2.1 Direct Access
<PYTHON>
CHAPTER 15: EXCEPTION HANDLING
15.1 TRY-EXCEPT
15.1.1 Basic Structure
<PYTHON>
15.1.2 Multiple Exceptions
<PYTHON>
15.1.3 Finally Block
<PYTHON>
15.1.4 Raising Exceptions
<PYTHON>
[Python] Important Algorithms
Factorial function
def factorial(n): #Task 1: Factorial function
if n==0: #Case 1: 0!
return 1
else: #Case 2: <positive_integer>!
return n*factorial(n-1) #multiply with factorial of n-1
Recursive arithmetic sum
def arithmetic_sum_2(term1,com_dif,n): #Task 2(alternative): Arithmetic Sum Function – Recursive method
if n==1: #Case 1: last term to add(=the first term of the sequence)
return term1
else: #Case 2: add <positive integer>th term
return arithmetic_sum_2(term1,com_dif,(n-1))+(n-1)*com_dif+term1
Iterative arithmetic sum
def arithmetic_sum_1(term1,com_dif,n): #Task 2: Arithmetic Sum function – Formula method
return (n/2)*(2*term1+(n-1)*com_dif)
Recursive geometric sum
def geometric_sum_2(term1,com_rat,n): #Task 3: Geometric Sum function – Recursive method
if n==1: #Case 1: last term to add(=the first term of the sequence)
return float(term1)
else: #Case 2: add <positive integer>th term
return float(geometric_sum_2(term1,com_rat,(n-1))+term1*(com_rat**(n-1))) #perform nth term addition
Iterative geometric sum
def geometric_sum_1(term1,com_rat,n): #Task 3: Geometric Sum function – Formula method
return (term1-(com_rat**n))/(1-com_rat)
Fibonacci function
def fibonacci(term1,term2,n): #Task 4: Fibonacci function
if n == 0:
return term1
elif n == 1:
return term2
else:
return fibonacci(term1,term2,(n-1))+fibonacci(term1,term2,(n-2))
Compound Interest
def compound_interest(initial,inc,n):
return initial*((1+(inc/100))**n)
PIN, deposit & withdraw
correct_pin=1111
enter_pin=0
attempt=0
balance=100.00
option=0
save=0.00
password=True
while attempt<3 and password:
while True:
try:
enter_pin=str(input("Enter PIN (4 digits)"))
if len(str(enter_pin))==4 and int(enter_pin)>=0 and int(enter_pin)<=9999:
break
else:
print("invalid format")
except ValueError:
print("invalid format")
if int(enter_pin)==int(correct_pin):
password=False
else:
attempt+=1
print("wrong")
def deposit():
global balance
while True:
try:
save=float(input("How much you save"))
if save>0:
break
else:
print("can't save that amount")
except ValueError:
print("invalid format")
balance+=save
def withdraw():
global balance
while True:
try:
take=float(input("How much you withdraw"))
if take>0 and take<=balance:
break
else:
print("can't withdraw that amount")
except ValueError:
print("invalid format")
balance-=take
def change_pin():
global correct_pin
while True:
try:
new=str(input("Enter new PIN(4digits)"))
if len(str(new))==4 and int(new)>=0 and int(new)<=9999 and new!=correct_pin:
break
elif new==correct_pin:
print("there is no change")
else:
print("invalid password")
except ValueError:
print("invalid format")
correct_pin=new
print("Change successful")
if not(password):
Out=False
while not(Out):
print("MENU")
print(f"Balance: {balance}")
print("Deposit[1]")
print("Withdraw[2]")
print("Change PIN[3]")
print("Exit[4]")
while True:
try:
option=int(input("Enter Option(number key)"))
if option>=1 and option<=4:
break
else:
print("no such option")
except ValueError:
print("invalid format")
if option==1:
deposit()
elif option==2:
withdraw()
elif option==3:
change_pin()
else:
Out=True
else:
print("Max attempt reached")
if Out==True:
print("End.")