Common Coding Patterns
Checking Divisibility
A classic use of the modulo operator is checking whether a number is divisible:
def is_divisible(number, divisor):
return number % divisor == 0
## Examples
print(is_divisible(10, 2)) ## True
print(is_divisible(15, 4)) ## False
Alternating Behavior
Create patterns that switch between states:
def toggle_state(iteration):
return "On" if iteration % 2 == 0 else "Off"
for i in range(5):
print(f"Iteration {i}: {toggle_state(i)}")
Circular Buffer Implementation
class CircularBuffer:
def __init__(self, size):
self.size = size
self.buffer = [None] * size
self.current = 0
def add(self, item):
self.buffer[self.current % self.size] = item
self.current += 1
def get_latest(self):
return self.buffer[(self.current - 1) % self.size]
buffer = CircularBuffer(3)
buffer.add(1)
buffer.add(2)
buffer.add(3)
buffer.add(4)
print(buffer.get_latest()) ## 4
Round-Robin Scheduling
class RoundRobinScheduler:
def __init__(self, tasks):
self.tasks = tasks
self.current_task = 0
def get_next_task(self):
task = self.tasks[self.current_task % len(self.tasks)]
self.current_task += 1
return task
tasks = ['Task A', 'Task B', 'Task C']
scheduler = RoundRobinScheduler(tasks)
for _ in range(5):
print(scheduler.get_next_task())
Generating Unique Patterns
def generate_unique_pattern(seed, length):
return [i % length for i in range(seed, seed + length)]
print(generate_unique_pattern(3, 5)) ## [3, 4, 0, 1, 2]
Frequency Distribution
def count_frequency_distribution(numbers, max_value):
distribution = [0] * max_value
for num in numbers:
distribution[num % max_value] += 1
return distribution
numbers = [12, 15, 17, 22, 25, 30]
print(count_frequency_distribution(numbers, 5))
Visualization of Modulo Patterns
graph TD
A[Modulo Operator Patterns] --> B[Divisibility Check]
A --> C[State Toggling]
A --> D[Circular Buffer]
A --> E[Round-Robin Scheduling]
A --> F[Unique Pattern Generation]
Common Modulo Patterns
Pattern |
Use Case |
Example |
Divisibility Check |
Determine if number is divisible |
n % d == 0 |
Circular Access |
Access elements in a circular manner |
index % length |
State Toggling |
Alternate between two states |
iteration % 2 |
Frequency Distribution |
Count occurrences in ranges |
value % max_range |
Advanced Pattern: Hash Distribution
def distribute_items(items, buckets):
distribution = [[] for _ in range(buckets)]
for item in items:
bucket = hash(item) % buckets
distribution[bucket].append(item)
return distribution
items = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(distribute_items(items, 3))
By understanding these common coding patterns, you'll become proficient in using the modulo operator across various programming scenarios with LabEx.