Introduction to Algorithms, Programming, and Compilers
- Cell 1: Markdown
- Introduction to Algorithms, Programming, and Compilers
- Store Closing Algorithm Challenge
- How to Play:
- Available Steps
- Your Order
- Perfect! You got it right!
- Not quite right
- Why Algorithms Matter in Programming
- Designing Good Algorithms
- What is a Compiler?
- Homework Hacks
- Congratulations!
- Important: Read Below
Cell 1: Markdown
Introduction to Algorithms, Programming, and Compilers
Please Navigate to 2025-09-21-1.1.ipynb
Get ready to practice with Algorithims, Compilers and More!
What is an Algorithm?
An algorithm is a step-by-step process to complete a task or solve a problem. Think of it like a recipe: each instruction must be followed in order to get the desired result.
Real-World Example: Making a Sandwich
- Get two slices of bread
- Spread peanut butter on one slice
- Spread jelly on the other slice
- Put the slices together
- Cut in half
Notice how each step is clear and in a specific order. That’s an algorithm!
Store Closing Algorithm Challenge
Drag and drop the steps into the correct order
How to Play:
- Drag steps from the left column to the position slots on the right
- Arrange them in the correct logical order for closing a store
- Click "Check Answer" to see if you got it right
- Use "Clear All" to start over or "Reset & Shuffle" for a new challenge
Available Steps
Your Order
Why Algorithms Matter in Programming
In programming, algorithms tell the computer exactly what to do. The more detailed and precise your algorithm, the better your program will work.
Example: Login System Algorithm
1. Get username from user
2. Get password from user
3. Check if username exists in database
4. If username doesn't exist → show error message
5. If username exists → compare password
6. If password matches → grant access
7. If password doesn't match → show error message
# Here's a Python version of the login algorithm you can run!
# Simple user database
user_database = {
"alice": "password123",
"bob": "securepass",
"charlie": "mypass456"
}
def login(username, password):
"""Algorithm for user login"""
# Step 1-2: Already have username and password as parameters
# Step 3: Check if username exists
if username not in user_database:
# Step 4: Handle user not found
print("❌ Error: Username not found")
return False
# Step 5-7: Compare password
if user_database[username] == password:
print("✅ Login successful!")
return True
else:
print("❌ Error: Incorrect password")
return False
# Try it out!
print("Test 1: Correct login")
login("alice", "password123")
print("\nTest 2: Wrong password")
login("alice", "wrongpass")
print("\nTest 3: User doesn't exist")
login("david", "anypass")
Designing Good Algorithms
Key Principle: Each task needs clear, detailed instructions.
❌ Bad Algorithm Example:
1. Prepare for school
2. Go to school
✅ Good Algorithm Example:
1. Wake up at 7:00 AM
2. Brush teeth
3. Take a shower
4. Get dressed in school uniform
5. Eat breakfast
6. Pack backpack with homework and lunch
7. Leave house at 7:45 AM
8. Walk to bus stop
9. Take bus to school
The second algorithm is better because it’s specific and detailed.
# Algorithm: Store user information
age = 16
name = "Alice"
is_student = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Is a student: {is_student}")
# Try changing the values and run again!
# age = 17
# name = "Bob"
2. Methods/Functions - Reusable Algorithms
Functions let you write an algorithm once and use it many times!
class Calculator:
"""A calculator class with reusable algorithms"""
def add(self, a, b):
"""Algorithm: Add two numbers"""
return a + b
def max(self, a, b):
"""Algorithm: Find the larger number"""
if a > b:
return a
else:
return b
def multiply(self, a, b):
"""Algorithm: Multiply two numbers"""
result = 0
for i in range(b):
result = self.add(result, a)
return result
# Create calculator and test it
calc = Calculator()
print("Addition: 5 + 3 =", calc.add(5, 3))
print("Maximum: max(10, 7) =", calc.max(10, 7))
print("Multiplication: 4 × 3 =", calc.multiply(4, 3))
# Try your own calculations!
# print(calc.add(100, 250))
What is a Compiler?
A compiler translates code that humans can read into machine code that computers can execute.
The Process:
Your Code → Compiler → Bytecode → Virtual Machine → Running Program
Note: Python is an interpreted language (runs line-by-line), while Java uses a compiler. But the concept is the same: translating human-readable code into something the computer can execute!
Example:
# You write this:
print("Hello, World!")
# Python interpreter executes it directly
# Output: Hello, World!
# Let's see what's "under the hood" of Python code!
import dis
def greet(name):
message = f"Hello, {name}!"
return message
# This shows the bytecode Python generates
print("Python bytecode for greet() function:")
print("=" * 50)
dis.dis(greet)
print("\n" + "=" * 50)
print("When you call the function:")
result = greet("Alice")
print(result)
Homework Hacks
Hack 1: Create Your Own Algorithm
Write a detailed algorithm for one of these activities:
- Getting ready for a basketball game
- Making a pizza from scratch
- Setting up a new phone
Requirements:
- At least 8 steps
- Each step must be specific and clear
- Steps must be in logical order
”””
Example Response:
Activity chosen: [Write your activity here]
Algorithm:
- [Your first step]
- [Your second step]
- [Your third step]
- [Continue…] “””
Hack 2: Identify the Bug
This algorithm has steps in the wrong order. Fix it:
Algorithm: Send an Email
1. Click "Send"
2. Open email application
3. Type the message
4. Log into your account
5. Enter recipient's email address
6. Write subject line
Example Response:
Corrected Algorithm: Send an Email
- [Your corrected step 1]
- [Your corrected step 2]
- [Your corrected step 3]
- [Continue…]
Hack 3: Code the Algorithm
Convert this algorithm into working Python code:
Algorithm: Grade Calculator
1. Get three test scores from user
2. Add them together
3. Divide by 3 to get average
4. If average >= 90, grade is A
5. If average >= 80, grade is B
6. If average >= 70, grade is C
7. If average >= 60, grade is D
8. Otherwise, grade is F
9. Display the grade
Example Response
def calculate_grade(score1, score2, score3):
"""
Calculate letter grade from three test scores
Args:
score1, score2, score3: Test scores (integers)
Returns:
grade: Letter grade (string)
"""
# TODO: Your code here!
# Step 1: Add the three scores together
# Step 2: Calculate the average
# Step 3: Determine the letter grade using if-elif-else
# Step 4: Return the grade
pass # Remove this when you add your code
# Test your function!
print("Test 1:", calculate_grade(95, 92, 88)) # Should be 'A'
print("Test 2:", calculate_grade(85, 80, 82)) # Should be 'B'
print("Test 3:", calculate_grade(75, 70, 72)) # Should be 'C'
print("Test 4:", calculate_grade(65, 60, 62)) # Should be 'D'
print("Test 5:", calculate_grade(55, 50, 52)) # Should be 'F'
Congratulations!
You’ve completed the Introduction to Algorithms lesson. Make sure to:
- Complete all 3 homework hacks
- Test your code by running all cells
- Experiment with the interactive examples
Important: Read Below
Submit your accomplishment of this lesson by following instructions inside the notebook aswell as running the practices for the hacks. Make sure that you submit your screenshots into an issue and then submit that issue in the google form: Link to Google Form Homework is Due in 3 Days.