Pattern Matching
Learn to identify similarities and patterns across different problems and solutions. Pattern matching is a fundamental computational thinking skill that helps you recognize when a new problem is similar to problems you’ve solved before.
What is Pattern Matching?
Pattern matching is the process of identifying regularities, similarities, and recurring structures in problems, data, or solutions. It’s about recognizing when something you’re facing is similar to something you’ve encountered before.
Core Elements of Pattern Matching
🔍 Recognition
Identifying when problems share similar structures or characteristics
🔗 Connection
Linking new problems to familiar patterns and existing solutions
📋 Classification
Grouping similar problems or data into categories based on shared features
Types of Patterns in Problem Solving
1. Problem Structure Patterns
Recognizing similar problem structures across different domains:
Pattern: Finding specific items in a collection
- Finding a book in a library
- Locating a file on a computer
- Searching for a word in a document
- Finding a contact in your phone
Common Solution Pattern:
- Define what you're looking for
- Determine where to search
- Choose a search strategy (linear, binary, etc.)
- Apply the search method
- Handle found/not found cases
- Organizing books by author
- Ranking students by grade
- Arranging tasks by priority
- Sorting files by date
Common Solution Pattern:
- Define the sorting criteria
- Choose comparison method
- Select sorting algorithm
- Apply systematic rearrangement
- Verify the result
- Finding the shortest route to work
- Scheduling tasks to minimize time
- Packing a suitcase efficiently
- Budgeting money for maximum benefit
Common Solution Pattern:
- Define what "best" means
- Identify constraints
- Generate possible solutions
- Evaluate and compare options
- Select optimal solution
Recognizing patterns in data helps predict behavior and make decisions:
Example: Website Traffic Analysis
Daily Visitors:
Monday: 1,200
Tuesday: 1,350
Wednesday: 1,400
Thursday: 1,450
Friday: 1,800
Saturday: 900
Sunday: 750
Patterns Identified:
- Weekday Pattern: Steady increase Mon-Thu
- Weekend Pattern: Significant drop Sat-Sun
- Peak Pattern: Friday has highest traffic
- Weekly Cycle: Pattern repeats each week
Applications:
- Staff scheduling based on expected traffic
- Server capacity planning
- Marketing campaign timing
- Content publishing schedule
3. Solution Patterns
Recognizing when similar solution strategies apply:
Divide and Conquer Pattern
When to Use: When you can break a problem into smaller, similar subproblems
Examples:
- Organizing a large event → Break into smaller tasks (venue, catering, entertainment)
- Learning a new language → Separate into vocabulary, grammar, pronunciation
- Cleaning a house → Room by room approach
- Debugging code → Isolate sections and test individually
Pattern Steps:
- Divide the problem into smaller subproblems
- Solve each subproblem independently
- Combine solutions to solve the original problem
Trial and Error Pattern
When to Use: When the solution space is small or when learning from failures is valuable
Examples:
- Finding the right password combination
- Adjusting recipe ingredients to taste
- Troubleshooting technical problems
- Learning a new skill through practice
Pattern Steps:
- Make an educated guess
- Test the solution
- Analyze the result
- Adjust based on feedback
- Repeat until successful
Template Pattern
When to Use: When you have a proven framework that can be adapted to similar problems
Examples:
- Writing essays using introduction-body-conclusion structure
- Following a recipe template for different dishes
- Using project management frameworks for different projects
- Applying coding design patterns to different programs
Pattern Steps:
- Identify the general template or framework
- Adapt the template to specific requirements
- Fill in the details specific to your problem
- Execute following the adapted template
Pattern Matching in Programming
Recognizing Code Patterns
1# Pattern: Input Validation
2# Appears whenever you need to check user input
3
4# Pattern Template:
5def validate_input(user_input, validation_criteria):
6 if not meets_criteria(user_input, validation_criteria):
7 return error_message
8 return processed_input
9
10# Applied to different contexts:
11
12# Email validation
13def validate_email(email):
14 if "@" not in email or "." not in email:
15 return "Invalid email format"
16 return email.lower()
17
18# Age validation
19def validate_age(age_str):
20 try:
21 age = int(age_str)
22 if age < 0 or age > 120:
23 return "Age must be between 0 and 120"
24 return age
25 except ValueError:
26 return "Age must be a number"
27
28# Password validation
29def validate_password(password):
30 if len(password) < 8:
31 return "Password must be at least 8 characters"
32 if not any(c.isdigit() for c in password):
33 return "Password must contain at least one number"
34 return password
Algorithm Patterns
1# Pattern: Accumulator Pattern
2# Used when building up a result over multiple iterations
3
4# Template:
5result = initial_value
6for item in collection:
7 result = update_result(result, item)
8return result
9
10# Applied Examples:
11
12# Sum of numbers
13def sum_numbers(numbers):
14 total = 0 # initial_value
15 for num in numbers:
16 total = total + num # update_result
17 return total
18
19# Build a string
20def create_greeting(names):
21 greeting = "Hello " # initial_value
22 for name in names:
23 greeting = greeting + name + ", " # update_result
24 return greeting[:-2] # remove last comma
25
26# Count occurrences
27def count_vowels(text):
28 count = 0 # initial_value
29 for char in text:
30 if char.lower() in "aeiou":
31 count = count + 1 # update_result
32 return count
Practical Pattern Matching Exercises
Exercise 1: Identify the Pattern
For each scenario, identify what type of problem pattern it represents:
Scenario: You need to find the best route from your home to three different stores, visiting each once.
- Pattern Type: _______________
- Similar Problems: _______________
Scenario: You’re organizing your email inbox by creating folders and moving emails to appropriate categories.
- Pattern Type: _______________
- Similar Problems: _______________
Scenario: You notice your monthly electricity bill follows a predictable pattern based on seasonal weather.
- Pattern Type: _______________
- Applications: _______________
Exercise 1 Solutions
- Optimization Pattern - Similar to traveling salesman problem, scheduling tasks, resource allocation
- Classification/Sorting Pattern - Similar to filing documents, organizing books, categorizing data
- Data Pattern Recognition - Applications include budgeting, energy planning, seasonal business forecasting
Exercise 2: Apply Solution Patterns
Choose the best solution pattern for each problem:
Problem: Learning to play guitar
- Options: Divide and Conquer, Trial and Error, Template Pattern
- Best Choice: _______________
- Reasoning: _______________
Problem: Debugging a complex software issue
- Options: Divide and Conquer, Trial and Error, Template Pattern
- Best Choice: _______________
- Reasoning: _______________
Exercise 2 Solutions
- Template Pattern + Divide and Conquer - Use proven learning methods (scales, chords, songs) and break into smaller skills
- Divide and Conquer - Isolate different parts of the system to identify where the bug occurs
Pattern Libraries for Programmers
Common Programming Patterns
When to Recognize: You need to repeat an action or process multiple items
Variations:
- For Each: Process every item in a collection
- While: Repeat until a condition is met
- Counting: Repeat a specific number of times
- Search: Repeat until you find what you're looking for
Pattern Recognition:
- Keywords: "for each", "every", "all", "until", "while"
- Context: Collections, lists, repetitive tasks
Variations:
- If-Then: Simple decision making
- If-Then-Else: Binary choices
- Multiple Conditions: Several possible paths
- Nested Conditions: Decisions within decisions
Pattern Recognition:
- Keywords: "if", "when", "depending on", "in case of"
- Context: Decision points, branching logic
Variations:
- Mapping: Transform each item individually
- Filtering: Select items that meet criteria
- Reducing: Combine many items into one result
- Grouping: Organize items by shared characteristics
Pattern Recognition:
- Keywords: "convert", "transform", "filter", "group", "combine"
- Context: Data processing, format changes
Steps to Develop Pattern Recognition Skills
- Study Examples: Look at how similar problems are solved in different contexts
- Document Patterns: Keep notes on patterns you discover
- Practice Application: Try applying known patterns to new problems
- Reflect on Solutions: After solving problems, identify which patterns you used
- Build Templates: Create reusable templates for common patterns
Pattern Documentation Template
Pattern Name: _______________
Problem Type: _______________
When to Use: _______________
Key Characteristics:
- _______________
- _______________
- _______________
Solution Steps:
1. _______________
2. _______________
3. _______________
Examples:
- _______________
- _______________
- _______________
Variations:
- _______________
- _______________
Next Steps
Pattern matching becomes more powerful when combined with the other computational thinking skills:
- With Decomposition: Break complex patterns into simpler components
- With Abstraction: Focus on essential pattern features while ignoring irrelevant details
- With Algorithms: Create step-by-step procedures for applying patterns
The more patterns you recognize and document, the faster you’ll be able to solve new problems by connecting them to familiar solutions.