anchor
stringlengths
13
118
positive
stringclasses
235 values
Write a function to demonstrate : Convert int to bytes struct (v7)
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)
Python code showing snippet for how to read and write json python. (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)
Common use case of Give me an example of python requests library exam Python (v9)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Demonstrate terminate infinite generator python in Python 3.
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Understanding What is the best way to python functools.cache exa in Python (v10)
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)
Tutorial on Show me how to python generator send method exampl Python (v7)
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
What is Demonstrate abstract method python in 3. in Python? (v3)
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 How do I create a retry decorator with maximum att example code (v3)
import time from functools import wraps def retry(max_attempts=3, delay=1.0): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, max_attempts + 1): try: return func(*args, **kwargs) except Exception...
Advanced I want to understand custom addition for python ob Python example (v4)
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})'
How Demonstrate collections.namedtuple tutorial in 3. is implemented in Python (v5)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
When to use Explain find and replace with regex python with co Python (v7)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Beginner guide to Code example: switch statement python Python (v3)
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
Python 3 Demonstrate how to pass data into a paused generat example code (v2)
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 What is the best way to fastapi tutorial python (v10)
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
Advanced Explain insert into sorted list python with code. Python example (v6)
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
Python example of I want to understand force subclass to implement m (v9)
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...
What is How do I stable sort python recursive in Python? (v9)
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(...
Explain What is the best way to debug info warning error p in Python (v7)
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)
Python snippet: Demonstrate map keys to values python one liner in
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Tutorial on What does modify outer variable from inner functio Python (v8)
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
How I want to understand how to group consecutive item is implemented in Python (v10)
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Demonstrate sorted() with key python in 3. with Python 3 (v2)
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)
Understanding What does user defined exception python look like in Python (v9)
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 unittest.mock patch python with code. is implemented in Python (v8)
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...
Common use case of nested function variable tutorial Python (v9)
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
How Best practice to run multiple coroutines concurren is implemented in Python (v5)
import asyncio async def fetch_data(id, delay): await asyncio.sleep(delay) return f"Data {id}" async def main(): results = await asyncio.gather(fetch_data(1, 0.2), fetch_data(2, 0.4)) return results
Explain Explain python chain iterators together with code. in Python
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]
Beginner guide to Mutable default in dataclass tutorial Python (v4)
from dataclasses import dataclass, field @dataclass class Team: name: str members: list = field(default_factory=list) _id: int = field(default=0, repr=False)
Python code showing code to count occurrences of items and find top N (v3)
from collections import Counter words = ['apple', 'banana', 'apple', 'orange', 'apple', 'banana'] counts = Counter(words) most_common = counts.most_common(2) # [('apple', 3), ('banana', 2)]
Advanced Can you show create numpy array python example Python example
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
What is Demonstrate __len__ and __getitem__ python in 3. in Python? (v2)
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 snippet: Explain permission flags python enum with code. (v9)
from enum import Flag, auto class Permission(Flag): READ = auto() WRITE = auto() EXECUTE = auto() ALL = READ | WRITE | EXECUTE user_perm = Permission.READ | Permission.WRITE print(Permission.READ in user_perm) # True
Python Can you show how to get all combinations python ex complete example (v5)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Demonstrate sort list of dicts python in 3. with Python 3 (v4)
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']))
What does find and replace with regex python look Python guide (v9)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Python snippet for magicmock python example. complete 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...
Practical use of Can you show producer consumer asyncio python exam in Python (v9)
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...
How does code to implement binary search algorithm iterativ work? (v4)
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1
Python snippet: Explain duck typing with type hints python with co (v2)
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
What is Write code for memory efficient iteration python. in Python? (v5)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Tutorial on Show me how to most common elements python in . Python (v7)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
How snippet for priority queue python. is implemented in Python (v3)
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)
What is Show me how to __iter__ and __next__ python in . 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 snippet for how to use multiprocessing in python. in Python (v4)
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 Give me an example of multiple inheritance mixin p in Python (v5)
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
How does code to copy move and delete directory tree using work? (v8)
import shutil shutil.copytree('source_dir', 'backup_dir', dirs_exist_ok=True) shutil.rmtree('backup_dir')
How collections.defaultdict tutorial tutorial is implemented in Python
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 is Process large file in Python? (v4)
# 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 snippet: Write code for implement indexing in python class (v9)
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]
Common use case of Explain plugin registration python __init_subclass Python
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}
Explain filter list python with code. with Python 3 (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)
What is Example of how to keep priority queue with min-hea in Python? (v8)
import heapq nums = [5, 1, 9, 3, 7] heapq.heapify(nums) heapq.heappush(nums, 2) smallest = heapq.heappop(nums) # 1 top_three = heapq.nlargest(3, nums)
Python snippet: Write code for take first n items from generator (v9)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Python 3 Can you show take first n items from generator pyt example code (v6)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Code for Example of how to copy move and delete directory t in Python (v5)
import shutil shutil.copytree('source_dir', 'backup_dir', dirs_exist_ok=True) shutil.rmtree('backup_dir')
Common use case of Show me how to how to slice an iterator python in Python
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Code for What is the best way to python math.floor ceil rou in Python (v4)
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
Understanding Demonstrate invoke parent __init__ python in 3. in Python (v7)
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 snippet for structural subtyping python. in Python (v2)
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
Explain What is the best way to how to add type hints in p in Python (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]
Python code showing lru_cache decorator example tutorial (v2)
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 for : O(log n) search in Python (v5)
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
How Show me how to make python object hashable in . is implemented in Python (v8)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
When to use What is the best way to python pytest example Python
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
Common use case of How do I submit tasks to thread pool python Python (v9)
from concurrent.futures import ThreadPoolExecutor, as_completed def fetch(url): import time; time.sleep(0.5) return f'result:{url}' with ThreadPoolExecutor(max_workers=5) as ex: futures = {ex.submit(fetch, url): url for url in ['a','b','c']} for fut in as_completed(futures): print(fut.result()...
Controlled attribute access tutorial Python guide (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 Make object hashable complete example (v3)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
Explain Demonstrate python-dotenv load .env file in 3. in Python (v7)
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')
What is What does __call__ method python look like in in Python?
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 example of snippet for cache expensive function calls python. (v10)
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)
What is the best way to operator.attrgetter sort 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']))
Tutorial on Explain and show code to run I/O bound requests in Python (v4)
from concurrent.futures import ThreadPoolExecutor import urllib.request def fetch(url): with urllib.request.urlopen(url) as r: return r.status urls = ['https://httpbin.org/get'] * 5 with ThreadPoolExecutor(max_workers=5) as pool: statuses = list(pool.map(fetch, urls))
Give me an example of class method that creates instance python.
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(...
Understanding Code example: filter list with comprehension pytho in Python (v3)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Write a function to demonstrate Give me an example of create objects based on type (v7)
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()
Python 3 How do I python logging to file example example code (v5)
import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger('myapp') logger.setLevel(logging.DEBUG) fh = RotatingFileHandler('app.log', maxBytes=1_000_000, backupCount=3) fh.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) logger.addHandler(fh) logger.add...
Python example of I want to understand resume a function from where (v3)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Understanding Example of how to dictionary comprehension with fi in Python (v10)
squares = {x: x**2 for x in range(10) if x % 2 == 0}
Python snippet: Can you show memoization python functools example (v5)
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 for Can you show pydantic model python example example 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...
Python code showing Explain duck typing with type hints python with co (v7)
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
Understanding requests library example in Python (v4)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
When to use : Simple context manager using generator Python
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')
Code for bisect module example tutorial in Python (v4)
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
Beginner guide to Give me an example of sorted() with key python. Python (v8)
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)
Beginner guide to Can you show publish subscribe python example Python (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)
Tutorial on Demonstrate make python object hashable in 3. Python (v9)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
Common use case of Code example: create objects based on type python 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()
Python snippet: Can you show python generator cleanup on close exa (v10)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
How does Demonstrate assert equal python unittest in 3. work? (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 snippet: Parallel processing (v3)
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)
How do I filter list python?
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)
Practical use of Give me an example of how to use property decorato in Python (v4)
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 3 I want to understand *args python example. example code (v5)
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)
Write a function to demonstrate threading.Lock example (v9)
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
When to use Build dictionary with comprehension Python (v6)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Python example of Demonstrate @dataclass decorator python in 3. (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
Python sort lambda example tutorial complete example (v8)
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)
Python: Divide and merge sort Python
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(...
Explain nonlocal keyword example in Python (v2)
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