Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Create a Data Splitter Class in Python
This code defines a DataSplitter class that splits data by index, into chunks, or by a predicate, demonstrating OOP principles in Python.
class DataSplitter:
def __init__(self, data):
self.data = list(data)
def split_by_index(self, index):
return self.data[:index], self.data[index:]
def split_into_chunks(self, chunk_size):
return [self.data[i:i + chunk_size] for i in range(0, len(self.data), chunk_size)]
…
Split Array Largest Sum in Python (Minimize Largest Subarray Sum)
Binary search + greedy check to split an array into k subarrays while minimizing the largest subarray sum.
def can_split(nums, k, max_sum):
subarrays = 1
current_sum = 0
for num in nums:
if current_sum + num <= max_sum:
current_sum += num
else:
subarrays += 1
current_sum = num
if subarrays > k:
return False
return True
def spli…
How to Implement CQRS with Separate Read and Write Models in Python
Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.
from dataclasses import dataclass, field
from typing import List, Dict, Optional
@dataclass
class OrderWriteModel:
order_id: int
customer: str
items: List[str] = field(default_factory=list)
def add_item(self, item: str) -> None:
self.items.append(item)
@dataclass
class OrderReadModel:
…
K-Fold Cross Validation in Python: A Simple Implementation
Implements k-fold cross validation from scratch, splitting data into folds and computing MSE scores for a baseline mean-predictor model.
import random
from statistics import mean
def cross_validation_scores(data, labels, k=5, seed=42):
random.seed(seed)
indices = list(range(len(data)))
random.shuffle(indices)
fold_size = len(indices) // k
folds = []
for i in range(k):
if i == k - 1:
folds.append(indices[i *…
How to Mock a Hot Shard Split in Python
Simulate a database hot shard splitting into two shards by key ranges when it exceeds a threshold, with a mock class for testing.
import random
from collections import defaultdict
class HotShardMock:
"""Mock implementation of a hot shard split in a distributed database."""
def __init__(self, shard_id="shard_1", max_entries=5):
self.shard_id = shard_id
self.max_entries = max_entries
self.entries = {}
def ad…
Mock CQRS Read/Write Split in Python
Separate order mutations from queries using a read model and write model to mock CQRS-style separation of concerns.
from dataclasses import dataclass, field
from typing import List, Dict
@dataclass
class Order:
id: int
amount: float
status: str = "pending"
class OrderWriteModel:
"""Handles all mutations (writes) to orders."""
def __init__(self):
self._orders: Dict[int, Order] = {}
self._next…
How to Mock Canary Deployment Traffic Split in Python
Simulate a canary deployment's stable/canary traffic split using deterministic request hashing to mock rollout behavior with precise percentage control.
class CanaryDeployment:
def __init__(self, stable_weight: float = 0.9, canary_weight: float = 0.1):
self.stable_weight = stable_weight
self.canary_weight = canary_weight
self.total_weight = stable_weight + canary_weight
def route_request(self, request_id: int) -> str:
"""Route …
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.