anchor
stringlengths
13
118
positive
stringclasses
235 values
Demonstrate super() python example in 3. with Python 3 (v8)
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 Explain profile python code performance with code. in Python (v8)
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)
Common use case of : generator error handling Python (v5)
def safe_gen(): """Generator that handles injected exceptions.""" try: while True: yield except ValueError as e: print(f'Caught: {e}') yield 'recovered'
Code for Demonstrate how to stop a generator python in 3. in Python (v7)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Python snippet: Can you show generator.throw() method python examp (v10)
def safe_gen(): """Generator that handles injected exceptions.""" try: while True: yield except ValueError as e: print(f'Caught: {e}') yield 'recovered'
Python snippet: Explain ordereddict python example with code. (v2)
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od.move_to_end('a') # move 'a' to end
Explain How do I python threading.lock example in Python
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 Code example: generate random number python Python (v9)
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
Understanding Write code for invoke parent __init__ python. 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!'
Python code showing Give me an example of what is a closure in python. (v5)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
When to use How do I handle multiple exceptions at once python Python (v5)
# 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)
Advanced Can you show asyncio.gather python example example Python example (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
How to chain multiple iterables together using itertools.chain
import itertools def combine_lists(list_a, list_b, list_c): """Chain multiple collections into a single continuous iterator.""" return list(itertools.chain(list_a, list_b, list_c))
Understanding : type() as metaclass in Python (v9)
class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class Config(metaclass=SingletonMeta): def __init__(self): self.debug = False
Python code showing Explain generic function python typing with code. (v2)
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 code to define modern typed dataclass with default complete example (v7)
from dataclasses import dataclass, field @dataclass class Config: host: str = 'localhost' port: int = 8080 endpoints: list[str] = field(default_factory=list)
Python example of Demonstrate readable tuple python in 3. (v3)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
When to use itertools.groupby example tutorial Python (v10)
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Python 3 Explain string template python with code. example code (v10)
# 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 How do I parse query parameters and URL components in Python (v2)
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']}
Beginner guide to What does generic function python typing look like Python (v2)
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()
Explain Only one instance of class in Python (v3)
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 What is the best way to concatenate iterables with Python (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]
Advanced frozen dataclass example Python example (v6)
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float p = Point(1.0, 2.0) # p.x = 3.0 # raises FrozenInstanceError
Beginner guide to snippet for abc python example. Python (v6)
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...
Understanding : Prefix tree in Python (v3)
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...
Understanding snippet for raise exception inside generator pytho in Python (v2)
def safe_gen(): """Generator that handles injected exceptions.""" try: while True: yield except ValueError as e: print(f'Caught: {e}') yield 'recovered'
I want to understand most common elements python.
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
Advanced Show me how to multithreading python tutorial in . Python example (v7)
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 snippet: Explain immutable dataclass python with code. (v2)
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float p = Point(1.0, 2.0) # p.x = 3.0 # raises FrozenInstanceError
I want to understand how to suppress exceptions python.
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
Write a function to demonstrate Example of how to write a decorator that validates (v6)
from functools import wraps def enforce_types(**expected_types): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for name, val in kwargs.items(): if name in expected_types and not isinstance(val, expected_types[name]): raise TypeError(...
Beginner guide to Code example: hashable dataclass python Python
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float p = Point(1.0, 2.0) # p.x = 3.0 # raises FrozenInstanceError
What is the best way to __add__ python example?
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})'
What is Can you show publish subscribe python example in Python? (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)
Python How do I pandas read csv python complete example (v5)
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
Can you show callable class python example?
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
What is snippet for divide and merge sort python. in Python? (v5)
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(...
Advanced Example of how to create lightweight tuple with na Python example (v9)
from collections import namedtuple Coordinate = namedtuple('Coordinate', ['lat', 'lon']) pt = Coordinate(lat=37.77, lon=-122.41) print(pt.lat, pt.lon)
Custom print for class tutorial Python guide (v4)
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})'
Explain Show me how to simple rest api flask python in . in Python (v10)
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}!'})
How does Show me how to how to use __slots__ in python in . work? (v2)
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 Demonstrate function wrapper python in 3. in Python (v7)
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
Python snippet: Give me an example of ensure single instance pytho (v6)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Tutorial on What does find slow code python look like in Python (v5)
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)
Python 3 Code example: convert dict to json python example code (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)
Understanding Can you show pickle dump and load python example in Python (v4)
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)
Python 3 Write code for how to get all combinations python example code (v10)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
How How do I handle multiple exceptions at once python is implemented in Python (v6)
# 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)
How Code example: how to call parent class method pyth is implemented in Python (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!'
Explain Code example: python path object example 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')
Advanced Explain priority queue python with code. Python example
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)
When to use Write code for force subclass to implement method 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...
Practical use of What is the best way to collections.namedtuple tut in Python (v10)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
When to use What is the best way to dataclass field with defau 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)
Tutorial on Optional vs Union tutorial Python (v10)
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
What is Show me how to log messages python in . in Python? (v2)
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)
When to use Write code for how to sort list by custom key pyt Python (v3)
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)
snippet for parametrized decorator python. with Python 3 (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 ...
I want to understand spread operator python. Python guide (v6)
first, *middle, last = [1, 2, 3, 4, 5] print(first, last) # 1 5 print(middle) # [2, 3, 4] # Merge dicts Python 3.9+ a = {'x': 1} b = {'y': 2} c = {**a, **b} # {'x': 1, 'y': 2}
Practical use of How do I find key with maximum value in dictionary in Python (v4)
scores = {'math': 88, 'physics': 95, 'chemistry': 91} top_subject = max(scores, key=scores.get)
What is the best way to python generator send meth Python guide (v8)
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 run multiple coroutines concurrentl with Python 3 (v9)
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
When to use Write code for priority queue python. 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)
Tutorial on snippet for http get with headers python. Python (v8)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Python snippet for python closure example.
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
Write a function to demonstrate I want to understand **kwargs python example. (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)
Advanced What does autocomplete data structure python look Python example (v9)
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...
Python code showing Explain binary search python with code. (v8)
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
Common use case of snippet for find and replace with regex python. Python (v2)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
What is What does controlled attribute access python look in Python? (v6)
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...
Explain find n smallest python with code.
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 snippet for unpack list as function arguments python.
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)
Python snippet: What is the best way to recursive graph traversal (v2)
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
Beginner guide to How do I square root python 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
Understanding What does one liner list transformation python loo in Python (v9)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
How What does python web app flask look like in is implemented in Python (v6)
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}!'})
How does How do I shortest path unweighted graph python work? (v6)
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) ...
How does Code example: reduce python object memory work? (v9)
import sys class WithDict: def __init__(self, x, y): self.x, self.y = x, y class WithSlots: __slots__ = ('x', 'y') def __init__(self, x, y): self.x, self.y = x, y print(sys.getsizeof(WithDict(1,2))) # ~48 bytes print(sys.getsizeof(WithSlots(1,2))) # ~32 bytes
Explain Add behaviour with mixin tutorial in Python (v2)
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 to specify union and optional type annotations in Python 3.10+ in Python
def parse_id(val: int | str | None) -> str: if val is None: return 'anonymous' return str(val)
What is How do I **kwargs python example in Python? (v6)
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)
How Example of how to memoize function output with fun is implemented in Python (v2)
from functools import lru_cache @lru_cache(maxsize=128) def slow_fibonacci(n): if n < 2: return n return slow_fibonacci(n - 1) + slow_fibonacci(n - 2)
Code for Show me how to functional programming python in . in Python (v6)
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)
Beginner guide to How do I implement indexing in python class Python (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]
Advanced Write code for stateful decorator python using cl Python example (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)
Python example of ProcessPoolExecutor example tutorial (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)
Python snippet: Inject error into generator (v8)
def safe_gen(): """Generator that handles injected exceptions.""" try: while True: yield except ValueError as e: print(f'Caught: {e}') yield 'recovered'
Beginner guide to How do I binary search algorithm python Python (v10)
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
What is call parent class method in Python? (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!'
How does Show me how to python walrus operator example in . work? (v2)
# 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]
Advanced Write code for how to parse command line argument Python example (v4)
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...
When to use Regex groups tutorial Python (v7)
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'))
Explain Give me an example of how to use yield in python. in Python (v9)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Python example of Write code for find and replace with regex python (v8)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
When to use Can you show how to use queue in asyncio python ex Python (v8)
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...
Advanced Code example: python lazy slicing of infinite sequ 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))
How Code example: f string with expressions python is implemented in Python (v5)
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}')
Code example: 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)
Advanced Can you show binary search algorithm python exampl Python example (v4)
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