anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
What is define callback signature with typing.Callable in in Python? (v3) | from typing import Callable
def process_items(items: list[int], func: Callable[[int], int]) -> list[int]:
return [func(x) for x in items] |
Beginner guide to What is the best way to insert into sorted list py Python (v9) | import bisect
sorted_list = [1, 3, 5, 7, 9]
bisect.insort(sorted_list, 4) # insert 4 keeping sorted
pos = bisect.bisect_left(sorted_list, 5) # find position of 5 |
Explain Implement __str__ and __repr__ for custom class re in Python (v2) | class User:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"User(name={self.name!r}, age={self.age!r})"
def __str__(self):
return f"{self.name} ({self.age} years old)" |
Python snippet: Explain sub-generator delegation python with code. (v2) | def flatten(nested):
"""Flatten nested iterables using yield from."""
for item in nested:
if hasattr(item, '__iter__') and not isinstance(item, str):
yield from flatten(item)
else:
yield item |
Python code showing Combine multiple lists itertools tutorial (v7) | import itertools
def chain_all(*iterables):
"""Chain multiple iterables into one using itertools."""
return list(itertools.chain(*iterables))
# Usage: chain_all([1,2], [3,4], [5]) -> [1,2,3,4,5] |
How does Priority queue tutorial work? (v6) | import heapq
nums = [5, 1, 8, 3, 9, 2]
heapq.heapify(nums) # in-place min-heap
smallest = heapq.heappop(nums)
nlargest = heapq.nlargest(3, nums) |
Practical use of What is the best way to interface in python using in Python (v5) | from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()
# Any class with draw() satisfies Drawable without inheritance |
Python 3 Write code for python typing module tutorial. example code (v10) | from typing import List, Dict, Optional, Tuple
def process(items: List[str], config: Dict[str, int]) -> Optional[Tuple[int, str]]:
if not items:
return None
return len(items), items[0] |
Write a function to demonstrate Show me how to how to chain generators using yield (v10) | def flatten(nested):
"""Flatten nested iterables using yield from."""
for item in nested:
if hasattr(item, '__iter__') and not isinstance(item, str):
yield from flatten(item)
else:
yield item |
What does generic type hint python look like in Python? | from typing import TypeVar, Generic, List
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self._items: List[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop() |
Python 3 What does regular expression python look like in example code (v8) | import re
# Find all email addresses
text = 'Contact alice@example.com or bob@test.org'
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text) |
Give me an example of os.environ python example. Python guide (v4) | import os
from dotenv import load_dotenv
load_dotenv() # reads .env file
DB_URL = os.environ['DATABASE_URL']
API_KEY = os.getenv('API_KEY', 'default-key') |
Python example of Write code for force subclass to implement method (v7) | from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
@abstractmethod
def perimeter(self) -> float: ...
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
import math; return math.pi * self.r**2
def perimeter... |
Python 3 Can you show collections.counter tutorial example example code | from collections import Counter
words = 'the quick brown fox jumps over the lazy dog'.split()
counts = Counter(words)
print(counts.most_common(3)) |
Code for I want to understand re.match groups python. in Python (v9) | import re
pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})')
m = pattern.search('Date: 2024-03-15')
if m:
print(m.group('year'), m.group('month'), m.group('day')) |
Python : call parent class method complete example (v5) | class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f'{self.name} makes a sound'
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
return super().speak() + ' - Woof!' |
Python How do I python generator cleanup on close complete example (v7) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Python code showing What does sort objects multiple criteria python lo (v8) | from operator import attrgetter, itemgetter
people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Carol', 'age': 30}]
# Sort by age then name
sorted_people = sorted(people, key=lambda p: (p['age'], p['name'])) |
Explain group by pandas python with code. | import pandas as pd
df = pd.read_csv('data.csv')
# Filter
high_salary = df[df['salary'] > 100_000]
# Group
avg_by_dept = df.groupby('department')['salary'].mean()
# New column
df['bonus'] = df['salary'] * 0.10 |
Advanced Write code for limit iterator output python. Python example (v7) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
What is snippet for python struct module example. in Python? (v2) | import struct
# Pack integers into bytes
packed = struct.pack('>IHH', 2024, 3, 15) # big-endian uint32, uint16, uint16
print(packed)
# Unpack
yr, mo, dy = struct.unpack('>IHH', packed)
print(yr, mo, dy) |
When to use What does singleton design pattern python example Python (v9) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Practical use of snippet for when to use classmethod python. in Python (v7) | class Date:
"""Date class demonstrating classmethod and staticmethod."""
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_string(cls, s):
"""Alternative constructor from 'YYYY-MM-DD' string."""
year, month, day = map(... |
: struct module example Python guide (v8) | import struct
# Pack integers into bytes
packed = struct.pack('>IHH', 2024, 3, 15) # big-endian uint32, uint16, uint16
print(packed)
# Unpack
yr, mo, dy = struct.unpack('>IHH', packed)
print(yr, mo, dy) |
Write a function to demonstrate What is the best way to exceptiongroup python exam (v2) | # Python 3.11+ ExceptionGroup
try:
raise ExceptionGroup('several errors', [
ValueError('bad value'),
TypeError('bad type'),
])
except* ValueError as eg:
print('ValueErrors:', eg.exceptions)
except* TypeError as eg:
print('TypeErrors:', eg.exceptions) |
Write Python code for how to suppress exceptions python. | from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt') # no error raised |
Python snippet: Demonstrate post request python in 3. (v3) | import requests
payload = {'name': 'Alice', 'score': 99}
resp = requests.post('https://api.example.com/submit', json=payload, timeout=10)
resp.raise_for_status()
print(resp.json()) |
Python Close a running generator tutorial complete example (v7) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Beginner guide to enforce timeout on an asynchronous operation using Python (v7) | import asyncio
async def slow_task():
await asyncio.sleep(5)
return "Done"
async def main():
try:
async with asyncio.timeout(1.0):
await slow_task()
except TimeoutError:
print("Task timed out!") |
How do I collections.namedtuple tutorial? | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Common use case of Code example: benchmark function python Python (v4) | import cProfile, pstats, timeit
# Quick benchmark
elapsed = timeit.timeit('sum(range(1000))', number=10_000)
print(f'10k runs: {elapsed:.3f}s')
# Full profiling
cProfile.run('my_function()', 'output.prof')
p = pstats.Stats('output.prof').sort_stats('cumulative')
p.print_stats(10) |
I want to understand python thread class example. | import threading
def worker(name):
print(f'Thread {name} starting')
threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join() |
Tutorial on Code example: python readline example Python (v7) | # Memory-efficient line-by-line reading
with open('large_file.txt', encoding='utf-8') as f:
for line in f:
process(line.rstrip('\n')) |
What is What does pydantic model python example look like in Python? (v9) | from pydantic import BaseModel, Field, validator
from typing import Optional
class User(BaseModel):
name: str
email: str
age: int = Field(gt=0, le=150)
bio: Optional[str] = None
@validator('email')
def email_must_have_at(cls, v):
if '@' not in v:
raise ValueError('invalid e... |
Advanced Give me an example of assignment expression python Python example (v3) | # Walrus operator: assign and use in same expression
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered = [y for x in data if (y := x**2) > 25] |
Write Python code for lazy list comprehension python. | # Generator expression - memory efficient
data = range(1_000_000)
total = sum(x**2 for x in data if x % 2 == 0) |
When to use Show me how to mutex python threading in . Python (v2) | import threading
class SafeCounter:
"""Thread-safe counter using Lock."""
def __init__(self):
self._value = 0
self._lock = threading.Lock()
def increment(self):
with self._lock:
self._value += 1
@property
def value(self):
return self._value |
Python 3 Demonstrate quicksort algorithm python in 3. example code (v3) | def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right) |
Advanced Explain how to use list comprehension python with Python example (v10) | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
Practical use of Explain factory design pattern python with code. in Python (v2) | class AnimalFactory:
@staticmethod
def create(kind: str):
animals = {'dog': Dog, 'cat': Cat, 'bird': Bird}
cls = animals.get(kind)
if cls is None:
raise ValueError(f'Unknown animal: {kind}')
return cls() |
Write code for replace pattern in string python. with Python 3 (v6) | import re
text = 'Hello World Python'
# Replace multiple spaces with single space
cleaned = re.sub(r'\s+', ' ', text.strip()) |
Write Python code for unique values comprehension python. | # Set comprehension: unique first letters
words = ['apple', 'avocado', 'banana', 'blueberry']
first_letters = {w[0] for w in words} |
Code for How do I calculate greatest common divisor and lea in Python (v9) | import math
def gcd_lcm(a, b):
g = math.gcd(a, b)
l = math.lcm(a, b)
return {'gcd': g, 'lcm': l} |
How does : enumerate example work? (v9) | names = ['Alice', 'Bob', 'Carol']
scores = [95, 87, 92]
# zip: pair elements
for name, score in zip(names, scores):
print(f'{name}: {score}')
# enumerate: add index
for i, name in enumerate(names, start=1):
print(f'{i}. {name}') |
Python code showing snippet for enumeration class python. (v10) | from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
print(Color.RED) # Color.RED
print(Color.RED.value) # 1
for color in Color:
print(color.name) |
Understanding What is the best way to how to sort list by custom in Python | people = [('Alice', 30), ('Bob', 25), ('Carol', 35)]
# Sort by age ascending
by_age = sorted(people, key=lambda p: p[1])
# Sort by name descending
by_name_desc = sorted(people, key=lambda p: p[0], reverse=True) |
Write code for generator function that pauses exe Python guide | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
When to use Demonstrate pydantic model python example in 3. Python (v2) | from pydantic import BaseModel, Field, validator
from typing import Optional
class User(BaseModel):
name: str
email: str
age: int = Field(gt=0, le=150)
bio: Optional[str] = None
@validator('email')
def email_must_have_at(cls, v):
if '@' not in v:
raise ValueError('invalid e... |
Python snippet: Demonstrate python rest api with fastapi in 3. (v8) | from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.get('/items/{item_id}')
def get_item(item_id: int):
return {'id': item_id}
@app.post('/items/')
def create_item(item: Item):
return item |
Python example of What is the best way to how to use dataclass in py (v3) | from dataclasses import dataclass
@dataclass
class Employee:
name: str
department: str
salary: float = 50000.0
def raise_salary(self, percent: float):
self.salary *= 1 + percent / 100 |
Write code for bfs algorithm python. with Python 3 (v5) | from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
... |
What is I want to understand square root python. in Python? (v9) | import math
print(math.sqrt(16)) # 4.0
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(math.log(100, 10)) # 2.0
print(math.pi, math.e) # constants
print(math.factorial(5)) # 120 |
Python example of What is the best way to how to make python object (v3) | class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 |
Tutorial on What does with statement custom class python look Python (v8) | class ManagedFile:
"""Custom context manager for file handling."""
def __init__(self, name, mode):
self.name = name
self.mode = mode
def __enter__(self):
self.file = open(self.name, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.... |
Understanding What does itertools.chain example python look like in Python (v4) | import itertools
def chain_all(*iterables):
"""Chain multiple iterables into one using itertools."""
return list(itertools.chain(*iterables))
# Usage: chain_all([1,2], [3,4], [5]) -> [1,2,3,4,5] |
When to use : *args example Python (v9) | def display(*args, **kwargs):
for arg in args:
print(arg)
for key, val in kwargs.items():
print(f'{key}={val}')
params = [1, 2, 3]
opts = {'sep': ', ', 'end': '\n'}
display(*params, **opts) |
When to use What does argparse python example look like in Python (v10) | import argparse
parser = argparse.ArgumentParser(description='My CLI tool')
parser.add_argument('input', help='Input file path')
parser.add_argument('-o', '--output', default='out.txt', help='Output file')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
print(args.input, args.ou... |
Python code showing Notify subscribers tutorial (v8) | class EventEmitter:
def __init__(self):
self._listeners = {}
def on(self, event, callback):
self._listeners.setdefault(event, []).append(callback)
def emit(self, event, *args, **kwargs):
for cb in self._listeners.get(event, []):
cb(*args, **kwargs) |
How does What does with statement custom class python look work? (v3) | class ManagedFile:
"""Custom context manager for file handling."""
def __init__(self, name, mode):
self.name = name
self.mode = mode
def __enter__(self):
self.file = open(self.name, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.... |
Practical use of Best practice to chain exceptions using raise from in Python | class AppError(Exception): pass
try:
val = int("invalid")
except ValueError as err:
raise AppError("Failed to parse configuration") from err |
When to use Can you show implement for loop support in python Python (v8) | class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
self.current = self.start
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1 |
Tutorial on Can you show submit form data python requests exam Python (v10) | import requests
payload = {'name': 'Alice', 'score': 99}
resp = requests.post('https://api.example.com/submit', json=payload, timeout=10)
resp.raise_for_status()
print(resp.json()) |
Python 3 Give me an example of callback registration python example code (v2) | class EventEmitter:
def __init__(self):
self._listeners = {}
def on(self, event, callback):
self._listeners.setdefault(event, []).append(callback)
def emit(self, event, *args, **kwargs):
for cb in self._listeners.get(event, []):
cb(*args, **kwargs) |
Explain collections.deque python tutorial with cod with Python 3 (v7) | from collections import deque
dq = deque(maxlen=5) # fixed-size circular buffer
for i in range(10):
dq.append(i)
print(dq) # deque([5, 6, 7, 8, 9], maxlen=5) |
Python What is the best way to make python object printab complete example | class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x!r}, {self.y!r})'
def __str__(self):
return f'({self.x}, {self.y})' |
Beginner guide to Give me an example of implement quicksort python. Python (v3) | def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right) |
Explain memoization python functools with code. | from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
"""Compute nth Fibonacci number using memoization."""
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2) |
Code example: singleton pattern python | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Python code showing os.environ example (v5) | import os
from dotenv import load_dotenv
load_dotenv() # reads .env file
DB_URL = os.environ['DATABASE_URL']
API_KEY = os.getenv('API_KEY', 'default-key') |
Python Demonstrate enumerate python example in 3. complete example (v9) | names = ['Alice', 'Bob', 'Carol']
scores = [95, 87, 92]
# zip: pair elements
for name, score in zip(names, scores):
print(f'{name}: {score}')
# enumerate: add index
for i, name in enumerate(names, start=1):
print(f'{i}. {name}') |
Write a function to demonstrate : What is a closure in (v9) | def make_counter(start=0):
"""Closure that maintains a counter."""
count = [start]
def increment(by=1):
count[0] += by
return count[0]
return increment |
Practical use of Demonstrate regex groups python in 3. in Python (v2) | import re
pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})')
m = pattern.search('Date: 2024-03-15')
if m:
print(m.group('year'), m.group('month'), m.group('day')) |
Advanced How do I breadth first search traversal on graph a Python example (v2) | from collections import deque
def bfs(graph, root):
visited = {root}
q = deque([root])
order = []
while q:
node = q.popleft()
order.append(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
q.a... |
Binary search algorithm tutorial with Python 3 (v3) | def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1 |
Practical use of What does python threading example look like in in Python (v9) | import threading
def worker(name):
print(f'Thread {name} starting')
threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join() |
Write a function to demonstrate snippet for @property python class example. (v9) | class Temperature:
"""Temperature class with Celsius/Fahrenheit via @property."""
def __init__(self, celsius=0):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise Val... |
Python code showing Format and inspect exception stack trace with trac (v3) | import traceback
try:
1 / 0
except ZeroDivisionError:
error_msg = traceback.format_exc()
print(f"Captured traceback:\n{error_msg}") |
Advanced Code example: how to slice an iterator python Python example (v7) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Common use case of use Lock in threading Python (v5) | import threading
class SafeCounter:
"""Thread-safe counter using Lock."""
def __init__(self):
self._value = 0
self._lock = threading.Lock()
def increment(self):
with self._lock:
self._value += 1
@property
def value(self):
return self._value |
Tutorial on Show me how to multiple inheritance mixin python i Python (v8) | class SerializeMixin:
def to_dict(self):
return self.__dict__
def to_json(self):
import json
return json.dumps(self.to_dict())
class User(SerializeMixin):
def __init__(self, name, email):
self.name = name
self.email = email |
Python 3 Write code for how to read environment variables example code (v2) | import os
from dotenv import load_dotenv
load_dotenv() # reads .env file
DB_URL = os.environ['DATABASE_URL']
API_KEY = os.getenv('API_KEY', 'default-key') |
: gather coroutines result with Python 3 (v8) | import asyncio
async def main():
"""Run tasks concurrently with asyncio.gather."""
results = await asyncio.gather(
fetch('http://api1.com'),
fetch('http://api2.com'),
fetch('http://api3.com'),
)
return results |
Understanding What is the best way to f string with expressions in Python (v7) | name = 'Alice'
age = 30
pi = 3.14159
# Basic
print(f'Hello, {name}!')
# Expression
print(f'In 5 years: {age + 5}')
# Format spec
print(f'Pi = {pi:.2f}')
# Repr
print(f'{name!r}') |
Common use case of Write code for implement merge sort python. Python (v2) | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(l, r):
result = []
i = j = 0
while i < len(l) and j < len(r):
if l[i] <= r[j]:
result.append(... |
Common use case of Explain and show code to define structural protoco Python (v3) | from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable):
obj.draw() |
Write a function to demonstrate Demonstrate default value dict python in 3. (v7) | from collections import defaultdict
# Group words by first letter
words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry']
groups = defaultdict(list)
for word in words:
groups[word[0]].append(word) |
Tutorial on : Thread class example Python (v6) | import threading
def worker(name):
print(f'Thread {name} starting')
threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join() |
Python example of CLI argument parser tutorial | import argparse
parser = argparse.ArgumentParser(description='My CLI tool')
parser.add_argument('input', help='Input file path')
parser.add_argument('-o', '--output', default='out.txt', help='Output file')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
print(args.input, args.ou... |
How does Code example: reusable mixin class python work? (v3) | class SerializeMixin:
def to_dict(self):
return self.__dict__
def to_json(self):
import json
return json.dumps(self.to_dict())
class User(SerializeMixin):
def __init__(self, name, email):
self.name = name
self.email = email |
Python code showing Demonstrate two-way communication with generator p | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Show me how to python web app flask in Python. | from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def hello():
name = request.args.get('name', 'World')
return jsonify({'message': f'Hello, {name}!'}) |
Tutorial on snippet for python copy vs deepcopy. Python (v4) | import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(original) # nested lists still shared
deep = copy.deepcopy(original) # fully independent copy
deep[0][0] = 99
print(original[0][0]) # still 1 |
Common use case of : type annotation example Python (v5) | from typing import List, Dict, Optional, Tuple
def process(items: List[str], config: Dict[str, int]) -> Optional[Tuple[int, str]]:
if not items:
return None
return len(items), items[0] |
Practical use of Show me how to python counter example in . in Python (v3) | from collections import Counter
words = 'the quick brown fox jumps over the lazy dog'.split()
counts = Counter(words)
print(counts.most_common(3)) |
How collections.OrderedDict tutorial tutorial is implemented in Python (v6) | from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od.move_to_end('a') # move 'a' to end |
How does Show me how to how to slice an iterator python in work? (v7) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Python snippet: Demonstrate how to use queue in asyncio python in (v6) | import asyncio
async def producer(queue):
for i in range(5):
await queue.put(i)
await asyncio.sleep(0.1)
async def consumer(queue):
while True:
item = await queue.get()
print(f'Consumed {item}')
queue.task_done()
async def main():
q = asyncio.Queue()
await asyn... |
Python 3 Demonstrate memory efficient file reading python i example code (v7) | # Memory-efficient line-by-line reading
with open('large_file.txt', encoding='utf-8') as f:
for line in f:
process(line.rstrip('\n')) |
Python re module example tutorial | import re
# Find all email addresses
text = 'Contact alice@example.com or bob@test.org'
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text) |
What is What does python lazy slicing of infinite sequence in Python? | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.