anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
How Autocomplete data structure is implemented in Python (v8) | class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end... |
Write a function to demonstrate Multithreading tutorial (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() |
Beginner guide to Thread synchronization using threading.Lock Python (v6) | import threading
lock = threading.Lock()
counter = 0
def increment():
global counter
with lock:
counter += 1 |
Python 3 Explain python getter setter using property with c example code (v8) | 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... |
Advanced How do I descriptor protocol python Python example (v2) | class Positive:
"""Descriptor that enforces positive values."""
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
return getattr(obj, f'_{self.name}', None)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f'{s... |
Beginner guide to snippet for stable sort python recursive. Python (v6) | 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(... |
How do I bfs algorithm python Python guide (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)
... |
Write a function to demonstrate snippet for faster than lambda python. (v2) | from operator import itemgetter, attrgetter, mul
from functools import reduce
items = [('apple', 3), ('banana', 1), ('cherry', 2)]
sorted_items = sorted(items, key=itemgetter(1))
product = reduce(mul, [1, 2, 3, 4, 5]) # 120 |
What is Code example: python gather coroutines result in Python? (v10) | 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 |
Python example of use __slots__ in (v5) | class Point:
__slots__ = ('x', 'y') # restrict to only x, y
def __init__(self, x, y):
self.x = x
self.y = y
# No __dict__ => saves memory for millions of instances |
Tutorial on What is the best way to call instance like a funct Python (v4) | class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 |
Python 3 create asyncio Task tutorial example code (v8) | import asyncio
async def background_work():
await asyncio.sleep(2)
print('Done')
async def main():
"""Create and schedule a background task."""
task = asyncio.create_task(background_work())
print('Task created, doing other work')
await task |
Advanced snippet for avoid keyerror python dictionary. Python example (v6) | 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) |
What does terminate infinite generator python look like in Python? | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Write code for what is a decorator in python. Python guide | from functools import wraps
def my_decorator(func):
"""Simple decorator that prints before and after."""
@wraps(func)
def wrapper(*args, **kwargs):
print('Before call')
result = func(*args, **kwargs)
print('After call')
return result
return wrapper |
Give me an example of python mixin example. Python guide (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 example of Show me how to submit form data python requests in (v8) | 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()) |
I want to understand fibonacci with dynamic progra Python guide (v4) | def fib_dp(n):
"""Fibonacci via bottom-up dynamic programming."""
if n < 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n] |
Python example of What does combine multiple lists python itertools (v2) | 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] |
Explain Can you show random sample python example in Python (v6) | import random
print(random.randint(1, 100)) # integer [1, 100]
print(random.random()) # float [0, 1)
print(random.choice(['a','b','c'])) # pick one
lst = list(range(10))
random.shuffle(lst) # in-place shuffle
sample = random.sample(lst, 3) # 3 unique picks |
Code for Give me an example of how to chain generators usin in Python | 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 Write code for factory design pattern python. (v10) | 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() |
How Show me how to create directory python pathlib in is implemented in Python (v3) | from pathlib import Path
base = Path.home() / 'projects' / 'myapp'
base.mkdir(parents=True, exist_ok=True)
# List all .py files recursively
py_files = list(base.rglob('*.py'))
# Read / write
(base / 'config.txt').write_text('setting=value') |
Understanding Code example: notify subscribers python in Python (v9) | 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) |
Python code to safely write to temporary file using tempf complete example (v2) | import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as tmp:
tmp.write('temporary data')
tmp.seek(0)
content = tmp.read() |
Python snippet: Demonstrate python re module example in 3. (v8) | import re
# Find all email addresses
text = 'Contact alice@example.com or bob@test.org'
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text) |
Beginner guide to : Deep copy Python (v8) | 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 |
What is Write code for write to file python. in Python? (v10) | # Read entire file
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
# Write to file
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!') |
Beginner guide to snippet for python yield from usage. Python (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 |
Explain snippet for unique values comprehension python. in Python (v7) | # Set comprehension: unique first letters
words = ['apple', 'avocado', 'banana', 'blueberry']
first_letters = {w[0] for w in words} |
Beginner guide to Write code for python gather coroutines result. Python | 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 |
Advanced Write code for binary search algorithm python. Python example (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 |
Tutorial on Write code for how to use dataclass in python. Python (v2) | 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 |
What is Write code for enumerate python example. in Python? (v8) | 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}') |
Tutorial on Show me how to replace pattern in string python in Python (v4) | import re
text = 'Hello World Python'
# Replace multiple spaces with single space
cleaned = re.sub(r'\s+', ' ', text.strip()) |
Tutorial on Variance statistics tutorial Python (v7) | import statistics as stats
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(stats.mean(data)) # 5.0
print(stats.median(data)) # 4.5
print(stats.mode(data)) # 4
print(stats.stdev(data)) # 2.0 |
Explain python lazy evaluation with yield with code. | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Python Explain weakvaluedictionary python with code. complete example (v5) | import weakref
class Node:
def __init__(self, val):
self.val = val
self.parent = None # strong reference would cause cycle
parent = Node(1)
child = Node(2)
child.parent = weakref.ref(parent) # weak reference
# Access: child.parent() returns None if parent was GC'd |
Python example of Write code for functional operators python. (v9) | from operator import itemgetter, attrgetter, mul
from functools import reduce
items = [('apple', 3), ('banana', 1), ('cherry', 2)]
sorted_items = sorted(items, key=itemgetter(1))
product = reduce(mul, [1, 2, 3, 4, 5]) # 120 |
Advanced Code example: python open file example Python example (v2) | # Read entire file
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
# Write to file
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!') |
Code example: how to split string python with Python 3 | s = ' Hello, World! '
print(s.strip()) # remove whitespace
print(s.lower()) # to lowercase
print(s.upper()) # to uppercase
print(s.replace('World', 'Python'))
words = s.strip().split(', ')
print('|'.join(words)) |
Common use case of snippet for python decorator with arguments. Python (v5) | from functools import wraps
def repeat(n):
"""Decorator factory: repeat function n times."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return ... |
What is Explain decorator factory python with code. in Python? (v8) | from functools import wraps
def repeat(n):
"""Decorator factory: repeat function n times."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return ... |
Python code showing What is the best way to flask get post route (v8) | 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}!'}) |
When to use : Validate attribute with descriptor Python (v8) | class Positive:
"""Descriptor that enforces positive values."""
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
return getattr(obj, f'_{self.name}', None)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f'{s... |
Advanced implement __str__ and __repr__ for custom class re Python example (v10) | 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 code showing Give me an example of iterate two lists simultaneo (v8) | 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 snippet: Demonstrate python group adjacent equal elements i (v6) | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
Understanding What does consecutive grouping python look like in in Python (v9) | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
Code for What is the best way to old style string formattin in Python (v9) | # str.format
msg = 'Hello, {}! You are {} years old.'.format('Alice', 30)
# Named placeholders
msg2 = '{name} scored {score:.1f}%'.format(name='Bob', score=92.5)
# % style
msg3 = 'Value: %d, Float: %.2f' % (42, 3.14) |
Understanding Give me an example of python enum example. in Python (v6) | 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) |
Code for Demonstrate implement indexing in python class in in Python (v7) | class MyList:
def __init__(self, data):
self._data = list(data)
def __len__(self):
return len(self._data)
def __getitem__(self, index):
return self._data[index] |
Practical use of I want to understand lightweight data object pytho in Python (v10) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
How Show me how to how to create custom exception pyth is implemented in Python (v3) | class ValidationError(Exception):
"""Raised when input validation fails."""
def __init__(self, field: str, msg: str):
self.field = field
super().__init__(f'{field}: {msg}')
class NetworkError(RuntimeError):
"""Raised on network failures."""
pass |
How Explain collections.counter tutorial with code. is implemented in Python (v6) | from collections import Counter
words = 'the quick brown fox jumps over the lazy dog'.split()
counts = Counter(words)
print(counts.most_common(3)) |
Write a function to demonstrate Show me how to bottom up dp python in . (v6) | def fib_dp(n):
"""Fibonacci via bottom-up dynamic programming."""
if n < 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n] |
Python code showing make a class a decorator tutorial (v2) | class CountCalls:
"""Class-based decorator that counts function calls."""
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs) |
What is snippet for define get endpoint fastapi. in Python? | 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 |
How Example of how to define Pydantic BaseModel with f is implemented in Python (v6) | from pydantic import BaseModel, Field, field_validator
class User(BaseModel):
id: int
email: str
age: int = Field(ge=0, le=120)
@field_validator('email')
def validate_email(cls, v):
if '@' not in v:
raise ValueError('Invalid email')
return v |
Practical use of Code example: sort list of dicts python in Python | 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'])) |
Python example of Can you show build dictionary with comprehension e (v2) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
How I want to understand implement trie python. is implemented in Python (v6) | class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end... |
Write a function to demonstrate : Catch multiple exceptions (v4) | def divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
raise ValueError('b cannot be zero') from e
except TypeError:
raise
else:
print('Success')
finally:
print('Always runs') |
What is : Debug info warning error logging in Python? (v6) | import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(name)s: %(message)s'
)
logger = logging.getLogger(__name__)
logger.info('Application started')
logger.warning('Low memory')
logger.error('Failed to connect', exc_info=True) |
Common use case of Explain and show code to combine multiple dictiona Python (v4) | from collections import ChainMap
default_cfg = {'theme': 'light', 'timeout': 30}
user_cfg = {'timeout': 60}
cfg = ChainMap(user_cfg, default_cfg)
print(cfg['timeout']) # 60 |
Python code showing How do I implement two pointers two sum solution o (v8) | def two_sum_sorted(nums, target):
i, j = 0, len(nums) - 1
while i < j:
s = nums[i] + nums[j]
if s == target: return [i, j]
elif s < target: i += 1
else: j -= 1
return [] |
How does Give me an example of run cpu bound tasks in paral work? (v8) | from multiprocessing import Pool
def square(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
results = p.map(square, range(10))
print(results) |
Explain Double ended queue in Python (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 example of Write code for python higher order function decor (v6) | from functools import wraps
def my_decorator(func):
"""Simple decorator that prints before and after."""
@wraps(func)
def wrapper(*args, **kwargs):
print('Before call')
result = func(*args, **kwargs)
print('After call')
return result
return wrapper |
What is the best way to python __enter__ __exit__ example? | 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.... |
Code for Show me how to simple pytest test python in . in Python (v2) | import pytest
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
@pytest.mark.parametrize('a,b,expected', [(1,2,3),(0,0,0),(-1,1,0)])
def test_add_parametric(a, b, expected):
assert add(a, b) == expected |
Code for Show me how to named constants python enum in . in Python (v7) | 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) |
When to use What is the best way to how to make a class a deco Python (v4) | class CountCalls:
"""Class-based decorator that counts function calls."""
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs) |
Beginner guide to Code example: old style string formatting python Python (v8) | # str.format
msg = 'Hello, {}! You are {} years old.'.format('Alice', 30)
# Named placeholders
msg2 = '{name} scored {score:.1f}%'.format(name='Bob', score=92.5)
# % style
msg3 = 'Value: %d, Float: %.2f' % (42, 3.14) |
What is How do I benchmark function python in Python? (v6) | 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) |
What does custom print for python class look like Python guide (v2) | 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})' |
Python Code example: efficient fifo queue python complete example (v4) | 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) |
How Demonstrate how to make class iterable python in is implemented in Python (v10) | 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 |
Code for Demonstrate python type annotation example in 3. in Python (v2) | 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] |
How does What does auto generate __init__ python look like work? (v8) | 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 |
How Write code for pytest fixture python. is implemented in Python (v5) | import pytest
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
@pytest.mark.parametrize('a,b,expected', [(1,2,3),(0,0,0),(-1,1,0)])
def test_add_parametric(a, b, expected):
assert add(a, b) == expected |
Python example of Accept multiple types function tutorial (v9) | from typing import Union
def to_int(val: Union[str, float, int]) -> int:
"""Convert string, float or int to int."""
return int(val) |
Give me an example of generator based context mana with Python 3 (v5) | from contextlib import contextmanager
@contextmanager
def timer(label=''):
"""Context manager that times a block."""
import time
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f'{label}: {elapsed:.4f}s') |
Common use case of Best practice to create a closure that maintains s Python (v5) | def make_counter(start=0):
count = start
def step():
nonlocal count
count += 1
return count
return step |
Explain What is the best way to __add__ python example in Python (v10) | class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f'Vector({self.x}, {self.y})' |
Code for Explain super() in inheritance python with code. in Python (v10) | 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!' |
Practical use of What is the best way to avoid circular reference p in Python (v8) | import weakref
class Node:
def __init__(self, val):
self.val = val
self.parent = None # strong reference would cause cycle
parent = Node(1)
child = Node(2)
child.parent = weakref.ref(parent) # weak reference
# Access: child.parent() returns None if parent was GC'd |
: any() all() with Python 3 | nums = [2, 4, 6, 8, 10]
print(all(n % 2 == 0 for n in nums)) # True - all even
print(any(n > 9 for n in nums)) # True - at least one > 9 |
Practical use of Show me how to dataclasses.field python example in in Python (v8) | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Write a function to demonstrate Can you show asynchronous function python example | import asyncio
async def fetch_data(url: str) -> str:
"""Simulate async HTTP fetch."""
await asyncio.sleep(1) # simulate network delay
return f'Data from {url}' |
I want to understand efficient search sorted list python. | 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 |
Python example of Best practice to use pathlib.Path for cross platfo (v6) | from pathlib import Path
base = Path('/var/log')
log_file = base / 'app' / 'server.log'
log_file.parent.mkdir(parents=True, exist_ok=True)
if log_file.exists():
content = log_file.read_text(encoding='utf-8') |
Common use case of Explain group by pandas python with code. Python (v2) | 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 |
Code for Simple data container in Python (v4) | 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 |
Explain What does filter list python look like in in Python (v10) | from functools import reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
total = reduce(lambda a, b: a + b, nums) |
Python code showing What is the best way to sort by multiple keys pyth (v9) | 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'])) |
Common use case of : Validate attribute with descriptor Python (v7) | class Positive:
"""Descriptor that enforces positive values."""
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
return getattr(obj, f'_{self.name}', None)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f'{s... |
How does How do I interface python abc module work? | 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... |
When to use Example of how to calculate greatest common diviso Python (v9) | import math
def gcd_lcm(a, b):
g = math.gcd(a, b)
l = math.lcm(a, b)
return {'gcd': g, 'lcm': l} |
Practical use of Give me an example of invoke parent __init__ pytho in Python | 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!' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.