anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Code for snippet for python asyncio example. in Python (v4) | 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}' |
Practical use of snippet for python namedtuple example. in Python (v7) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Understanding Code example: efficient fifo queue python in Python (v3) | 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 does Ignore specific exception work? (v6) | from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt') # no error raised |
Demonstrate mock external dependency python in Python 3. | from unittest.mock import patch, MagicMock
def get_user(user_id):
import requests
return requests.get(f'/users/{user_id}').json()
def test_get_user():
with patch('requests.get') as mock_get:
mock_get.return_value.json.return_value = {'id': 1, 'name': 'Alice'}
result = get_user(1)
a... |
Python Demonstrate how to make class iterable python in complete example | 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 |
Practical use of What is the best way to logical or/and over list p in Python (v8) | 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 |
Common use case of Code example: raise exception inside generator pyt Python (v6) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Python example of Demonstrate concatenate iterables without copying (v8) | 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] |
What is the best way to two-way communication with generator python? | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Python example of Can you show flask route example python example (v9) | 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 : Raise custom exception Python | 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 |
Explain Show me how to python dataclass example in . in Python (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 |
Python example of Priority queue tutorial (v5) | 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) |
Python code showing Write code for how to define __repr__ and __str__ (v9) | 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})' |
Advanced Give me an example of mock external dependency pyt Python example (v10) | from unittest.mock import patch, MagicMock
def get_user(user_id):
import requests
return requests.get(f'/users/{user_id}').json()
def test_get_user():
with patch('requests.get') as mock_get:
mock_get.return_value.json.return_value = {'id': 1, 'name': 'Alice'}
result = get_user(1)
a... |
When to use : asyncio example Python (v6) | 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}' |
Demonstrate non blocking io python asyncio in Python 3. | 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}' |
Practical use of Can you show __repr__ vs __str__ python example in Python (v9) | 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})' |
Write a function to demonstrate snippet for interactive generator python. (v9) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Tutorial on Demonstrate sub-generator delegation python in 3. Python (v4) | 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 3 Demonstrate stable sort python recursive in 3. example code (v8) | 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(... |
Python example of : Trie data structure | 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... |
What is Explain python map filter reduce example with code in Python? (v4) | 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 Explain write tests with pytest with code. (v9) | 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 snippet: Show me how to define get endpoint fastapi in . | 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 snippet: How do I how to get all pairs from two lists pytho (v7) | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
Advanced How do I python path object example Python example (v5) | 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') |
Python : string representation of object complete example (v3) | 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})' |
Understanding Write code for singleton design pattern python ex in Python (v4) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Beginner guide to Demonstrate functools.reduce python in 3. Python (v4) | 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 snippet: Explain and show code to create double ended queue | from collections import deque
recent = deque(maxlen=3)
for i in range(5):
recent.append(i) # deque([2, 3, 4], maxlen=3) |
Beginner guide to Give me an example of mergesort algorithm python. Python (v8) | 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(... |
Practical use of snippet for python mixin example. in Python (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 example: invoke parent __init__ python complete example (v6) | 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!' |
Write a function to demonstrate Show me how to python list comprehension example i (v5) | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
Write a function to demonstrate : Functional operators (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 |
Common use case of Explain test case python with code. Python | import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
def test_divide_zero(self):
with self.assertRaises(ZeroDivisionError):
1 / 0
if __name__ == '__main__':
unittest.main() |
Python code showing Give me an example of python operator module examp (v8) | 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 does python __enter__ __exit__ example look like in Python? | 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.... |
DFS iterative Python | def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited |
How Write code for logical or/and over list python. is implemented in Python (v6) | 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 |
I want to understand python defaultdict example. Python guide (v8) | 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) |
Python snippet for async def python tutorial. complete example (v3) | 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}' |
Python snippet: Give me an example of itertools.combinations examp (v5) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Common use case of Code example: argparse python example Python (v8) | 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 Show me how to how to serialize python objects in work? (v2) | import pickle
data = {'key': [1, 2, 3], 'model': None}
# Save
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Load
with open('data.pkl', 'rb') as f:
loaded = pickle.load(f) |
How I want to understand restrict attributes with __sl is implemented in Python (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 |
Code for Code example: create numpy array python in Python (v3) | import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.arange(5)
c = np.zeros((3, 3))
d = np.ones((2, 4))
print(a * 2) # [2 4 6 8 10]
print(a.mean()) # 3.0
print(a @ a) # dot product = 55 |
Write a function to demonstrate Code example: split join strip python string (v7) | 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)) |
How does Show me how to python functools.partial example in work? (v8) | from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(4)) # 16
print(cube(3)) # 27 |
Python code showing Write code for python __enter__ __exit__ example. (v4) | 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.... |
How Code example: python math.floor ceil round is implemented in Python (v10) | 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 |
Explain Show me how to debug info warning error python log in Python (v5) | 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) |
Write Python code for math functions python. | 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 Demonstrate __len__ and __getitem__ python in 3. complete example (v6) | 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] |
Python example of Give me an example of functional programming pytho (v8) | 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) |
Give me an example of nonlocal keyword python example. | def make_adder(n):
"""Use nonlocal to modify enclosing scope variable."""
total = 0
def add(x):
nonlocal total
total += x + n
return total
return add |
Beginner guide to How do I weak reference python Python (v2) | 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 |
How What is the best way to itertools.combinations exa is implemented in Python (v5) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
What is Give me an example of recursive graph traversal py in Python? (v7) | def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited |
Python example of Code example: make python object printable | 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 3.10 union type hint | | from typing import Union
def to_int(val: Union[str, float, int]) -> int:
"""Convert string, float or int to int."""
return int(val) |
Show me how to python generator error handling in with Python 3 (v4) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Code for define a property with getter setter and deleter i in Python (v4) | class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, val):
if val <= 0:
raise ValueError("Radius must be positive")
self._radius = val
@radius.deleter
def ra... |
Tutorial on Explain convert dict to json python with code. Python (v10) | import json
# Deserialize
with open('data.json') as f:
data = json.load(f)
# Serialize
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
# String operations
text = json.dumps({'key': 'value'})
obj = json.loads(text) |
Common use case of Can you show python rest api with fastapi example Python (v9) | 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 Code example: bottom up dp python is implemented in Python (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 snippet: Explain named tuple python with code. (v2) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Advanced I want to understand hook subclass definition pyth Python example | class Base:
_registry = {}
def __init_subclass__(cls, kind=None, **kw):
super().__init_subclass__(**kw)
if kind:
Base._registry[kind] = cls
class Dog(Base, kind='dog'): pass
class Cat(Base, kind='cat'): pass
print(Base._registry) # {'dog': Dog, 'cat': Cat} |
Python code showing closure example tutorial (v2) | def make_counter(start=0):
"""Closure that maintains a counter."""
count = [start]
def increment(by=1):
count[0] += by
return count[0]
return increment |
What is throw exception into generator tutorial in Python? (v8) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Code for Event listener tutorial 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 showing I want to understand python random module example. (v8) | 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 |
How Code example: dataframe operations python is implemented in Python (v6) | 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 |
How : sys.argv vs argparse is implemented in Python (v9) | 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... |
Advanced I want to understand encapsulate state with closur Python example (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 |
Python snippet: Can you show how to create a closure python exampl (v10) | def make_counter(start=0):
"""Closure that maintains a counter."""
count = [start]
def increment(by=1):
count[0] += by
return count[0]
return increment |
Can you show how to use queue in asyncio python ex with Python 3 (v5) | 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... |
Practical use of How do I parse query parameters and URL components in Python (v7) | from urllib.parse import urlparse, parse_qs
url = 'https://api.example.com/search?q=python&page=2'
parsed = urlparse(url)
params = parse_qs(parsed.query) # {'q': ['python'], 'page': ['2']} |
Explain Simple pytest test in Python (v9) | 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 snippet: Can you show math functions python example (v7) | 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 |
Tutorial on Write code for config from environment python. Python (v9) | 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') |
Code for Show me how to matrix to flat list python in . in Python (v10) | matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [elem for row in matrix for elem in row] |
Practical use of create generator without yield tutorial in Python | # Generator expression - memory efficient
data = range(1_000_000)
total = sum(x**2 for x in data if x % 2 == 0) |
Practical use of Show me how to % formatting python in . in Python (v5) | # 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) |
Common use case of : String interpolation 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}') |
How What does collections.namedtuple tutorial look lik is implemented in Python (v4) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
How do I abstract class python Python guide (v5) | 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... |
Give me an example of nested list comprehension py Python guide (v7) | matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [elem for row in matrix for elem in row] |
Python snippet: : read and write JSON (v8) | import json
# Deserialize
with open('data.json') as f:
data = json.load(f)
# Serialize
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
# String operations
text = json.dumps({'key': 'value'})
obj = json.loads(text) |
Write code for divide and conquer sort python. with Python 3 (v10) | 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) |
Python example of Explain and show code to implement len protocol us (v7) | class CustomCollection:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items) |
Can you show how to copy dict python example with Python 3 (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 |
Write a function to demonstrate random module example tutorial (v10) | 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 |
When to use Mutable default in dataclass Python | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Dictionary from two lists Python tutorial | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
What is test class in Python? (v6) | import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
def test_divide_zero(self):
with self.assertRaises(ZeroDivisionError):
1 / 0
if __name__ == '__main__':
unittest.main() |
Python 3 I want to understand python dataclass list default example code (v2) | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Show me how to collections.ordereddict tutorial in Python guide | from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od.move_to_end('a') # move 'a' to end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.