Sunday, May 24, 2026
Cohort 3 | Project CloudIgnite Topics: Prime Numbers Script, Python Challenge Walkthroughs, LeetCode, Nested Loops, Python Tips Duration: ~4 hours
Key Takeaways
- Prime number algorithms: basic O(n/2), optimized (skip evens), efficient O(√n) — RSA encryption uses large primes
- Palindrome: clean string (keep alpha, lowercase), reverse with
[::-1], compare - Highest frequency character: build count dict, iterate alphabetically for tie-breaking
- LeetCode Two Sum: nested loop O(n²) approach; hash map solution is O(n)
- Python tips: ternary operator, chained comparisons (
'a' <= ch <= 'z'),map(),zip(), multiple assignment, list slicing, type hints - Nested loops: right-angled triangle and pyramid pattern printing
- Key insight:
s[::-1]reverses a string; Python has no built-in.reverse()for strings
Table of Contents
- Lab 14 – Prime Numbers Script (EC2/Python)
- Python Challenge 2 – Problem Walkthroughs
- Python Tips & Syntax Features
- LeetCode Problem 1 – Two Sum
- Nested Loops – Triangle & Pyramid
- AWS CLF-C02 Relevance
Lab 14 – Prime Numbers Script
Objective: Write a Python script that displays all prime numbers between 1–250 (or a given range), then saves results to results.txt.
What is a Prime Number?
A number divisible only by 1 and itself. Note: 1 is not considered prime.
Algorithm: Checking if N is Prime
Version 1 – Basic (check up to N/2)
def is_prime(n):
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
return True
- Uses
//(integer division) instead of/to avoid float errors %is the modulo operator — returns remainder; if0, the number is divisible
Version 2 – Faster (skip even numbers, check odd only)
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i <= n // 2:
if n % i == 0:
return False
i += 2 # step by 2, odd numbers only
return True
- ~2× faster than Version 1 by skipping even divisors
Version 3 – Most Efficient (check up to √N)
import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i <= math.sqrt(n):
if n % i == 0:
return False
i += 2
return True
- For N = 10,000: Version 1 iterates ~5,000×, Version 2 ~2,500×, Version 3 only ~50×
- For very large numbers, the speed difference is enormous
Complexity note: Modern CPUs handle ~10^7.5–10^8 operations/second. Loops that iterate 10^8+ times can take minutes or hours.
Collecting & Printing Primes
primes = []
for i in range(2, 251):
if is_prime(i):
primes.append(i)
# Print space-separated
print(*primes) # using unary star (print only)
print(" ".join(map(str, primes))) # using join + map (works anywhere)
Writing Output to File
prime_str = " ".join(map(str, primes))
try:
with open("results.txt", "w") as file:
file.write(prime_str)
print("Result saved to results.txt")
except Exception as e:
print(f"Error: {e}")
Note:
try/exceptis optional here but recommended for good practice.
Key Concepts Recap
| Operator | Meaning | Example |
|---|---|---|
% | Modulo (remainder) | 11 % 3 == 2 |
// | Integer division | 11 // 2 == 5 |
/ | Float division | 11 / 2 == 5.5 |
Real-World Relevance
- Prime numbers are the foundation of RSA encryption and SSL/TLS — directly relevant to cybersecurity
- Large primes (100+ digits) are used in real cryptographic systems
- Probabilistic algorithms (e.g., Miller-Rabin) exist for checking very large primes — not 100% accurate but extremely fast
Python Challenge 2 – Problem Walkthroughs
Problem 6 – Palindrome Checker
A palindrome reads the same forwards and backwards (e.g., madam, racecar).
Key steps:
- Clean the string (keep only alphabetic characters, lowercase)
- Reverse the cleaned string
- Compare — if equal, it's a palindrome
def clean(sequence):
result = []
for ch in sequence:
if ('a' <= ch <= 'z') or ('A' <= ch <= 'Z'):
result.append(ch.lower())
return "".join(result)
def is_palindrome(sequence):
seq1 = sequence.lower()
seq2 = sequence[::-1].lower() # [::-1] reverses the string
return seq1 == seq2
s = input()
cleaned = clean(s)
if is_palindrome(cleaned):
print("Yes")
else:
print("No")
String reversal tip:
s[::-1]— Python has no built-in.reverse()for strings; use slice notation instead.
Problem 7 – Highest Frequency Character
Find the character that appears most frequently; if tied, return the one that comes first alphabetically.
s = input()
count = {}
for ch in s:
if ch in count:
count[ch] += 1
else:
count[ch] = 1
# Alternative: count[ch] = count.get(ch, 0) + 1
# Iterate alphabetically, track the max
alphabet = "abcdefghijklmnopqrstuvwxyz"
answer = alphabet[0]
for ch in alphabet:
if count.get(ch, 0) > count.get(answer, 0):
answer = ch
print(answer)
Key insight: Iterating through the alphabet (instead of the string) ensures alphabetical priority naturally.
Python Tips & Syntax Features
1. Ternary Operator
# Instead of:
if x >= 40:
answer = "Pass"
else:
answer = "Fail"
# Use:
answer = "Pass" if x >= 40 else "Fail"
2. Chained Comparisons
# Instead of:
if ch >= 'a' and ch <= 'z':
# Use:
if 'a' <= ch <= 'z': # More readable, like natural language
3. Underscore as Number Separator
big_number = 1_000_000_000 # Same as 1000000000, easier to read
pi = 3.141_592_653
4. map() Function
Applies a function to every item in an iterable.
def double(item):
return item * 2
nums = list(map(int, input().split())) # Common pattern: read integers
result = list(map(double, nums))
5. zip() Function
Combines two (or more) lists element-by-element into tuples.
cars = ['A', 'B', 'C', 'D']
count = [1, 2, 3, 4]
for item in zip(cars, count):
print(item) # ('A', 1), ('B', 2), ...
# Unpack directly:
for car, c in zip(cars, count):
print(car, c)
6. Multiple Assignment & Swap
a, b = 0, 1 # Assign multiple variables in one line
a, b = b, a # Swap without a temp variable
7. List Slicing with Step
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
items[2:5] # Index 2 to 4
items[::2] # Every 2nd item: 0, 2, 4, 6, 8
items[::-1] # Reverse the list
items[5:1:-1] # From index 5 down to index 2
Syntax: list[start:stop:step]
8. List Initialisation
zeros = [0] * 10 # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9. Type Hints (introduced via LeetCode)
def two_sum(nums: list[int], target: int) -> list[int]:
...
Not required, but improves readability — shows expected input/output types.
LeetCode Problem 1 – Two Sum
Problem: Given a list of integers and a target, return the indices of two numbers that add up to the target.
Solution (Nested/2D Loop)
def two_sum(nums, target):
answer = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
answer = [i, j]
break
if len(answer) > 0:
break
return answer
How it works:
- Outer loop picks one number
- Inner loop starts from
i+1(avoids reuse and duplicates) - When a pair is found, both loops break and indices are returned
Note: This O(n²) solution is not the most efficient, but it is the most readable for beginners. An O(n) solution using a hash map exists.
Nested Loops – Triangle & Pyramid
Right-Angled Triangle
n = int(input())
# Method 1: Nested loop
for i in range(n):
for j in range(i + 1):
print("*", end="")
print()
# Method 2: One-liner (uses string multiplication)
for i in range(1, n + 1):
print("*" * i)
Pyramid
n = int(input())
for i in range(n):
# Print leading spaces
for j in range(n - i):
print(" ", end="")
# Print stars (2i + 1 stars per row)
for k in range(2 * i + 1):
print("*", end="")
print()
Pattern logic:
| Row (i, 0-indexed) | Spaces (n−i) | Stars (2i+1) |
|---|---|---|
| 0 | n | 1 |
| 1 | n−1 | 3 |
| 2 | n−2 | 5 |
| n−1 | 1 | 2n−1 |
Debugging tip: Use VS Code debugger — set a breakpoint (red dot on line number), then use "Run and Debug". Add Watch expressions (e.g.,
i,j,n-i) to track values step-by-step.
Upcoming Topics
- Tomorrow: Introduction to Databases — SQLite and some NoSQL
- Instructor plans to prepare a weekly Python challenge for continued practice
- Theory modules will be paced faster to allow revision time in the final week
AWS CLF-C02 Relevance
The majority of this lecture was focused on Python programming fundamentals. Direct AWS CLF-C02 exam content was minimal, but the following connections are worth noting:
✅ Indirectly Relevant
| Topic Covered | CLF-C02 Connection |
|---|---|
| Connecting to EC2 instances and running scripts | Domain 3: Cloud Technology & Services — EC2 is a core compute service tested in the exam |
| Using VS Code / Cloud9 as a development environment | AWS Cloud9 is an AWS-managed IDE; understanding cloud-based dev tools is useful context |
| Python scripting on Linux | EC2 instances commonly run Linux; familiarity helps with real-world AWS usage |
| RSA / SSL / encryption mentioned | CLF-C02 covers AWS security services (ACM, KMS) at a conceptual level — understanding that encryption underpins HTTPS/SSL is helpful background |
| Try/except for file operations | General best-practice coding — not exam content, but relevant to building on AWS |
❌ Not Directly Tested in CLF-C02
- Prime number algorithms, palindrome checking, frequency counting, LeetCode problems, and Python syntax tips are not part of the CLF-C02 exam syllabus.
📌 Recommended CLF-C02 Study Areas (for self-study)
If you want to reinforce AWS knowledge alongside this course, focus on:
- EC2 – instance types, pricing models (On-Demand, Reserved, Spot)
- Security – Shared Responsibility Model, IAM, encryption at rest/in transit
- Core Services – S3, RDS, Lambda, VPC
- Cloud concepts – High availability, scalability, fault tolerance
Notes compiled from lecture — May 24, 2026