Crashers - 3.9 Developing Algorithms Python Hacks
Categories: PythonLearn how to develop algorithms through the Peppa Pig Maze game
🐷 Peppa’s Algorithm Adventures - Python Hacks
Welcome to Peppa’s algorithm challenges! Complete these three hacks to master algorithm development with interactive Python examples.
Hack 1: Peppa’s Number Comparison Algorithm �
Create algorithms that use Boolean expressions to compare numbers, just like in the lesson!
Your task: Complete the missing Boolean conditions to help Peppa make smart decisions.
# Peppa's number comparison algorithms (like the lesson examples!)
def algorithm_a_find_maximum(a, b):
"""Algorithm A: Find the larger number using if-else"""
# Use a straightforward if/else comparison
if a > b:
return a
else:
return b
def algorithm_b_find_maximum(a, b):
"""Algorithm B: Same problem, different approach using Boolean expression"""
# Use a concise boolean expression (ternary style)
return a if a > b else b
def peppa_decision_maker():
"""Help Peppa make decisions using Boolean logic"""
peppa_coins = 20
toy_price = 12
print("🐷 Peppa's Decision Algorithm")
print(f"Peppa has {peppa_coins} coins")
print(f"Toy costs {toy_price} coins")
# Use >= so Peppa can buy when she has exactly the toy price
can_buy_toy = peppa_coins >= toy_price
if can_buy_toy:
print("✅ Peppa can buy the toy!")
else:
print("❌ Peppa needs more coins!")
return can_buy_toy
# Test the algorithms (like the lesson does)
print("=== Testing Maximum Algorithms ===")
x, y = 10, 7
print(f"Algorithm A result: {algorithm_a_find_maximum(x, y)}")
print(f"Algorithm B result: {algorithm_b_find_maximum(x, y)}")
print("\n=== Peppa's Decision ===")
peppa_decision_maker()
=== Testing Maximum Algorithms ===
Algorithm A result: 10
Algorithm B result: 10
=== Peppa's Decision ===
🐷 Peppa's Decision Algorithm
Peppa has 20 coins
Toy costs 12 coins
✅ Peppa can buy the toy!
True
Hack 2: George’s Simple Movement Algorithm �
Create a simple movement algorithm like the maze example from the lesson!
Your task: Complete the Boolean conditions to control George’s movement.
# George's movement algorithm (similar to the lesson's maze example)
def george_movement_algorithm():
"""Simple movement system using Boolean conditions"""
# George's current position
george_x = 2
george_y = 1
# Boundary limits (like the maze example)
max_x = 4
max_y = 3
min_x = 0
min_y = 0
print("🐷 George's Movement Algorithm")
print(f"George is at position ({george_x}, {george_y})")
print(f"Boundaries: x({min_x}-{max_x}), y({min_y}-{max_y})")
print("\n--- Testing Movement ---")
# Try moving right
new_x = george_x + 1
can_move_right = (new_x <= max_x) and (new_x >= min_x)
print(f"Move right to ({new_x}, {george_y}): {'✅ Valid' if can_move_right else '❌ Invalid'}")
# Try moving up
new_y = george_y + 1
can_move_up = (new_y <= max_y) and (new_y >= min_y)
print(f"Move up to ({george_x}, {new_y}): {'✅ Valid' if can_move_up else '❌ Invalid'}")
# Try moving left
new_x = george_x - 1
can_move_left = (new_x >= min_x) and (new_x <= max_x)
print(f"Move left to ({new_x}, {george_y}): {'✅ Valid' if can_move_left else '❌ Invalid'}")
def interactive_movement():
"""Let user test the movement algorithm"""
print("\n🎯 Interactive Movement Test")
x, y = 1, 1 # Starting position
direction = input("Which way should George move? (up/down/left/right): ").lower()
if direction == "right":
new_x, new_y = x + 1, y
elif direction == "left":
new_x, new_y = x - 1, y
elif direction == "up":
new_x, new_y = x, y + 1
elif direction == "down":
new_x, new_y = x, y - 1
else:
print("❌ Invalid direction!")
return
# Correct Boolean boundary condition
is_valid_move = (0 <= new_x <= 4) and (0 <= new_y <= 3)
if is_valid_move:
print(f"✅ George moved {direction} to ({new_x}, {new_y})")
else:
print(f"❌ Can't move {direction} - out of bounds!")
# Run the algorithms
george_movement_algorithm()
interactive_movement()
Hack 3: Peppa’s Pathfinding Adventure 🗺️
Create a pathfinding algorithm to help Peppa navigate through different terrains to reach her friends! This combines Boolean logic, conditional statements, and algorithm design.
Your task: Implement different pathfinding strategies and compare their effectiveness using interactive visualizations.
def peppa_maze_pathfinder():
"""Help Peppa find her way through a simple maze"""
maze = [
[2, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 1, 1],
[1, 1, 1, 0, 0, 3]
]
def display_maze(path=None):
symbols = {0: "⬜", 1: "⬛", 2: "🐷", 3: "🏆"}
print("\n🗺️ Peppa's Maze:")
for r in range(6):
row = ""
for c in range(6):
if path and (r, c) in path:
row += "🟨"
else:
row += symbols[maze[r][c]]
print(row)
def is_valid_move(row, col):
if row < 0 or row >= 6 or col < 0 or col >= 6:
return False
if maze[row][col] == 1:
return False
return True
def find_path():
start = (0, 0)
goal = (5, 5)
from collections import deque
q = deque()
q.append((start, [start]))
visited = {start}
while q:
(r, c), path = q.popleft()
if (r, c) == goal:
return path
for dr, dc in [(0,1),(1,0),(0,-1),(-1,0)]:
nr, nc = r+dr, c+dc
if is_valid_move(nr, nc) and (nr, nc) not in visited:
visited.add((nr, nc))
q.append(((nr, nc), path + [(nr, nc)]))
return None
print("🐷 Welcome to Peppa's Mini Maze!")
display_maze()
path = find_path()
if path:
print("✅ Path found!")
display_maze(path)
print(f"Path length: {len(path)} steps")
else:
print("❌ No path found — check the maze or is_valid_move logic")
peppa_maze_pathfinder()
🐷 Welcome to Peppa's Mini Maze!
🗺️ Peppa's Maze:
🐷⬜⬛⬜⬜⬜
⬜⬜⬛⬜⬛⬜
⬜⬛⬜⬜⬜⬜
⬜⬜⬜⬛⬜⬜
⬛⬜⬜⬜⬛⬛
⬛⬛⬛⬜⬜🏆
✅ Path found!
🗺️ Peppa's Maze:
🟨⬜⬛⬜⬜⬜
🟨⬜⬛⬜⬛⬜
🟨⬛⬜⬜⬜⬜
🟨🟨🟨⬛⬜⬜
⬛⬜🟨🟨⬛⬛
⬛⬛⬛🟨🟨🟨
Path length: 11 steps
📝 What You Should Complete
After finishing the lesson, you should be able to:
- Hack 1: Fill in the Boolean comparison operators (
<=,>=,<,>) to make the muddy puddle validator work - Hack 2: Complete the
if/elif/elsestatements for George’s number comparison - Hack 3: Fill in the boundary conditions for George’s movement algorithm