id stringlengths 25 36 | kind stringclasses 2
values | title stringlengths 17 17 ⌀ | provisional bool 1
class | code stringlengths 30 1.07k ⌀ | input stringlengths 4 203 ⌀ | language stringclasses 2
values | predicted_output stringlengths 1 231 ⌀ | filename stringclasses 3
values | contentType stringclasses 1
value | checksumSha256 stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|
467896b5-43d3-499f-ad8e-01117df93716 | sponsor_example | null | null | null | null | null | null | execution_trace_drafts-1.json | application/json | 10bbb426d6af9f5046e63f0315bd1d902b9603741973d66d1d827a3e71c4c39e |
19c2e7a7-a5dc-4fad-abea-feead6531b39 | sponsor_example | null | null | null | null | null | null | execution_trace_drafts-2.json | application/json | 6879890a763756fcec73d54666ea8b15ec9cede5bb01d45418af5437c70c5984 |
ca00bb89-d1c2-41f1-bef8-78dfa1e441ec | sponsor_example | null | null | null | null | null | null | execution_trace_drafts-3.json | application/json | 2c6608160b303c2af34a30dd4eb95ec12f25924b7dd2e27b030a65e28949fa25 |
cmskf3c8200071wp2lcgno27p | contributor_item | Submission GNO27P | false | def demo():
config = {"retries": 3}
kept = config.setdefault("retries", 10)
added = config.setdefault("timeout", 30)
return (kept, added, config.get("timeout", 99), sorted(config.items())) | demo() | Python | (3, 30, 30, [('retries', 3), ('timeout', 30)]) | null | null | null |
cmskf3c8200051wp25947eul8 | contributor_item | Submission 47EUL8 | false | def demo():
loose = []
for factor in range(1, 4):
loose.append(lambda x: x * factor)
bound = [lambda x, factor=factor: x * factor for factor in range(1, 4)]
return ([f(10) for f in loose], [f(10) for f in bound]) | demo() | Python | ([30, 30, 30], [10, 20, 30]) | null | null | null |
cmskf3c8300091wp29wn8ecs7 | contributor_item | Submission N8ECS7 | false | def demo():
path = "a/b/c/d"
parts = path.split("/")
return (parts[::-1], "/".join(parts[1:-1]), path.partition("/"), path[::2]) | demo() | Python | (['d', 'c', 'b', 'a'], 'b/c', ('a', '/', 'b/c/d'), 'abcd') | null | null | null |
cmskf3c8200031wp2jpynnp7y | contributor_item | Submission YNNP7Y | false | def resolve(flag):
try:
if flag:
return "from-try"
raise ValueError("bad flag")
except ValueError:
return "from-except"
finally:
print("cleanup ran")
def demo():
return (resolve(True), resolve(False)) | demo() | Python | cleanup ran
cleanup ran
('from-try', 'from-except') | null | null | null |
cmskf3c8200041wp2vszakqde | contributor_item | Submission ZAKQDE | false | import copy
def demo():
grid = [[0, 1], [2, 3]]
shallow = list(grid)
deep = copy.deepcopy(grid)
grid[0][0] = 99
return (shallow[0][0], deep[0][0], shallow[0] is grid[0]) | demo() | Python | (99, 0, True) | null | null | null |
cmskf3c8200011wp22kb81bve | contributor_item | Submission B81BVE | false | records = [
{"name": "ida", "dept": "ops", "years": 4},
{"name": "ben", "dept": "eng", "years": 4},
{"name": "cy", "dept": "eng", "years": 7},
]
def rank():
ordered = sorted(records, key=lambda r: (r["dept"], -r["years"], r["name"]))
return [(r["dept"], r["name"], r["years"]) for r in ordered] | rank() | Python | [('eng', 'cy', 7), ('eng', 'ben', 4), ('ops', 'ida', 4)] | null | null | null |
cmskf3c8200001wp2osjhk0zm | contributor_item | Submission JHK0ZM | false | def collect(item, bucket=[]):
bucket.append(item)
return bucket
def demo():
first = collect("a")
second = collect("b")
return (first, second, first is second) | demo() | Python | (['a', 'b'], ['a', 'b'], True) | null | null | null |
cmskf3c8200081wp28tpa14hx | contributor_item | Submission PA14HX | false | class ParseError(Exception):
pass
def parse_port(raw):
try:
return int(raw)
except ValueError:
raise ParseError("not a port: " + raw) from None
def demo():
results = []
for raw in ["8080", "https"]:
try:
results.append(parse_port(raw))
except ParseError ... | demo() | Python | [8080, 'ParseError: not a port: https'] | null | null | null |
cmskf3c8200061wp24z0nxfpf | contributor_item | Submission 0NXFPF | false | from itertools import groupby
tickets = ["ops-3", "eng-1", "ops-9", "eng-4"]
def team_of(ticket):
return ticket.split("-")[0]
def demo():
raw = [(team, list(g)) for team, g in groupby(tickets, key=team_of)]
tidy = [(team, list(g)) for team, g in groupby(sorted(tickets), key=team_of)]
return (raw, tid... | demo() | Python | ([('ops', ['ops-3']), ('eng', ['eng-1']), ('ops', ['ops-9']), ('eng', ['eng-4'])], [('eng', ['eng-1', 'eng-4']), ('ops', ['ops-3', 'ops-9'])]) | null | null | null |
cmskf3c8200021wp23qmbd6xs | contributor_item | Submission MBD6XS | false | from collections import Counter
def tally():
counts = Counter("pear fig pear plum fig date".split())
return (counts.most_common(2), counts["kiwi"], len(counts)) | tally() | Python | ([('pear', 2), ('fig', 2)], 0, 4) | null | null | null |
cmskfpd47000ix6p20pacmnuw | contributor_item | Submission ACMNUW | false | from itertools import accumulate, chain, islice
def demo_itertools():
running = list(accumulate([1, 2, 3, 4]))
joined = list(chain([1, 2], "ab"))
window = list(islice(range(10), 2, 7, 2))
return (running, joined, window) | demo_itertools() | Python | ([1, 3, 6, 10], [1, 2, 'a', 'b'], [2, 4, 6]) | null | null | null |
cmskfpd48000zx6p2kejqm7xx | contributor_item | Submission JQM7XX | false | def make_counter():
count = 0
def bump():
nonlocal count
count += 1
return count
return bump
def demo_nonlocal():
first = make_counter()
second = make_counter()
return (first(), first(), second()) | demo_nonlocal() | Python | (1, 2, 1) | null | null | null |
cmskfpd480011x6p2zei9p4qw | contributor_item | Submission I9P4QW | false | def demo_try_else():
log = []
for raw in ["5", "oops"]:
try:
value = int(raw)
except ValueError:
log.append("except")
else:
log.append("else:" + str(value))
finally:
log.append("finally")
return log | demo_try_else() | Python | ['else:5', 'finally', 'except', 'finally'] | null | null | null |
cmskfpd48000wx6p29wilm6gc | contributor_item | Submission ILM6GC | false | def demo_formatting():
value = 3.14159
name = "pi"
return (
"{:.2f}".format(value),
"{:>8}".format(name),
"{:08.3f}".format(value),
f"{name:*^9}",
) | demo_formatting() | Python | ('3.14', ' pi', '0003.142', '***pi****') | null | null | null |
cmskfpd48000px6p2v14vqo4a | contributor_item | Submission 4VQO4A | false | def demo_repeated_refs():
shared = [[]] * 3
shared[0].append("x")
independent = [[] for _ in range(3)]
independent[0].append("y")
return (shared, independent, shared[1] is shared[2]) | demo_repeated_refs() | Python | ([['x'], ['x'], ['x']], [['y'], [], []], True) | null | null | null |
cmskfpd47000ax6p223kae635 | contributor_item | Submission KAE635 | false | class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
self._celsius = (value - 32) * 5 / 9
def demo_property():
t = Temperature(100)
... | demo_property() | Python | (212.0, 0.0) | null | null | null |
cmskfpd47000fx6p2w5qkhnld | contributor_item | Submission QKHNLD | false | def noisy_range(n):
for i in range(n):
print("yielding", i)
yield i
def demo_lazy():
gen = noisy_range(3)
print("created")
first = next(gen)
print("got", first)
return list(gen) | demo_lazy() | Python | created
yielding 0
got 0
yielding 1
yielding 2
[1, 2] | null | null | null |
cmskfpd48000qx6p2n2wi82p4 | contributor_item | Submission WI82P4 | false | def demo_tuple_mutation():
holder = ([1], "fixed")
try:
holder[0] += [2]
outcome = "no error"
except TypeError as exc:
outcome = type(exc).__name__
return (outcome, holder) | demo_tuple_mutation() | Python | ('TypeError', ([1, 2], 'fixed')) | null | null | null |
cmskfpd470006x6p2krj21lmm | contributor_item | Submission J21LMM | false | from functools import partial
def power(base, exponent):
return base ** exponent
def demo_partial():
square = partial(power, exponent=2)
cube_of_two = partial(power, 2)
return (square(7), cube_of_two(3)) | demo_partial() | Python | (49, 8) | null | null | null |
cmskfpd47000nx6p27w17ork7 | contributor_item | Submission 17ORK7 | false | def demo_dict_removal():
data = {"a": 1, "b": 2, "c": 3}
popped = data.pop("b")
missing = data.pop("zz", "default")
last = data.popitem()
return (popped, missing, last, data) | demo_dict_removal() | Python | (2, 'default', ('c', 3), {'a': 1}) | null | null | null |
cmskfpd47000kx6p2it2r85a5 | contributor_item | Submission 2R85A5 | false | def truthy(value):
print("checking", value)
return value > 2
def demo_short_circuit():
any_result = any(truthy(v) for v in [1, 3, 5])
print("---")
all_result = all(truthy(v) for v in [3, 1, 5])
return (any_result, all_result) | demo_short_circuit() | Python | checking 1
checking 3
---
checking 3
checking 1
(True, False) | null | null | null |
cmskfpd47000hx6p2cnnrr8b4 | contributor_item | Submission NRR8B4 | false | def demo_generator_expr():
squares = (x * x for x in range(4))
first_pass = list(squares)
second_pass = list(squares)
return (first_pass, second_pass) | demo_generator_expr() | Python | ([0, 1, 4, 9], []) | null | null | null |
cmskfpd470003x6p208eutk8e | contributor_item | Submission EUTK8E | false | from collections import OrderedDict
def reorder():
od = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
od.move_to_end("a")
first = list(od.keys())
od.move_to_end("c", last=False)
return (first, list(od.keys())) | reorder() | Python | (['b', 'c', 'a'], ['c', 'b', 'a']) | null | null | null |
cmskfpd480012x6p25xexstzj | contributor_item | Submission EXSTZJ | false | def demo_walrus():
readings = [4, 8, 1, 9]
kept = []
while readings and (current := readings.pop(0)) < 9:
kept.append(current)
return (kept, readings, current) | demo_walrus() | Python | ([4, 8, 1], [], 9) | null | null | null |
cmskfpd47000cx6p2x1o0moev | contributor_item | Submission O0MOEV | false | class Registry:
members = []
def __init__(self, name):
self.name = name
Registry.members.append(name)
@classmethod
def count(cls):
return len(cls.members)
@staticmethod
def label():
return "registry"
def demo_class_state():
Registry("a")
Registry("b")
... | demo_class_state() | Python | (2, 'registry', ['a', 'b']) | null | null | null |
cmskfpd47000gx6p29j30ysdj | contributor_item | Submission 30YSDJ | false | def demo_next_default():
it = iter([10, 20])
a = next(it)
b = next(it)
c = next(it, "empty")
try:
next(it)
d = "no error"
except StopIteration:
d = "StopIteration"
return (a, b, c, d) | demo_next_default() | Python | (10, 20, 'empty', 'StopIteration') | null | null | null |
cmskfpd47000ox6p2dkksi4nv | contributor_item | Submission KSI4NV | false | def demo_slice_assign():
nums = [0, 1, 2, 3, 4, 5]
nums[1:3] = ["a", "b", "c"]
copy = nums[:]
nums[::2] = [None] * len(nums[::2])
return (copy, nums) | demo_slice_assign() | Python | ([0, 'a', 'b', 'c', 3, 4, 5], [None, 'a', None, 'c', None, 4, None]) | null | null | null |
cmskfpd47000lx6p2pn9rllgy | contributor_item | Submission 9RLLGY | false | def demo_sort_stability():
rows = [("b", 2), ("a", 2), ("c", 1)]
by_number = sorted(rows, key=lambda r: r[1])
in_place = list(rows)
returned = in_place.sort()
return (by_number, returned, in_place) | demo_sort_stability() | Python | ([('c', 1), ('b', 2), ('a', 2)], None, [('a', 2), ('b', 2), ('c', 1)]) | null | null | null |
cmskfpd47000jx6p2kajq3aon | contributor_item | Submission JQ3AON | false | def demo_zip_truncate():
names = ["a", "b", "c"]
scores = [1, 2]
paired = list(zip(names, scores))
unzipped = list(zip(*paired))
return (paired, unzipped) | demo_zip_truncate() | Python | ([('a', 1), ('b', 2)], [('a', 'b'), (1, 2)]) | null | null | null |
cmskfpd47000mx6p2eh1owurq | contributor_item | Submission 1OWURQ | false | def demo_dict_comprehension():
pairs = [("a", 1), ("b", 2), ("a", 3)]
collapsed = {k: v for k, v in pairs}
merged = {**{"a": 0, "z": 9}, **collapsed}
return (collapsed, merged, len(pairs)) | demo_dict_comprehension() | Python | ({'a': 3, 'b': 2}, {'a': 3, 'z': 9, 'b': 2}, 3) | null | null | null |
cmskfpd48000rx6p2ub50qz4y | contributor_item | Submission 50QZ4Y | false | def demo_unpacking():
first, *middle, last = [1, 2, 3, 4, 5]
(a, b), c = (1, 2), 3
return (first, middle, last, a, b, c) | demo_unpacking() | Python | (1, [2, 3, 4], 5, 1, 2, 3) | null | null | null |
cmskfpd48000vx6p2qp65b639 | contributor_item | Submission 65B639 | false | def demo_string_methods():
raw = " Report-2024-final.txt "
trimmed = raw.strip()
return (
trimmed.split("-"),
trimmed.rsplit("-", 1),
trimmed.replace("-", "_", 1),
trimmed.endswith(".txt"),
) | demo_string_methods() | Python | (['Report', '2024', 'final.txt'], ['Report-2024', 'final.txt'], 'Report_2024-final.txt', True) | null | null | null |
cmskfpd48000ux6p22d5tlcj7 | contributor_item | Submission 5TLCJ7 | false | def demo_float_precision():
total = 0.1 + 0.2
return (total, total == 0.3, abs(total - 0.3) < 1e-9, 1 / 3) | demo_float_precision() | Python | (0.30000000000000004, False, True, 0.3333333333333333) | null | null | null |
cmskfpd48000xx6p26i7nnib7 | contributor_item | Submission 7NNIB7 | false | import re
def demo_regex():
text = "id=12, id=345, name=ada"
numbers = re.findall(r"id=(\d+)", text)
masked = re.sub(r"\d+", "#", text)
match = re.search(r"name=(\w+)", text)
return (numbers, masked, match.group(1), match.span()) | demo_regex() | Python | (['12', '345'], 'id=#, id=#, name=ada', 'ada', (15, 23)) | null | null | null |
cmskfpd48000yx6p27d6tmmfu | contributor_item | Submission 6TMMFU | false | import json
def demo_json():
payload = {"b": 2, "a": [1, {"c": None}], "flag": True}
text = json.dumps(payload, sort_keys=True)
restored = json.loads(text)
return (text, restored["a"][1]["c"], restored == payload) | demo_json() | Python | ('{"a": [1, {"c": null}], "b": 2, "flag": true}', None, True) | null | null | null |
cmskfpd48000sx6p2gt75dfwh | contributor_item | Submission 75DFWH | false | def demo_floor_division():
return (
7 // 2, -7 // 2,
7 % 3, -7 % 3,
divmod(-7, 2),
) | demo_floor_division() | Python | (3, -4, 1, 2, (-4, 1)) | null | null | null |
cmskfpd48000tx6p25c19vws9 | contributor_item | Submission 19VWS9 | false | def demo_rounding():
return (round(0.5), round(1.5), round(2.5), round(2.675, 2), round(-1.5)) | demo_rounding() | Python | (0, 2, 2, 2.67, -2) | null | null | null |
cmskfpd480010x6p2wy5lhlet | contributor_item | Submission 5LHLET | false | def classify(n):
for candidate in range(2, n):
if n % candidate == 0:
return ("composite", candidate)
else:
return ("prime", None)
def demo_for_else():
return (classify(9), classify(7)) | demo_for_else() | Python | (('composite', 3), ('prime', None)) | null | null | null |
cmskfpd480013x6p2eg5i0jjb | contributor_item | Submission 5I0JJB | false | def tally(*args, sep="-", **kwargs):
return (args, sep, sorted(kwargs.items()))
def demo_signature():
return (tally(1, 2, sep="+", mode="fast"), tally()) | demo_signature() | Python | (((1, 2), '+', [('mode', 'fast')]), ((), '-', [])) | null | null | null |
cmskfpd470007x6p222pr0xuz | contributor_item | Submission PR0XUZ | false | from functools import reduce
def fold():
numbers = [3, 1, 4, 1, 5]
total = reduce(lambda a, b: a + b, numbers)
seeded = reduce(lambda a, b: a + b, numbers, 100)
largest = reduce(lambda a, b: a if a > b else b, numbers)
return (total, seeded, largest) | fold() | Python | (14, 114, 5) | null | null | null |
cmskfpd47000ex6p25pphz9hy | contributor_item | Submission PHZ9HY | false | class Resource:
def __init__(self, log):
self.log = log
def __enter__(self):
self.log.append("enter")
return self
def __exit__(self, exc_type, exc, tb):
self.log.append("exit:" + (exc_type.__name__ if exc_type else "clean"))
return True
def demo_context():
log ... | demo_context() | Python | ['enter', 'body', 'exit:clean', 'enter', 'exit:ValueError'] | null | null | null |
cmskfpd47000dx6p2ggiej64m | contributor_item | Submission IEJ64M | false | class Counter:
total = 0
def bump(self):
self.total += 1
return self.total
def demo_shadowing():
a = Counter()
b = Counter()
first = a.bump()
second = a.bump()
return (first, second, b.total, Counter.total, "total" in a.__dict__) | demo_shadowing() | Python | (1, 2, 0, 0, True) | null | null | null |
cmskfpd460000x6p2765o8s86 | contributor_item | Submission 5O8S86 | false | from collections import defaultdict
def index_by_initial(names):
buckets = defaultdict(list)
for name in names:
buckets[name[0]].append(name)
missing = buckets["z"]
return (dict(buckets), missing, "z" in buckets) | index_by_initial(["ana", "arjun", "bela", "cy"]) | Python | ({'a': ['ana', 'arjun'], 'b': ['bela'], 'c': ['cy'], 'z': []}, [], True) | null | null | null |
cmskfpd470002x6p2ycc8i1sj | contributor_item | Submission C8I1SJ | false | from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
def move_point():
origin = Point(0, 0)
shifted = origin._replace(y=5)
return (origin, shifted, origin == Point(0, 0), shifted._asdict()) | move_point() | Python | (Point(x=0, y=0), Point(x=0, y=5), True, {'x': 0, 'y': 5}) | null | null | null |
cmskfpd470005x6p2foxxbcs1 | contributor_item | Submission XXBCS1 | false | from functools import lru_cache
calls = []
@lru_cache(maxsize=None)
def slow_square(n):
calls.append(n)
return n * n
def demo_cache():
results = [slow_square(4), slow_square(4), slow_square(5)]
return (results, calls) | demo_cache() | Python | ([16, 16, 25], [4, 5]) | null | null | null |
cmskfpd470004x6p2uwirhw78 | contributor_item | Submission IRHW78 | false | from collections import Counter
def counter_math():
left = Counter(a=3, b=1)
right = Counter(a=1, b=4)
return (dict(left - right), dict(left + right), dict(left & right)) | counter_math() | Python | ({'a': 2}, {'a': 4, 'b': 5}, {'a': 1, 'b': 1}) | null | null | null |
cmskfpd470008x6p2phg7werx | contributor_item | Submission G7WERX | false | from functools import wraps
def announce(fn):
@wraps(fn)
def inner(*args, **kwargs):
return fn(*args, **kwargs) * 2
return inner
def plain(fn):
def inner(*args, **kwargs):
return fn(*args, **kwargs)
return inner
@announce
def base(x):
"""docstring here"""
return x + 1
@pl... | demo_wraps() | Python | (10, 'base', 'docstring here', 'inner') | null | null | null |
cmskfpd47000bx6p2bq3uvguo | contributor_item | Submission 3UVGUO | false | class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return Money(self.amount + other.amount)
def __eq__(self, other):
return self.amount == other.amount
def __repr__(self):
return "Money(" + str(self.amount) + ")"
def demo_operators... | demo_operators() | Python | (Money(12), True, [Money(1), Money(2)]) | null | null | null |
cmskfpd470001x6p23240prqe | contributor_item | Submission 40PRQE | false | from collections import deque
def shuffle_queue():
q = deque([1, 2, 3, 4], maxlen=4)
q.rotate(1)
snapshot = list(q)
q.appendleft(99)
return (snapshot, list(q), q.maxlen) | shuffle_queue() | Python | ([4, 1, 2, 3], [99, 4, 1, 2], 4) | null | null | null |
cmskfpd470009x6p2zmftr2s5 | contributor_item | Submission FTR2S5 | false | class Base:
def greet(self):
return "base"
class Left(Base):
def greet(self):
return "left->" + super().greet()
class Right(Base):
def greet(self):
return "right->" + super().greet()
class Both(Left, Right):
pass
def demo_mro():
return (Both().greet(), [c.__name__ for c i... | demo_mro() | Python | ('left->right->base', ['Both', 'Left', 'Right', 'Base', 'object']) | null | null | null |
cmsms65yl001rdmp21hfk09gv | contributor_item | Submission FK09GV | false | def generator_pipeline(n):
def squares():
for i in range(n):
yield i * i
return list(x for x in squares() if x % 2 == 0) | generator_pipeline(10) | Python | [0, 4, 16, 36, 64] | null | null | null |
cmsms65yl001fdmp242km4ilp | contributor_item | Submission KM4ILP | false | def try_finally_demo(x):
log = []
try:
if x < 0:
raise ValueError("negative")
log.append("processed")
return x * 2
except ValueError as e:
log.append(f"error: {e}")
return -1
finally:
log.append("cleanup")
return log | try_finally_demo(-5) | Python | -1 | null | null | null |
cmsms65yl0018dmp2el6rff6e | contributor_item | Submission 6RFF6E | false | def flatten(nested):
result = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result | flatten([1, [2, 3, [4, [5, 6]], 7], 8]) | Python | [1, 2, 3, 4, 5, 6, 7, 8] | null | null | null |
cmsms65ym0025dmp2hbik6tq3 | contributor_item | Submission IK6TQ3 | false | def validate_and_transform(records):
valid = []
errors = []
for r in records:
try:
age = int(r["age"])
if age < 0:
raise ValueError("negative age")
valid.append({"name": r["name"], "age": age})
except (KeyError, ValueError) as e:
... | validate_and_transform([{"name": "A", "age": "30"}, {"name": "B", "age": "-5"}, {"name": "C"}]) | Python | ([{'name': 'A', 'age': 30}], ['negative age', "'age'"]) | null | null | null |
cmsms65yl001mdmp253fhlc9x | contributor_item | Submission FHLC9X | false | class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
def speak_all(animals):
return [a.speak() for a in animals] | speak_all([Dog(), Cat(), Animal()]) | Python | ['Woof', 'Meow', '...'] | null | null | null |
cmsms65ym0021dmp2fu55zszn | contributor_item | Submission 55ZSZN | false | def context_manager_demo():
class Resource:
def __init__(self, name):
self.name = name
self.log = []
def __enter__(self):
self.log.append(f"open:{self.name}")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.log.appen... | context_manager_demo() | Python | ['open:db', 'using', 'close:db'] | null | null | null |
cmsms65yl001cdmp2iet1jnom | contributor_item | Submission T1JNOM | false | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def linked_list_to_list(head):
out = []
while head:
out.append(head.value)
head = head.next
return out
def build_and_walk():
head = Node(1, Node(2, Node(3, Node(4))))
return li... | build_and_walk() | Python | [1, 2, 3, 4] | null | null | null |
cmsms65yl0015dmp2r0v8hlyy | contributor_item | Submission V8HLYY | false | def fib_memo(n, cache={}):
if n in cache:
return cache[n]
if n <= 1:
return n
cache[n] = fib_memo(n - 1, cache) + fib_memo(n - 2, cache)
return cache[n]
def fib_sequence(count):
return [fib_memo(i) for i in range(count)] | fib_sequence(10) | Python | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | null | null | null |
cmsms65yl0016dmp2h7cwgkzy | contributor_item | Submission CWGKZY | false | class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def __repr__(self):
return f"Stack({self._items})"
def use_stack():
s = Stack()
for i in [1, 2, 3]:
s.push(i * i)
... | use_stack() | Python | Stack([1, 4]) | null | null | null |
cmsms65yl001udmp2lkajjzn0 | contributor_item | Submission AJJZN0 | false | 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 | binary_search([1, 3, 5, 7, 9, 11, 13], 9) | Python | 4 | null | null | null |
cmsms65yl001ldmp27xl7ddf4 | contributor_item | Submission L7DDF4 | false | def chained_comparisons(a, b, c):
return a < b < c, a < b > c | chained_comparisons(1, 5, 10) | Python | (True, False) | null | null | null |
cmsms65ym001zdmp2lspm4jta | contributor_item | Submission PM4JTA | false | def recursive_sum_digits(n):
if n < 10:
return n
return n % 10 + recursive_sum_digits(n // 10) | recursive_sum_digits(987654) | Python | 39 | null | null | null |
cmsms65ym0027dmp2wyqlwn0p | contributor_item | Submission QLWN0P | false | class ReadOnlyDict:
def __init__(self, data):
self._data = dict(data)
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, value):
raise TypeError("read-only")
def __repr__(self):
return f"ReadOnlyDict({self._data})"
def try_mutate():
d = Rea... | try_mutate() | Python | ('read-only', 1) | null | null | null |
cmsms65yl001pdmp28w0q1k9v | contributor_item | Submission 0Q1K9V | false | from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
def sum_points(points):
total_x = sum(p.x for p in points)
total_y = sum(p.y for p in points)
return Point(total_x, total_y) | sum_points([Point(1, 2), Point(3, 4), Point(5, 6)]) | Python | Point(x=9, y=12) | null | null | null |
cmsms65ym002fdmp2sv8l9ze7 | contributor_item | Submission 8L9ZE7 | false | def class_method_and_static_demo():
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
@classmethod
def unit_circle(cls):
return cls(1)
@staticmethod
def area_for(radius):
return Circle.pi * radius * radius
... | class_method_and_static_demo() | Python | (3.14159, 28.274309999999996) | null | null | null |
cmsms65ym002edmp24r7p7ur2 | contributor_item | Submission 7P7UR2 | false | def find_duplicates_with_index(items):
seen = {}
dupes = []
for i, item in enumerate(items):
if item in seen:
dupes.append((item, seen[item], i))
else:
seen[item] = i
return dupes | find_duplicates_with_index(["a", "b", "a", "c", "b", "b"]) | Python | [('a', 0, 2), ('b', 1, 4), ('b', 1, 5)] | null | null | null |
cmsms65yl001tdmp26yej0i1k | contributor_item | Submission EJ0I1K | false | def custom_exception_demo():
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {amount}, balance is {balance}")
def withdraw(balance, amount):
if amount... | custom_exception_demo() | Python | ('Cannot withdraw 100, balance is 50', 50, 100) | null | null | null |
cmsms65yl001edmp2hgo5ornw | contributor_item | Submission O5ORNW | false | def custom_sort(records):
return sorted(records, key=lambda r: (-r[1], r[0])) | custom_sort([("apple", 3), ("banana", 5), ("cherry", 3), ("date", 5)]) | Python | [('banana', 5), ('date', 5), ('apple', 3), ('cherry', 3)] | null | null | null |
cmsms65yl001odmp2u9t9o5sk | contributor_item | Submission T9O5SK | false | def walrus_demo(nums):
result = []
i = 0
while (n := nums[i] if i < len(nums) else None) is not None:
result.append(n * 2)
i += 1
return result | walrus_demo([1, 2, 3]) | Python | [2, 4, 6] | null | null | null |
cmsms65yl001idmp2po1v4lzd | contributor_item | Submission 1V4LZD | false | def apply_decorator():
def logged(func):
calls = []
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
calls.append((args, result))
return result
wrapper.calls = calls
return wrapper
@logged
def square(x):
return x * x
... | apply_decorator() | Python | [((2,), 4), ((3,), 9), ((4,), 16)] | null | null | null |
cmsms65yl001kdmp2w35m9my5 | contributor_item | Submission 5M9MY5 | false | def default_arg_pitfall(value, bucket=[]):
bucket.append(value)
return bucket
def run_pitfall():
a = default_arg_pitfall(1)
b = default_arg_pitfall(2)
return a, b | run_pitfall() | Python | ([1, 2], [1, 2]) | null | null | null |
cmsms65ym001wdmp2pm5n7obm | contributor_item | Submission 5N7OBM | false | import itertools
def pairwise_products(nums):
return [a * b for a, b in itertools.combinations(nums, 2)] | pairwise_products([1, 2, 3, 4]) | Python | [2, 3, 4, 6, 8, 12] | null | null | null |
cmsms65ym002admp2k44z2fdq | contributor_item | Submission 4Z2FDQ | false | def exception_chaining_demo():
def parse(value):
try:
return int(value)
except ValueError as e:
raise RuntimeError("parse failed") from e
try:
parse("abc")
except RuntimeError as e:
return str(e), type(e.__cause__).__name__ | exception_chaining_demo() | Python | ('parse failed', 'ValueError') | null | null | null |
cmsms65ym0024dmp2jsgsbo3f | contributor_item | Submission GSBO3F | false | def lru_style_cache():
from functools import lru_cache
calls = []
@lru_cache(maxsize=None)
def expensive(n):
calls.append(n)
return n * n
expensive(4)
expensive(4)
expensive(5)
expensive(4)
return calls, expensive(5) | lru_style_cache() | Python | ([4, 5], 25) | null | null | null |
cmsms65ym0022dmp2202rqi5h | contributor_item | Submission 2RQI5H | false | def deep_update(base, updates):
for key, value in updates.items():
if isinstance(value, dict) and isinstance(base.get(key), dict):
deep_update(base[key], value)
else:
base[key] = value
return base | deep_update({'a': 1, 'b': {'c': 2, 'd': 3}}, {'b': {'c': 20, 'e': 4}, 'f': 5}) | Python | {'a': 1, 'b': {'c': 20, 'd': 3, 'e': 4}, 'f': 5} | null | null | null |
cmsms65ym0020dmp25eg7nx6x | contributor_item | Submission G7NX6X | false | def slicing_tricks(lst):
return lst[::2], lst[::-1], lst[1:-1], lst[-3:] | slicing_tricks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) | Python | ([0, 2, 4, 6, 8], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 3, 4, 5, 6, 7, 8], [7, 8, 9]) | null | null | null |
cmsms65ym001ydmp2xg18vj5g | contributor_item | Submission 18VJ5G | false | 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 __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def ... | add_vectors() | Python | Vector(4, 6) | null | null | null |
cmsms65ym0029dmp2fn3fu20h | contributor_item | Submission 3FU20H | false | def sort_stability_demo(items):
return sorted(items, key=lambda x: x[0]) | sort_stability_demo([(1, "a"), (2, "b"), (1, "c"), (2, "d"), (1, "e")]) | Python | [(1, 'a'), (1, 'c'), (1, 'e'), (2, 'b'), (2, 'd')] | null | null | null |
cmsms65ym002cdmp20zjm36jy | contributor_item | Submission JM36JY | false | def kwargs_and_args_demo(*args, **kwargs):
return sum(args) + sum(kwargs.values()), sorted(kwargs.keys()) | kwargs_and_args_demo(1, 2, 3, x=10, y=20) | Python | (36, ['x', 'y']) | null | null | null |
cmsms65yl001gdmp272796quj | contributor_item | Submission 796QUJ | false | def make_counter():
count = 0
def increment(step=1):
nonlocal count
count += step
return count
return increment
def run_counter():
inc = make_counter()
inc(3)
inc(2)
return inc(5) | run_counter() | Python | 10 | null | null | null |
cmsms65yl001sdmp2givupg1f | contributor_item | Submission VUPG1F | false | class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
self._celsius = (value - 32) * 5 / 9
def convert_round_trip():
t = Temperature(25)
... | convert_round_trip() | Python | (77.0, 37.78) | null | null | null |
cmsmt31me003ddmp2z9zdhdt7 | contributor_item | Submission ZDHDT7 | false | def fib(n):
a, b = 0, 1
seq = []
for _ in range(n):
seq.append(a)
a, b = b, a + b
return seq | fib(7) | Python | [0, 1, 1, 2, 3, 5, 8] | null | null | null |
cmsmt31me003bdmp2q8mw3cbt | contributor_item | Submission MW3CBT | false | def word_lengths(sentence):
return {w: len(w) for w in sentence.split()} | word_lengths('the quick brown') | Python | {'the': 3, 'quick': 5, 'brown': 5} | null | null | null |
cmsmt31me0039dmp2sd0scuw6 | contributor_item | Submission 0SCUW6 | false | def group_parity(nums):
groups = {'even': [], 'odd': []}
for n in nums:
groups['even' if n % 2 == 0 else 'odd'].append(n)
return groups | group_parity([1, 2, 3, 4, 5]) | Python | {'even': [2, 4], 'odd': [1, 3, 5]} | null | null | null |
cmsmt31me003fdmp2fy8adeje | contributor_item | Submission 8ADEJE | false | def count_vowels(text):
return sum(1 for c in text.lower() if c in 'aeiou') | count_vowels('Encyclopedia') | Python | 5 | null | null | null |
cmsmt31me0037dmp2dnd6rlsg | contributor_item | Submission D6RLSG | false | def safe_divs(pairs):
out = []
for a, b in pairs:
try:
out.append(round(a / b, 3))
except ZeroDivisionError:
out.append(None)
return out | safe_divs([(10, 4), (1, 0)]) | Python | [2.5, None] | null | null | null |
cmsmt31me0038dmp2g8ln771t | contributor_item | Submission LN771T | false | def flatten(nested):
out = []
for item in nested:
if isinstance(item, list):
out.extend(item)
else:
out.append(item)
return out | flatten([1, [2, 3], 4, [5]]) | Python | [1, 2, 3, 4, 5] | null | null | null |
cmsmt31me003admp23gvj9ios | contributor_item | Submission VJ9IOS | false | def unique_sorted(items):
return sorted(set(items)) | unique_sorted([3, 1, 2, 3, 1, 4]) | Python | [1, 2, 3, 4] | null | null | null |
cmsmt31me003edmp25clx0lg4 | contributor_item | Submission LX0LG4 | false | def merge_dicts(a, b):
result = dict(a)
result.update(b)
return result | merge_dicts({'x': 1, 'y': 2}, {'y': 9, 'z': 3}) | Python | {'x': 1, 'y': 9, 'z': 3} | null | null | null |
cmsmt31me003cdmp2aso8su1o | contributor_item | Submission O8SU1O | false | def clamp_all(values, low, high):
return [max(low, min(v, high)) for v in values] | clamp_all([5, -3, 15], 0, 10) | Python | [5, 0, 10] | null | null | null |
cmsmt6sqa003qdmp2qhof64wq | contributor_item | Submission OF64WQ | false | def rle_encode(s):
if not s:
return []
out = []
prev = s[0]
count = 1
for ch in s[1:]:
if ch == prev:
count += 1
else:
out.append((prev, count))
prev = ch
count = 1
out.append((prev, count))
return out | rle_encode('aaabbc') | Python | [('a', 3), ('b', 2), ('c', 1)] | null | null | null |
cmsmt6sqa003hdmp2i68pnij5 | contributor_item | Submission 8PNIJ5 | false | def first_letters(words):
return [w[0] for w in words] | first_letters(['tree', 'quiet', 'brown']) | Python | ['t', 'q', 'b'] | null | null | null |
cmsmt6sqa003pdmp2a9wxm3j6 | contributor_item | Submission WXM3J6 | false | def stack_ops(commands):
stack = []
for op in commands:
if op == 'pop':
stack.pop()
else:
stack.append(op)
return stack | stack_ops(['a', 'b', 'pop', 'c']) | Python | ['a', 'c'] | null | null | null |
cmsmt6sqa003odmp21bz19ele | contributor_item | Submission Z19ELE | false | def normalize(scores):
lo, hi = min(scores), max(scores)
span = hi - lo
return [round((s - lo) / span, 2) for s in scores] | normalize([10, 20, 30]) | Python | [0.0, 0.5, 1.0] | null | null | null |
cmsmt6sqa003rdmp2tdati42s | contributor_item | Submission ATI42S | false | def price_after_tax(prices, rate):
return [round(p * (1 + rate), 2) for p in prices] | price_after_tax([100, 250], 0.08) | Python | [108.0, 270.0] | null | null | null |
cmsmt6sqa003idmp2srnydpyp | contributor_item | Submission NYDPYP | false | def running_max(nums):
best = nums[0]
out = []
for n in nums:
best = max(best, n)
out.append(best)
return out | running_max([1, 3, 2, 5, 4]) | Python | [1, 3, 3, 5, 5] | null | null | null |
cmsmt6sqa003jdmp2a67oiimk | contributor_item | Submission 7OIIMK | false | def dedupe_keep_order(seq):
seen = set()
out = []
for x in seq:
if x not in seen:
seen.add(x)
out.append(x)
return out | dedupe_keep_order([3, 1, 3, 2, 1, 4]) | Python | [3, 1, 2, 4] | null | null | null |
End of preview. Expand in Data Studio
Python Execution Trace & Output Prediction
Self-contained Python programs paired with a concrete function call and the exact runtime output. Include realistic control flow, collections, exceptions, and standard-library behavior; exclude external network, filesystem, secrets, personal data, and copied benchmark examples.
About
This dataset was produced by the DataBounty community and published here as part of an open, karma-only program.
- Contributor items exported: 1000
- Language: Python
- Framework: Community
- License: CC-BY-4.0
Contributors
- @advisorygopher
- @ajaysomavarapu
- @arun-ai-forge
- @benam2k
- @bhanu-n
- @bravebooby
- @combinedgoat
- @culturalturtle
- @directfly
- @dutchswan
- @famousgoose
- @gladiator
- @integralgoldfish
- @kailas
- @kumar-k
- @maheshk218
- @odysseus
- @pleasedgiraffe
- @raja
- @sparemockingbird
- @sravan
- @sriramreddy
- @starlord
- @unsightlyscallop
- @vamshi
- @vinodhsnair
Files
data/items.jsonl— the accepted dataset items (one JSON object per line).manifest.json— machine-readable provenance, license, and credit metadata.
- Downloads last month
- 39