id
stringlengths
25
25
kind
stringclasses
1 value
title
stringlengths
17
17
provisional
bool
1 class
output_code
stringlengths
60
4.12k
input_data_sample
stringlengths
3
637
output_data_sample
unknown
transformation_instruction
stringlengths
54
1.91k
cmsue07fp00grg4p28lb6t3w8
contributor_item
Submission B6T3W8
false
def transform(text): masked = [] for chunk in text.strip().split(";"): _, _, number = chunk.partition("=") number = number.strip() if not number: continue if len(number) <= 4: masked.append(number) else: masked.append("*" * (len(number)...
acct=100200300400;acct=9;acct=44445555
"********0400\n9\n****5555"
Mask each account number so only the last four characters remain visible, replacing the rest with '*'. Numbers of four characters or fewer are left untouched. Return the masked values one per line.
cmsue07fp00gsg4p2izvioqb0
contributor_item
Submission VIOQB0
false
import re def transform(text): def key(name): parts = re.split(r"(\d+)", name) return [int(part) if part.isdigit() else part.casefold() for part in parts] names = [line.strip() for line in text.strip().split("\n") if line.strip()] return "\n".join(sorted(names, key=key))
file10.txt file2.txt File1.txt file20.txt
"File1.txt\nfile2.txt\nfile10.txt\nfile20.txt"
Sort the filenames naturally: split each name into digit and non-digit runs, compare text case-insensitively and digit runs numerically. Return the sorted names one per line.
cmsue07fo00gfg4p22qm2hlzh
contributor_item
Submission M2HLZH
false
def transform(text): keep = {"WARN", "ERROR"} rows = ["time\tlevel\tmessage"] for line in text.strip().split("\n"): parts = line.split(None, 3) if len(parts) < 4: continue date, time, level, message = parts if level not in keep: continue rows.a...
2026-01-04 09:12:01 WARN disk usage 91% 2026-01-04 09:12:04 INFO heartbeat ok 2026-01-04 09:13:00 ERROR upload failed retry=2 malformed line without level
"time\tlevel\tmessage\n09:12:01\tWARN\tdisk usage 91%\n09:13:00\tERROR\tupload failed retry=2"
Convert the log into TSV with header 'time\tlevel\tmessage', keeping only WARN and ERROR lines. Use just the time portion of the timestamp. Lines that do not match the expected shape are skipped.
cmsue07fp00glg4p25ssyvwqe
contributor_item
Submission SYVWQE
false
def transform(text): seen = set() kept = [] for line in text.split("\n"): stripped = line.strip() if not stripped: continue key = stripped.casefold() if key in seen: continue seen.add(key) kept.append(stripped) return "\n".join(kept...
beta alpha Beta alpha gamma beta
"beta\nalpha\ngamma"
Remove duplicate lines case-insensitively, keeping the first spelling seen and the original order. Blank lines are dropped. Return the remaining lines.
cmsue07fp00gog4p2gskv0ri0
contributor_item
Submission KV0RI0
false
def transform(text): factors = {"h": 3600, "m": 60, "s": 1} rows = ["duration,seconds"] for line in text.strip().split("\n"): duration = line.strip() total = 0 for token in duration.split(): total += int(token[:-1]) * factors[token[-1]] rows.append(duration + "," ...
1h 30m 45m 2h 0m 1h 5m 30s
"duration,seconds\n1h 30m,5400\n45m,2700\n2h,7200\n0m,0\n1h 5m 30s,3930"
Convert each duration into total seconds, returning CSV with header 'duration,seconds' preserving the input order.
cmsue07fq00gtg4p2yrzg28uf
contributor_item
Submission ZG28UF
false
import json def transform(text): groups = {} for line in text.strip().split("\n"): name, _rank, status = line.strip().split("|") groups.setdefault(status, []).append(name) ordered = {status: sorted(groups[status]) for status in sorted(groups)} return json.dumps(ordered)
alpha|1|active beta|2|retired gamma|3|active
{ "active": [ "alpha", "gamma" ], "retired": [ "beta" ] }
Group the pipe-delimited rows by their status column and return JSON mapping each status to the sorted list of names, with statuses in alphabetical order.
cmsue07fo00geg4p24aqy8wbx
contributor_item
Submission QY8WBX
false
import csv, io def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) totals = {} for row in reader: totals[row["region"]] = totals.get(row["region"], 0) + int(row["units"]) ordered = sorted(totals.items(), key=lambda pair: (-pair[1], pair[0])) lines = ["region,total"] ...
region,units north,10 south,4 north,6 east,0 south,11
"region,total\nnorth,16\nsouth,15\neast,0"
Aggregate the CSV by region, summing units. Return CSV with header 'region,total' sorted by total descending, then region ascending for ties. Regions totalling zero are still included.
cmsue07fo00gcg4p2pbr9ejby
contributor_item
Submission R9EJBY
false
import json def transform(text): lines = [line for line in text.strip().split("\n") if line.strip()] rows = [] for line in lines[1:]: sku = line[0:9].strip() qty = int(line[9:14].strip()) unit_price = float(line[14:].strip()) if qty == 0: continue rows.ap...
SKU QTY UNIT_PRICE AX-100 012 0004.50 BX-220 000 0012.00 CX-330 007 0000.99
[ { "sku": "AX-100", "qty": 12, "line_total": 54 }, { "sku": "CX-330", "qty": 7, "line_total": 6.93 } ]
Parse the fixed-width inventory report (columns SKU, QTY, UNIT_PRICE) and return a JSON array of objects with keys sku, qty (integer, leading zeros stripped) and line_total (qty * unit_price rounded to 2 decimals). Skip rows whose qty is zero.
cmsue07fo00gdg4p2te2qn262
contributor_item
Submission 2QN262
false
import json def transform(text): config = {} section = None for line in text.strip().split("\n"): line = line.strip() if not line: continue if line.startswith("[") and line.endswith("]"): section = line[1:-1] config[section] = {} conti...
[app] retries = 3 debug = true name = ingest worker [db] port = 5432 ssl = false
{ "app": { "retries": 3, "debug": true, "name": "ingest worker" }, "db": { "port": 5432, "ssl": false } }
Parse the INI-style config into nested JSON, coercing values: 'true'/'false' become booleans, all-digit values become integers, everything else stays a string. Section names become top-level keys.
cmsue07fp00gjg4p2eve0oebn
contributor_item
Submission E0OEBN
false
import json def transform(text): blocks = [block for block in text.strip().split("\n\n") if block.strip()] lines = [] for block in blocks: record = {} for line in block.strip().split("\n"): key, _, value = line.partition(":") record[key.strip()] = value.strip() ...
id: 41 status: open id: 42 status: closed note: duplicate id: 43 status: open
"{\"id\":\"41\",\"status\":\"open\"}\n{\"id\":\"42\",\"status\":\"closed\",\"note\":\"duplicate\"}\n{\"id\":\"43\",\"status\":\"open\"}"
Split the blank-line separated 'key: value' blocks into JSON Lines — one compact JSON object per block, one per output line, preserving key order within a block.
cmsue07fp00gig4p2on3l6vuf
contributor_item
Submission 3L6VUF
false
import json def transform(text): root = [] stack = [(-1, root)] for line in text.rstrip().split("\n"): if not line.strip(): continue indent = len(line) - len(line.lstrip(" ")) label = line.strip().lstrip("-").strip() node = {label: []} while stack and sta...
- platform - ingest - parser - storage - web - api
[ { "platform": [ { "ingest": [ { "parser": [] } ] }, { "storage": [] } ] }, { "web": [ { "api": [] } ] } ]
Convert the two-space-indented Markdown bullet list into nested JSON where each node maps its label to a list of child nodes, and a leaf maps to an empty list.
cmsue07fo00ggg4p25x2oz0ql
contributor_item
Submission 2OZ0QL
false
import csv, io, json def transform(text): records = json.loads(text) out = io.StringIO() writer = csv.writer(out, lineterminator="\n") writer.writerow(["name", "qty"]) for record in records: writer.writerow([record["name"], record["qty"]]) return out.getvalue().strip()
[{"name": "Bolt, 5mm", "qty": 12}, {"name": "Nut \"hex\"", "qty": 3}]
"name,qty\n\"Bolt, 5mm\",12\n\"Nut \"\"hex\"\"\",3"
Convert the JSON array into CSV with header 'name,qty', applying standard CSV quoting so that names containing commas or double quotes survive a round trip. Rows keep their original order.
cmsue07fp00gng4p2mf0e53fx
contributor_item
Submission 0E53FX
false
def transform(text): values = [] for line in text.strip().split("\n"): raw = line.strip().replace("USD", "").replace("$", "").replace(",", "").strip() values.append(format(float(raw), ".2f")) return "\n".join(values)
$1,299.50 -$45 $0.05 USD 12.10
"1299.50\n-45.00\n0.05\n12.10"
Normalise the currency amounts to plain signed decimals with exactly two decimal places, stripping symbols, thousands separators and the 'USD' prefix. Return one value per line in the original order.
cmsue07fp00gkg4p2rp0nl09u
contributor_item
Submission 0NL09U
false
def transform(text): units = ["B", "KiB", "MiB", "GiB", "TiB"] lines = [] for line in text.strip().split("\n"): name, _, raw = line.partition("\t") size = float(raw) if size == 0: lines.append(name + ": 0 B") continue index = 0 while size >= 10...
archive.tar 1536 video.mkv 2411724800 notes.txt 0 image.png 1048576
"archive.tar: 1.5 KiB\nvideo.mkv: 2.2 GiB\nnotes.txt: 0 B\nimage.png: 1.0 MiB"
Convert byte sizes to human-readable units using binary multiples (1024), one decimal place, choosing the largest unit that keeps the value >= 1. Zero stays '0 B'. Output 'name: size' lines in the original order.
cmsue07fp00gmg4p2z9pit05u
contributor_item
Submission PIT05U
false
import csv, io def transform(text): rows = list(csv.DictReader(io.StringIO(text.strip()))) metrics = sorted({row["metric"] for row in rows}) table = {} for row in rows: table.setdefault(row["date"], {})[row["metric"]] = row["value"] out = io.StringIO() writer = csv.writer(out, linetermi...
date,metric,value 2026-01-01,cpu,10 2026-01-01,mem,40 2026-01-02,cpu,15
"date,cpu,mem\n2026-01-01,10,40\n2026-01-02,15,"
Pivot the long-format CSV to wide: one row per date, one column per metric (columns sorted alphabetically). Missing combinations become empty cells. Header starts with 'date'.
cmsue07fp00gqg4p2ptoqolyg
contributor_item
Submission OQOLYG
false
import json def transform(text): flat = {} def walk(node, prefix): if isinstance(node, dict): for key, value in node.items(): walk(value, prefix + "." + key if prefix else key) elif isinstance(node, list): for index, value in enumerate(node): ...
{"server": {"host": "db1", "ports": [5432, 5433]}, "debug": false}
"debug=false\nserver.host=\"db1\"\nserver.ports.0=5432\nserver.ports.1=5433"
Flatten the nested JSON into dotted paths, indexing list elements by position, and return 'path=value' lines sorted by path. Values are rendered as JSON literals, so strings keep their double quotes and booleans stay lowercase.
cmsue07fp00gpg4p2gl32zvrd
contributor_item
Submission 32ZVRD
false
def transform(text): counts = {} for word in text.lower().split(): counts[word] = counts.get(word, 0) + 1 ordered = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0])) return "\n".join(word + "=" + str(count) for word, count in ordered[:3])
the cat sat the mat sat The CAT ran
"the=3\ncat=2\nsat=2"
Count word frequencies case-insensitively and return the top 3 as 'word=count' lines, ordered by count descending then word ascending.
cmsue07fq00gug4p2z9o6nf88
contributor_item
Submission O6NF88
false
def transform(text): rows = [] for line in text.rstrip("\n").split("\n"): rows.append("chars=" + str(len(line)) + " bytes=" + str(len(line.encode("utf-8")))) return "\n".join(rows)
Grüße, Team naïve café plain ascii
"chars=11 bytes=13\nchars=10 bytes=12\nchars=11 bytes=11"
For each line report the character count and the byte length when encoded as UTF-8, as 'chars=<n> bytes=<n>' lines, so that multi-byte characters are visible as a difference.
cmsue07fq00gvg4p2h0z7jcme
contributor_item
Submission Z7JCME
false
def transform(text): rows = [] for index, line in enumerate(text.strip().split("\n"), start=1): total = sum(int(cell) if cell.strip() else 0 for cell in line.split(",")) rows.append("row" + str(index) + ": " + str(total)) return "\n".join(rows)
10,20,30 5,,15 ,, 7,8,9
"row1: 60\nrow2: 20\nrow3: 0\nrow4: 24"
Sum each CSV row, treating empty cells as zero, and return 'row<N>: <sum>' lines numbered from 1. A row of only empty cells sums to 0.
cmsugzt3200hcg4p2di7wcjsk
contributor_item
Submission 7WCJSK
false
import json def transform(text): lines = [l for l in text.strip().split('\n') if l] header = lines[0].split('\t') rows = [] for line in lines[1:]: values = line.split('\t') rows.append(dict(zip(header, values))) return json.dumps(rows)
name age city Alice 30 NYC Bob 25 LA
[ { "name": "Alice", "age": "30", "city": "NYC" }, { "name": "Bob", "age": "25", "city": "LA" } ]
Convert a tab-separated values block (first row is the header) into a JSON array of objects, one per data row.
cmsugzt3200hbg4p2ohl32rks
contributor_item
Submission L32RKS
false
import json def transform(text): result = {} section = None for line in text.strip().split('\n'): line = line.strip() if not line or line.startswith('#'): continue if line.startswith('[') and line.endswith(']'): section = line[1:-1] result[section...
[server] host = localhost port = 8080 [database] name = mydb user = admin
{ "server": { "host": "localhost", "port": "8080" }, "database": { "name": "mydb", "user": "admin" } }
Parse a simple INI-style config with [section] headers and key = value lines into a nested JSON object keyed by section, then key.
cmsugzt3300hfg4p2i1yxe5pr
contributor_item
Submission YXE5PR
false
import re def transform(text): nums = [float(n) for n in re.findall(r'-?\d+\.?\d*', text)] total = sum(nums) return str(total) if total != int(total) else str(int(total))
Order #1023: 3 items at 12.50 each, plus 2 items at 7 each, shipping -5 discount
1042.5
Extract every number (integer or decimal, including negatives) embedded anywhere in the free text and return the sum as a plain string, without a trailing '.0' when the result is a whole number.
cmsugzt3300heg4p2w56tdabi
contributor_item
Submission 6TDABI
false
import json def transform(text): pairs = [p.strip() for p in text.strip().split(';') if p.strip()] d = {} for p in pairs: k, v = p.split(':', 1) d[k.strip()] = v.strip() return json.dumps(dict(sorted(d.items())))
zebra: stripes; apple: fruit; mango: fruit
{ "apple": "fruit", "mango": "fruit", "zebra": "stripes" }
Parse a semicolon-separated list of 'key: value' pairs into a JSON object with keys sorted alphabetically.
cmsugzt3200hdg4p2mx341zif
contributor_item
Submission 341ZIF
false
def transform(text): words = text.strip().split() result = [] i = 0 while i < len(words): w = words[i] count = 1 while i + count < len(words) and words[i + count] == w: count += 1 result.append(f"{w}x{count}" if count > 1 else w) i += count return ...
the the the cat sat sat on on on on the mat
"thex3 cat satx2 onx4 the mat"
Collapse consecutive duplicate whitespace-separated words into a single 'wordxN' token when N>1 (keep single occurrences as-is), preserving overall word order.
cmsuhh08w00jmg4p2p8uxys68
contributor_item
Submission UXYS68
false
import json def transform(text): lines = [l for l in text.split('\n') if l.strip()] rows = [] for line in lines: name = line[0:10].strip() age = line[10:13].strip() city = line[13:].strip() rows.append({"name": name, "age": int(age), "city": city}) return json.dumps(rows...
Alice 30 New York Bob 25 Boston
[ { "name": "Alice", "age": 30, "city": "New York" }, { "name": "Bob", "age": 25, "city": "Boston" } ]
Parse fixed-width text rows (name in columns 0-9, age in columns 10-12, city in the remainder) into a JSON array of objects with name, age (as an integer), and city.
cmsuhh08w00jog4p2h4lt72ge
contributor_item
Submission LT72GE
false
def transform(text): lines = [l for l in text.strip().split('\n') if l] header, *rows = lines seen = {} order = [] for row in rows: key = row.split(',')[0] if key not in seen: order.append(key) seen[key] = row out_lines = [header] + [seen[k] for k in order] ...
id,value 1,a 2,b 1,c 3,d 2,e
"id,value\n1,c\n2,e\n3,d"
Given CSV text with a header row and an id column first, deduplicate rows by id, keeping only the last occurrence of each id, and preserve the first-seen order of ids.
cmsuhh08w00jng4p2mahirt2f
contributor_item
Submission HIRT2F
false
import json def transform(text): result = {} for pair in text.strip().split(','): k, v = pair.split('=', 1) k, v = k.strip(), v.strip() if v.lower() in ('true', 'false'): result[k] = v.lower() == 'true' else: try: result[k] = int(v) ...
name=Widget, price=19.99, in_stock=true, quantity=42
{ "name": "Widget", "price": 19.99, "in_stock": true, "quantity": 42 }
Parse a comma-separated list of key=value pairs into a JSON object, inferring the type of each value as boolean, integer, float, or string.
cmsuhh08w00jqg4p2kunxyqyc
contributor_item
Submission NXYQYC
false
import json def transform(text): result = {} for pair in text.strip().split(';'): if not pair.strip(): continue tag, value = pair.split(':', 1) result[tag.strip()] = value.strip() return json.dumps(result)
author:Jane Doe;year:2024;genre:Fiction
{ "author": "Jane Doe", "year": "2024", "genre": "Fiction" }
Parse a semicolon-separated list of tag:value pairs into a JSON object mapping each tag to its value.
cmsuhh08w00jpg4p2utzj3mi0
contributor_item
Submission ZJ3MI0
false
import json def transform(text): temps = [float(x.strip()) for x in text.strip().split(',')] fahrenheit = [round(t * 9/5 + 32, 1) for t in temps] return json.dumps(fahrenheit)
0, 20, 37, 100
[ 32, 68, 98.6, 212 ]
Parse a comma-separated list of Celsius temperature readings and convert them to Fahrenheit, rounded to 1 decimal place, returned as a JSON array.
cmsujal4500lwg4p24v3d9vu9
contributor_item
Submission 3D9VU9
false
import csv, json, io def transform(text): reader = csv.reader(io.StringIO(text.strip())) result = [] for row in reader: result.append({'name': row[0], 'age': int(row[1]), 'role': row[2]}) return json.dumps(result)
John Doe,32,Engineer Jane Smith,28,Designer Bob Lee,45,Manager
[ { "name": "John Doe", "age": 32, "role": "Engineer" }, { "name": "Jane Smith", "age": 28, "role": "Designer" }, { "name": "Bob Lee", "age": 45, "role": "Manager" } ]
Parse CSV rows of name,age,role (no header) into a JSON array of objects with keys name, age (as int), role.
cmsujal4500m0g4p2peqf0l8v
contributor_item
Submission QF0L8V
false
import json def transform(text): totals = {} for line in text.strip().split('\n'): date, product, qty = line.split(',') totals[product] = totals.get(product, 0) + int(qty) return json.dumps({k: totals[k] for k in sorted(totals)})
2026-01-15,widget,3 2026-01-16,gadget,1 2026-01-15,widget,2 2026-01-17,widget,5
{ "gadget": 1, "widget": 10 }
Parse lines of date,product,quantity and sum quantities per product across all dates, returning a JSON object sorted by product name.
cmsujal4500lxg4p2d5v861zr
contributor_item
Submission V861ZR
false
def transform(text): lines = text.split('\n') cleaned = [] for line in lines: cleaned.append(' '.join(line.split())) return '\n'.join(cleaned)
Hello World This is a Test
"Hello World\nThis is a Test"
Normalize whitespace: collapse multiple spaces into one, strip leading/trailing whitespace on each line, and join lines with a single newline.
cmsujal4500lyg4p28cd4n13v
contributor_item
Submission D4N13V
false
import json def transform(text): result = {} for pair in text.strip().split(','): k, v = pair.split(':') result[k] = int(v) result['_total'] = sum(result.values()) return json.dumps(result)
apple:3,banana:5,cherry:2
{ "apple": 3, "banana": 5, "cherry": 2, "_total": 10 }
Parse a comma-separated key:value inventory string into a JSON object mapping each key to its integer value, and add a computed '_total' key summing all values.
cmsujal4500lzg4p25sdcpyhn
contributor_item
Submission DCPYHN
false
import csv, io, json def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) result = {} for row in reader: score = int(row['score']) if score >= 90: grade = 'A' elif score >= 80: grade = 'B' else: grade = 'C' resul...
id,score 1,85 2,92 3,78 4,95
{ "1": "B", "2": "A", "3": "C", "4": "A" }
Given a CSV of id,score, return a JSON object mapping each id to a letter grade: A for score>=90, B for 80-89, C for below 80.
cmsuqx5uo011tg4p2wygv0auc
contributor_item
Submission GV0AUC
false
import json import re def transform(text): line = text.strip() pattern = r'(\w+)=("[^"]*"|\S+)' pairs = re.findall(pattern, line) result = {} for key, value in pairs: if value.startswith('"') and value.endswith('"'): value = value[1:-1] elif re.fullmatch(r'-?\d+', value...
level=INFO msg="user created successfully" user_id=42 ip=10.0.0.5 latency_ms=12.5 retries=0
{ "level": "INFO", "msg": "user created successfully", "user_id": 42, "ip": "10.0.0.5", "latency_ms": 12.5, "retries": 0 }
Parse a logfmt-style key=value log line into a JSON object. Quoted values (e.g. msg="...") may contain spaces and must have their surrounding quotes stripped. Values that look numeric should be converted to int or float, but a value that merely resembles a number — like an IP address — must remain a string.
cmsuqx5uo011ug4p2gmlyhv3q
contributor_item
Submission LYHV3Q
false
import csv import io from collections import defaultdict def transform(text): totals = defaultdict(float) counts = defaultdict(int) for line in text.strip().split('\n'): line = line.strip() if not line: continue category, amount = line.rsplit(' ', 1) totals[cate...
groceries 45.50 transport 12.00 dry goods 30.25 dining 60.00 transport 8.75 dry goods 15.00
"category,total,count\r\ndining,60.00,1\r\ndry goods,45.25,2\r\ngroceries,45.50,1\r\ntransport,20.75,2"
Each line is '<category> <amount>', one transaction per line; category names may themselves contain spaces (e.g. 'dry goods'). Aggregate the total amount and transaction count per category, and output as CSV with header 'category,total,count', rows sorted alphabetically by category, amounts formatted to exactly 2 decim...
cmsv71ouv019bg4p2d0tfpoot
contributor_item
Submission TFPOOT
false
import csv, io, json def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) records = [] for row in reader: rec = {} for k, v in row.items(): v = v.strip() if v.lower() in ('true', 'false'): rec[k] = v.lower() == 'true' el...
sku,quantity,price,in_stock A100,12,4.99,true B200,0,19.5,false C300,7,3,true
[ { "sku": "A100", "quantity": 12, "price": 4.99, "in_stock": true }, { "sku": "B200", "quantity": 0, "price": 19.5, "in_stock": false }, { "sku": "C300", "quantity": 7, "price": 3, "in_stock": true } ]
Parse a CSV string with a header row into a JSON array of records, coercing each cell to int, float, or bool where possible (leaving other values as strings).
cmsv723vq019jg4p2rtrfqv03
contributor_item
Submission RFQV03
false
import json def transform(text): data = json.loads(text) def flatten(obj, prefix=''): items = {} if isinstance(obj, dict): for k, v in obj.items(): new_key = f"{prefix}.{k}" if prefix else k items.update(flatten(v, new_key)) elif isinstance(o...
{"user": {"id": 42, "name": "Priya", "address": {"city": "Pune", "zip": "411001"}, "tags": ["vip", "beta"]}, "active": true}
{ "active": true, "user.address.city": "Pune", "user.address.zip": "411001", "user.id": 42, "user.name": "Priya", "user.tags[0]": "vip", "user.tags[1]": "beta" }
Flatten an arbitrarily nested JSON object (including lists) into a single-level JSON object whose keys use dot notation for nested dicts and bracket notation like key[0] for list indices, with keys sorted alphabetically.
cmsv72j0h019sg4p2hdlqvgg8
contributor_item
Submission LQVGG8
false
import json from collections import defaultdict def transform(text): rows = json.loads(text) agg = defaultdict(lambda: {"total_revenue": 0.0, "order_count": 0}) for r in rows: key = r["region"] agg[key]["total_revenue"] += r["amount"] agg[key]["order_count"] += 1 result = [] ...
[{"region": "west", "amount": 120.5}, {"region": "east", "amount": 80.0}, {"region": "west", "amount": 30.0}, {"region": "east", "amount": 45.25}, {"region": "west", "amount": 10.0}]
[ { "region": "east", "total_revenue": 125.25, "order_count": 2, "avg_order_value": 62.62 }, { "region": "west", "total_revenue": 160.5, "order_count": 3, "avg_order_value": 53.5 } ]
Group a JSON array of order records by 'region' and compute total_revenue, order_count, and avg_order_value per region, returning a JSON array sorted by region name.
cmsv73ibi01a0g4p2g28jff3y
contributor_item
Submission 8JFF3Y
false
import json, re def transform(text): lines = [l.strip() for l in text.strip().split('\n') if l.strip()] out = [] for line in lines: digits = re.sub(r'\D', '', line) if len(digits) == 11 and digits.startswith('1'): digits = digits[1:] if len(digits) != 10: out...
(555) 123-4567 555.987.6543 1-555-222-3333 12345
[ { "raw": "(555) 123-4567", "normalized": "+1-555-123-4567", "valid": true }, { "raw": "555.987.6543", "normalized": "+1-555-987-6543", "valid": true }, { "raw": "1-555-222-3333", "normalized": "+1-555-222-3333", "valid": true }, { "raw": "12345", "normalized":...
Normalize a list of messy US phone number strings (varied punctuation) into E.164-like '+1-XXX-XXX-XXXX' format, flagging entries that cannot be parsed into exactly 10 digits as invalid.
cmsv749af01acg4p2qr9z0ww9
contributor_item
Submission 9Z0WW9
false
import json from collections import OrderedDict def transform(text): rows = json.loads(text) pivot = OrderedDict() months = [] for r in rows: product = r["product"] month = r["month"] if month not in months: months.append(month) pivot.setdefault(product, {})[...
[{"product": "Widget", "month": "2026-01", "units_sold": 10}, {"product": "Widget", "month": "2026-02", "units_sold": 15}, {"product": "Gadget", "month": "2026-01", "units_sold": 5}, {"product": "Gadget", "month": "2026-03", "units_sold": 8}]
[ { "product": "Widget", "2026-01": 10, "2026-02": 15, "2026-03": 0 }, { "product": "Gadget", "2026-01": 5, "2026-02": 0, "2026-03": 8 } ]
Pivot a JSON array of {product, month, units_sold} records into a wide table with one row per product and one column per month (sorted chronologically), filling missing month/product combinations with 0.
cmsv74vi201ang4p2sz8ngxy6
contributor_item
Submission 8NGXY6
false
import json from datetime import datetime def transform(text): rows = json.loads(text) latest = {} for r in rows: key = (r["customer_id"], r["product_sku"]) ts = datetime.fromisoformat(r["updated_at"].replace("Z", "+00:00")) if key not in latest or ts > latest[key][0]: l...
[{"customer_id": 1, "product_sku": "A1", "status": "pending", "updated_at": "2026-01-01T10:00:00Z"}, {"customer_id": 1, "product_sku": "A1", "status": "shipped", "updated_at": "2026-01-03T10:00:00Z"}, {"customer_id": 2, "product_sku": "B2", "status": "pending", "updated_at": "2026-01-02T10:00:00Z"}, {"customer_id": 1, ...
[ { "customer_id": 1, "product_sku": "A1", "status": "shipped", "updated_at": "2026-01-03T10:00:00Z" }, { "customer_id": 2, "product_sku": "B2", "status": "pending", "updated_at": "2026-01-02T10:00:00Z" } ]
Deduplicate a JSON array of order-status update records using the composite key (customer_id, product_sku), keeping only the record with the most recent 'updated_at' timestamp for each key, and return the results sorted by customer_id then product_sku.
cmsv75d6601ayg4p2rxcbgv67
contributor_item
Submission CBGV67
false
import json def transform(text): rows = json.loads(text) out = [] for r in rows: migrated = { "id": r["user_id"], "profile": { "first_name": r["first_name"], "last_name": r["last_name"], "email": r["email_address"] ...
[{"user_id": 1, "first_name": "Ana", "last_name": "Silva", "email_address": "ana@example.com", "phone_number": "555-1000", "signup_date": "2025-11-01"}, {"user_id": 2, "first_name": "Ben", "last_name": "Lee", "email_address": "ben@example.com", "phone_number": null, "signup_date": "2025-12-15"}]
[ { "id": 1, "profile": { "first_name": "Ana", "last_name": "Silva", "email": "ana@example.com" }, "contact": { "phone": "555-1000" }, "meta": { "created": "2025-11-01" } }, { "id": 2, "profile": { "first_name": "Ben", "last_name": "Lee...
Migrate a flat legacy user-record JSON schema into a nested schema grouping fields under 'profile', 'contact', and 'meta' objects, renaming id and email fields appropriately.
cmsv75vxl01bag4p23lnpf07h
contributor_item
Submission NPF07H
false
import json, csv, io def transform(text): lines = [l for l in text.strip().split('\n') if l.strip()] records = [json.loads(l) for l in lines] fieldnames = [] for r in records: for k in r.keys(): if k not in fieldnames: fieldnames.append(k) out = io.StringIO() ...
{"id": 1, "name": "Alpha", "score": 88} {"id": 2, "name": "Beta", "score": 92} {"id": 3, "name": "Gamma", "score": 79}
"id,name,score\r\n1,Alpha,88\r\n2,Beta,92\r\n3,Gamma,79"
Convert newline-delimited JSON (JSON Lines) records into a CSV string with a header row derived from the union of all keys in first-seen order.
cmsv76ahq01blg4p2h0c3uxgw
contributor_item
Submission C3UXGW
false
import json from datetime import datetime def transform(text): lines = [l.strip() for l in text.strip().split('\n') if l.strip()] formats = ["%m/%d/%Y", "%d-%m-%Y", "%Y.%m.%d", "%B %d, %Y"] out = [] for line in lines: parsed = None for fmt in formats: try: pa...
03/15/2026 25-12-2025 2026.01.09 March 3, 2026
[ "2026-03-15", "2025-12-25", "2026-01-09", "2026-03-03" ]
Parse a list of dates written in several different inconsistent formats (MM/DD/YYYY, DD-MM-YYYY, YYYY.MM.DD, and 'Month DD, YYYY') and normalize each to ISO 8601 'YYYY-MM-DD', returning null for any that fail to parse.
cmsv76qy701bxg4p2smnenho8
contributor_item
Submission NENHO8
false
import json, re from collections import Counter def transform(text): lines = [l for l in text.strip().split('\n') if l.strip()] counts = Counter() for line in lines: m = re.search(r'"\w+ \S+ HTTP/\d\.\d"\s+(\d{3})', line) if m: counts[m.group(1)] += 1 return json.dumps(dict(...
127.0.0.1 - - [10/Aug/2026:10:00:00] "GET /index.html HTTP/1.1" 200 512 127.0.0.1 - - [10/Aug/2026:10:00:05] "GET /missing HTTP/1.1" 404 128 127.0.0.1 - - [10/Aug/2026:10:00:07] "POST /login HTTP/1.1" 200 256 127.0.0.1 - - [10/Aug/2026:10:00:09] "GET /error HTTP/1.1" 500 64
{ "200": 2, "404": 1, "500": 1 }
Parse Apache-style access log lines and count occurrences of each HTTP status code, returning a JSON object mapping status code strings to counts sorted by code.
cmsv777sa01c9g4p2npm8qdaw
contributor_item
Submission M8QDAW
false
import json def transform(text): data = json.loads(text) out = [] for order in data: for item in order["items"]: out.append({ "order_id": order["order_id"], "customer": order["customer"], "sku": item["sku"], "qty": item["qt...
[{"order_id": "O1", "customer": "Kai", "items": [{"sku": "X1", "qty": 2, "unit_price": 5.5}, {"sku": "X2", "qty": 1, "unit_price": 12.0}]}, {"order_id": "O2", "customer": "Mei", "items": [{"sku": "X3", "qty": 3, "unit_price": 4.0}]}]
[ { "order_id": "O1", "customer": "Kai", "sku": "X1", "qty": 2, "line_total": 11 }, { "order_id": "O1", "customer": "Kai", "sku": "X2", "qty": 1, "line_total": 12 }, { "order_id": "O2", "customer": "Mei", "sku": "X3", "qty": 3, "line_total": 12 } ]
Explode a JSON array of orders, each containing a nested list of line items, into a flat JSON array of one row per line item including order_id, customer, sku, qty, and a computed line_total (qty * unit_price, rounded to 2 decimals).
cmsv77qiw01ckg4p2vawis9vk
contributor_item
Submission WIS9VK
false
import csv, io, json def transform(text): reader = csv.reader(io.StringIO(text.strip())) header = [h.strip().lower().replace(' ', '_') for h in next(reader)] out = [] for row in reader: if not any(c.strip() for c in row): continue rec = {} for k, v in zip(header, row...
Full Name , Age , City " Zara Khan " , 29 , " Lahore " Omar Farooq, N/A ,Karachi ,,
[ { "full_name": "Zara Khan", "age": 29, "city": "Lahore" }, { "full_name": "Omar Farooq", "age": null, "city": "Karachi" } ]
Clean a messy CSV string with inconsistent whitespace, quoted fields, and 'N/A' placeholders: normalize header names to lowercase snake_case, trim and unquote values, convert 'N/A' and empty strings to null, coerce numeric strings to int/float, and drop fully blank rows.
cmsv786es01cxg4p2jcv48jd1
contributor_item
Submission V48JD1
false
import json from collections import defaultdict def transform(text): rows = json.loads(text) weighted = defaultdict(lambda: [0.0, 0.0]) for r in rows: weighted[r["course"]][0] += r["grade"] * r["credits"] weighted[r["course"]][1] += r["credits"] result = {course: round(total / weight, 2...
[{"course": "Math", "grade": 90, "credits": 3}, {"course": "Math", "grade": 80, "credits": 4}, {"course": "Physics", "grade": 70, "credits": 2}, {"course": "Physics", "grade": 95, "credits": 3}]
{ "Math": 84.29, "Physics": 85 }
Compute the credit-weighted average grade per course from a JSON array of {course, grade, credits} records, returning a JSON object mapping course name to the rounded weighted average.
cmsv78lrn01d8g4p2mt5nm3xk
contributor_item
Submission 5NM3XK
false
import re, json def transform(text): tags = re.findall(r'<(\w+)([^>]*)>([^<]*)</\1>', text) result = {} for name, attrs_str, value in tags: attrs = dict(re.findall(r'(\w+)="([^"]*)"', attrs_str)) entry = {"value": value.strip()} if attrs: entry["attributes"] = attrs ...
<config><host port="8080">localhost</host><timeout unit="ms">3000</timeout><debug>true</debug></config>
{ "debug": { "value": "true" }, "host": { "attributes": { "port": "8080" }, "value": "localhost" }, "timeout": { "attributes": { "unit": "ms" }, "value": "3000" } }
Parse a simple single-line XML-like config string into a JSON object, extracting each top-level child tag's text value and any XML attributes it has, keyed by tag name.
cmsv791cd01dig4p2yden9jp6
contributor_item
Submission EN9JP6
false
import csv, io, json def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) id_field = reader.fieldnames[0] year_fields = reader.fieldnames[1:] out = [] for row in reader: for year in year_fields: val = row[year].strip() if val == '': ...
country,2023,2024,2025 USA,100,110, India,80,90,95
[ { "country": "USA", "year": "2023", "value": 100 }, { "country": "USA", "year": "2024", "value": 110 }, { "country": "India", "year": "2023", "value": 80 }, { "country": "India", "year": "2024", "value": 90 }, { "country": "India", "year": "202...
Reshape a wide CSV with an id column followed by multiple year columns into a long/tidy JSON array of {id_field, year, value} records, skipping any cells that are blank for a given year.
cmsv79loh01dwg4p24sq2rm2r
contributor_item
Submission Q2RM2R
false
import json from datetime import datetime def transform(text): rows = json.loads(text) rows = sorted(rows, key=lambda r: (r["user"], r["ts"])) sessions = [] current = None GAP_MINUTES = 30 for r in rows: ts = datetime.fromisoformat(r["ts"]) if current is None or current["user"] ...
[{"user": "u1", "ts": "2026-05-01T09:00:00"}, {"user": "u1", "ts": "2026-05-01T09:10:00"}, {"user": "u1", "ts": "2026-05-01T10:00:00"}, {"user": "u2", "ts": "2026-05-01T09:05:00"}, {"user": "u1", "ts": "2026-05-01T10:05:00"}]
[ { "user": "u1", "start": "2026-05-01T09:00:00", "end": "2026-05-01T09:10:00", "event_count": 2 }, { "user": "u1", "start": "2026-05-01T10:00:00", "end": "2026-05-01T10:05:00", "event_count": 2 }, { "user": "u2", "start": "2026-05-01T09:05:00", "end": "2026-05-01T0...
Sessionize a JSON array of per-user timestamped events into sessions, starting a new session whenever the gap between consecutive events for the same user exceeds 30 minutes, and return each session's user, start time, end time, and event count.
cmsv7a1w601e8g4p2pym4thii
contributor_item
Submission M4THII
false
import json from collections import defaultdict def transform(text): rows = json.loads(text) by_category = defaultdict(list) for r in rows: by_category[r["category"]].append(r) result = [] for category in sorted(by_category): top = sorted(by_category[category], key=lambda r: -r["sal...
[{"category": "electronics", "product": "TV", "sales": 500}, {"category": "electronics", "product": "Phone", "sales": 900}, {"category": "electronics", "product": "Radio", "sales": 100}, {"category": "furniture", "product": "Chair", "sales": 200}, {"category": "furniture", "product": "Table", "sales": 300}]
[ { "category": "electronics", "top_products": [ { "product": "Phone", "sales": 900 }, { "product": "TV", "sales": 500 } ] }, { "category": "furniture", "top_products": [ { "product": "Table", "sales": 300 }, ...
Group a JSON array of {category, product, sales} records by category and return, for each category (sorted alphabetically), the top 2 products by sales in descending order.
cmsv7ahlz01egg4p2ysec68y9
contributor_item
Submission EC68Y9
false
import json, re def transform(text): lines = [l.strip() for l in text.strip().split('\n') if l.strip()] out = [] for line in lines: m = re.match(r'^([\w\s\-]+):\s*([\d.]+)\s*(kg|lb|g)$', line.strip()) if not m: out.append({"raw": line, "kg": None}) continue n...
Flour: 2 kg Sugar: 4.4 lb Salt: 500 g Badline
[ { "item": "Flour", "kg": 2 }, { "item": "Sugar", "kg": 1.996 }, { "item": "Salt", "kg": 0.5 }, { "raw": "Badline", "kg": null } ]
Normalize a list of 'item: amount unit' strings with mixed weight units (kg, lb, g) into a JSON array converting every amount to kilograms (rounded to 3 decimals), marking unparseable lines with a null kg value.
cmsv7ayxh01eng4p2yyftp46o
contributor_item
Submission FTP46O
false
import json from collections import defaultdict def transform(text): pairs = json.loads(text) children = defaultdict(list) all_nodes = set() child_nodes = set() for p in pairs: children[p["parent"]].append(p["child"]) all_nodes.add(p["parent"]) all_nodes.add(p["child"]) ...
[{"parent": "CEO", "child": "VP_Eng"}, {"parent": "CEO", "child": "VP_Sales"}, {"parent": "VP_Eng", "child": "Manager_A"}, {"parent": "Manager_A", "child": "Dev1"}, {"parent": "VP_Sales", "child": "Manager_B"}]
[ { "node": "CEO", "depth": 0 }, { "node": "Dev1", "depth": 3 }, { "node": "Manager_A", "depth": 2 }, { "node": "Manager_B", "depth": 2 }, { "node": "VP_Eng", "depth": 1 }, { "node": "VP_Sales", "depth": 1 } ]
Build a tree from a JSON array of {parent, child} pairs and compute the depth of every node from its root (nodes that never appear as a child are roots at depth 0), returning a JSON array of {node, depth} sorted by node name.
cmsv7bg7q01evg4p2qwqf1ahp
contributor_item
Submission QF1AHP
false
import json from collections import defaultdict def transform(text): rows = json.loads(text) rows = sorted(rows, key=lambda r: (r["account"], r["date"])) running = defaultdict(float) out = [] for r in rows: running[r["account"]] += r["amount"] out.append({ "account": r["...
[{"account": "acc1", "date": "2026-02-01", "amount": 100.0}, {"account": "acc2", "date": "2026-02-01", "amount": 50.0}, {"account": "acc1", "date": "2026-02-03", "amount": -30.5}, {"account": "acc2", "date": "2026-02-05", "amount": 20.0}, {"account": "acc1", "date": "2026-02-04", "amount": 15.25}]
[ { "account": "acc1", "date": "2026-02-01", "amount": 100, "running_total": 100 }, { "account": "acc1", "date": "2026-02-03", "amount": -30.5, "running_total": 69.5 }, { "account": "acc1", "date": "2026-02-04", "amount": 15.25, "running_total": 84.75 }, { ...
Compute a running cumulative total of 'amount' per account over time from a JSON array of dated transactions (sorted by account then date), returning each transaction annotated with its running_total rounded to 2 decimals.
cmsv88bdo01ggg4p2zodak850
contributor_item
Submission DAK850
false
import json def transform(text): data = json.loads(text) headers = data["headers"] rows = data["rows"] # transpose: each original column becomes a row, prefixed by its header transposed = [] for col_idx, header in enumerate(headers): row = [header] + [r[col_idx] for r in rows] t...
{"headers": ["name", "age", "city"], "rows": [["Alice", 30, "NYC"], ["Bob", 25, "LA"], ["Cara", 35, "SF"]]}
{ "headers": [ "field", "row1", "row2", "row3" ], "rows": [ [ "name", "Alice", "Bob", "Cara" ], [ "age", 30, 25, 35 ], [ "city", "NYC", "LA", "SF" ] ] }
Transpose a table given as JSON with 'headers' and 'rows' (list of row arrays) so each original column becomes a row. Output JSON with new 'headers' (['field', 'row1', 'row2', ...]) and 'rows' where each row starts with the original column header followed by that column's values in order.
cmsv88x3d01gjg4p2gzmqymcg
contributor_item
Submission MQYMCG
false
import json from datetime import datetime, timedelta def transform(text): records = json.loads(text) # bucket timestamps into hourly buckets, average the value in each bucket buckets = {} for r in records: ts = datetime.fromisoformat(r["ts"].replace("Z", "+00:00")) bucket_key = ts.strft...
[{"ts": "2026-05-01T08:05:00Z", "value": 10}, {"ts": "2026-05-01T08:40:00Z", "value": 20}, {"ts": "2026-05-01T10:15:00Z", "value": 5}, {"ts": "2026-05-01T11:00:00Z", "value": 7}, {"ts": "2026-05-01T11:50:00Z", "value": 9}]
[ { "hour": "2026-05-01T08:00:00Z", "avg_value": 15, "filled": false }, { "hour": "2026-05-01T09:00:00Z", "avg_value": 15, "filled": true }, { "hour": "2026-05-01T10:00:00Z", "avg_value": 5, "filled": false }, { "hour": "2026-05-01T11:00:00Z", "avg_value": 8, ...
Given a JSON list of {"ts": ISO8601 timestamp, "value": number} records, resample into hourly buckets from the earliest to the latest hour present, averaging values within each hour (rounded to 2 decimals). For hours with no records, forward-fill the last known average and mark 'filled': true; hours with real data get ...
cmsv89dsx01gmg4p2w5bi5rof
contributor_item
Submission BI5ROF
false
import json def transform(text): tree = json.loads(text) def rollup(node): if "children" not in node or not node["children"]: node["total"] = node.get("value", 0) return node["total"] total = node.get("value", 0) for child in node["children"]: total ...
{"name": "root", "value": 0, "children": [{"name": "A", "value": 5, "children": [{"name": "A1", "value": 3}, {"name": "A2", "value": 4}]}, {"name": "B", "value": 2, "children": [{"name": "B1", "value": 10}]}]}
{ "name": "root", "value": 0, "children": [ { "name": "A", "value": 5, "children": [ { "name": "A1", "value": 3, "total": 3 }, { "name": "A2", "value": 4, "total": 4 } ], "total": 12 }...
Given a JSON tree where each node has 'name', 'value', and optional 'children' (list of nodes), compute a 'total' field on every node equal to its own 'value' plus the recursive sum of all descendant 'value' fields (a hierarchical rollup). Return the tree as JSON with the added 'total' fields, preserving all original f...
cmsv89v6301gpg4p250ql61qo
contributor_item
Submission QL61QO
false
import json, re def transform(text): payload = json.loads(text) template = payload["template"] data = payload["data"] pattern = re.compile(r"\{\{\s*([\w.]+)\s*(?:\|\s*([^}]*?)\s*)?\}\}") def resolve(path): cur = data for part in path.split("."): if isinstance(cur, dict...
{"template": "Hello {{name|Guest}}, your order #{{order.id}} ships to {{order.city|Unknown City}}. Balance: {{account.balance|0}}", "data": {"name": "Priya", "order": {"id": "A1029", "city": ""}, "account": {}}}
"Hello Priya, your order #A1029 ships to Unknown City. Balance: 0"
Given a JSON object with a 'template' string containing placeholders of the form {{field.path}} or {{field.path|default}}, and a 'data' object, render the template by substituting each placeholder with the value found by following the dotted path in data. If the path resolves to a missing key or an empty string, use th...
cmsv8afc801gsg4p2bhfbweis
contributor_item
Submission FBWEIS
false
import json def transform(text): data = json.loads(text) values = [d["value"] for d in data] sorted_vals = sorted(values) n = len(sorted_vals) def percentile(p): idx = p * (n - 1) lo = int(idx) hi = min(lo + 1, n - 1) frac = idx - lo return sorted_vals[lo] +...
[{"id": 1, "value": 12}, {"id": 2, "value": 14}, {"id": 3, "value": 15}, {"id": 4, "value": 13}, {"id": 5, "value": 200}, {"id": 6, "value": 16}, {"id": 7, "value": 11}, {"id": 8, "value": -50}]
{ "q1": 11.75, "q3": 15.25, "iqr": 3.5, "lower_bound": 6.5, "upper_bound": 20.5, "kept": [ { "id": 1, "value": 12 }, { "id": 2, "value": 14 }, { "id": 3, "value": 15 }, { "id": 4, "value": 13 }, { "id": 6, "value...
Given a JSON list of {"id", "value"} records, detect outliers using the IQR method (linear-interpolation quartiles): compute Q1, Q3, IQR = Q3-Q1, and bounds [Q1-1.5*IQR, Q3+1.5*IQR]. Return a JSON object with 'q1', 'q3', 'iqr', 'lower_bound', 'upper_bound' (each rounded to 2 decimals), 'kept' (records within bounds, or...
cmsv8awvc01gvg4p244mzdze2
contributor_item
Submission MZDZE2
false
import json def transform(text): data = json.loads(text) triples = data["entries"] n_rows = data["rows"] n_cols = data["cols"] dense = [[0 for _ in range(n_cols)] for _ in range(n_rows)] for e in triples: dense[e["row"]][e["col"]] = e["value"] return json.dumps(dense)
{"rows": 3, "cols": 4, "entries": [{"row": 0, "col": 1, "value": 5}, {"row": 1, "col": 3, "value": 7}, {"row": 2, "col": 0, "value": 9}, {"row": 0, "col": 3, "value": 2}]}
[ [ 0, 5, 0, 2 ], [ 0, 0, 0, 7 ], [ 9, 0, 0, 0 ] ]
Given a JSON object with 'rows', 'cols' (dense matrix dimensions) and 'entries' (a sparse list of {"row", "col", "value"} triples), build the dense matrix as a 2D JSON array of size rows x cols, filling unspecified cells with 0 and placing each entry's value at its [row][col] position.
cmsv8bf0201gzg4p2f16u3pus
contributor_item
Submission 6U3PUS
false
import json, csv, io def transform(text): data = json.loads(text) out = io.StringIO() writer = csv.writer(out) writer.writerow(["source", "target", "weight"]) for node, edges in data.items(): for edge in edges: if isinstance(edge, dict): writer.writerow([node, ed...
{"A": [{"to": "B", "weight": 4}, {"to": "C", "weight": 2}], "B": [{"to": "C", "weight": 5}], "C": []}
"source,target,weight\r\nA,B,4\r\nA,C,2\r\nB,C,5"
Given a JSON adjacency-list graph where each key is a node name mapped to a list of edges (each edge either an object {"to", "weight"} or a plain node-name string implying weight 1), convert it into a CSV edge list with header 'source,target,weight', one row per edge in the order nodes and their edges appear in the inp...
cmsv8cag401h3g4p2nht7qn1w
contributor_item
Submission T7QN1W
false
import json def transform(text): data = json.loads(text) rates = data["rates"] # to USD txns = data["transactions"] out = [] grand_total = 0.0 for t in txns: currency = t["currency"] amount = t["amount"] if currency not in rates: out.append({**t, "usd_amount...
{"rates": {"EUR": 1.08, "GBP": 1.27, "USD": 1.0, "JPY": 0.0067}, "transactions": [{"id": "t1", "amount": 100, "currency": "EUR"}, {"id": "t2", "amount": 50, "currency": "GBP"}, {"id": "t3", "amount": 200, "currency": "USD"}, {"id": "t4", "amount": 1000, "currency": "JPY"}, {"id": "t5", "amount": 75, "currency": "CHF"}]...
{ "transactions": [ { "id": "t1", "amount": 100, "currency": "EUR", "usd_amount": 108 }, { "id": "t2", "amount": 50, "currency": "GBP", "usd_amount": 63.5 }, { "id": "t3", "amount": 200, "currency": "USD", "usd_amount": 200 ...
Given a JSON object with 'rates' (currency code -> USD conversion rate) and 'transactions' (list of {"id", "amount", "currency"}), convert each transaction's amount to USD (rounded to 2 decimals) using the rate table. If a transaction's currency isn't in the rate table, set its usd_amount to null and add an 'error' fie...
cmsv8dno601h7g4p2fmnr5314
contributor_item
Submission NR5314
false
import json, re from collections import Counter def transform(text): stopwords = {"the", "a", "an", "and", "or", "of", "to", "in", "is", "it", "on"} words = re.findall(r"[a-zA-Z']+", text.lower()) filtered = [w for w in words if w not in stopwords] counts = Counter(filtered) top = sorted(counts.ite...
The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs to the woods in the night.
{ "total_tokens": 13, "unique_tokens": 11, "frequencies": [ [ "dog", 2 ], [ "fox", 2 ], [ "barks", 1 ], [ "brown", 1 ], [ "jumps", 1 ], [ "lazy", 1 ], [ "night", 1 ], [ ...
Given a raw text passage, tokenize it into lowercase alphabetic word tokens (stripping punctuation), remove a fixed stopword list (the, a, an, and, or, of, to, in, is, it, on), and build a frequency table. Return JSON with 'total_tokens' (count after stopword removal), 'unique_tokens' (distinct word count), and 'freque...
cmsv8eux901hcg4p261kwffg0
contributor_item
Submission KWFFG0
false
import json def transform(text): payload = json.loads(text) schema = payload["schema"] # field -> type ("int","float","bool","str") records = payload["records"] def coerce(value, typ): if value is None: return None, False try: if typ == "int": r...
{"schema": {"id": "int", "price": "float", "active": "bool", "name": "str"}, "records": [{"id": "12", "price": "9.99", "active": "yes", "name": "Widget"}, {"id": "abc", "price": "5.5", "active": "true", "name": 42}, {"id": "3", "price": "7.25", "active": "maybe"}]}
[ { "record": { "id": 12, "price": 9.99, "active": true, "name": "Widget" }, "valid": true, "errors": [] }, { "record": { "id": "abc", "price": 5.5, "active": true, "name": "42" }, "valid": false, "errors": [ "invalid:id" ] ...
Given a JSON object with a 'schema' (field name -> one of "int","float","bool","str") and 'records' (list of objects with possibly wrong-typed string values), coerce each field's value to the declared type. Bool coercion accepts case-insensitive true/1/yes as true and false/0/no as false. If a field is missing from a r...
cmsv8g3y301hhg4p2fsp2kwwj
contributor_item
Submission P2KWWJ
false
import json def transform(text): intervals = json.loads(text) intervals = sorted(intervals, key=lambda iv: iv["start"]) merged = [] for iv in intervals: if merged and iv["start"] <= merged[-1]["end"]: merged[-1]["end"] = max(merged[-1]["end"], iv["end"]) merged[-1]["merg...
[{"start": 1, "end": 3, "label": "a"}, {"start": 2, "end": 6, "label": "b"}, {"start": 8, "end": 10, "label": "c"}, {"start": 15, "end": 18, "label": "d"}, {"start": 9, "end": 12, "label": "e"}]
[ { "start": 1, "end": 6, "merged_from": [ "a", "b" ] }, { "start": 8, "end": 12, "merged_from": [ "c", "e" ] }, { "start": 15, "end": 18, "merged_from": [ "d" ] } ]
Given a JSON list of intervals {"start", "end", "label"}, merge all overlapping or touching intervals (sorted by start) into a minimal set of non-overlapping intervals. Each merged interval must include 'start', 'end' (the union bounds) and 'merged_from' (list of the original labels combined into it, in the order they ...
cmsv8hdur01hmg4p28ver6uo2
contributor_item
Submission ER6UO2
false
import json, csv, io def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) rows = list(reader) categorical_col = "color" categories = sorted({r[categorical_col] for r in rows}) other_cols = [c for c in reader.fieldnames if c != categorical_col] out_fields = other_cols + [f"{c...
id,color,price 1,red,10 2,blue,20 3,green,15 4,red,12
"id,price,color_blue,color_green,color_red\r\n1,10,0,0,1\r\n2,20,1,0,0\r\n3,15,0,1,0\r\n4,12,0,0,1"
Given a CSV string with columns including a categorical 'color' column, one-hot encode the 'color' column into separate binary columns named 'color_<value>' (one per distinct category found, sorted alphabetically), placed after the other original columns in their original order (with 'color' itself removed). Return the...
cmsv8icih01hqg4p22fcuac4l
contributor_item
Submission CUAC4L
false
import json def transform(text): values = json.loads(text) window = 3 result = [] for i in range(len(values)): lo = max(0, i - window + 1) window_vals = values[lo:i+1] avg = round(sum(window_vals) / len(window_vals), 3) result.append(avg) return json.dumps(result)
[10, 20, 30, 40, 50, 60]
[ 10, 15, 20, 30, 40, 50 ]
Given a JSON list of numeric values, compute a trailing simple moving average with a window size of 3. For each position i, average the current value together with up to the previous 2 values (using a smaller partial window near the start of the list rather than padding). Return a JSON list of the moving averages (roun...
cmsv8j43m01hug4p27xknwy92
contributor_item
Submission KNWY92
false
import json, re def transform(text): records = json.loads(text) def mask_email(email): m = re.match(r"^(.)([^@]*)(@.*)$", email) if not m: return email first, rest, domain = m.groups() return f"{first}{'*' * len(rest)}{domain}" def mask_phone(phone): di...
[{"name": "Alice", "email": "alice.j@example.com", "phone": "+1-415-555-2671"}, {"name": "Bob", "email": "bob@work.org", "phone": "555.123.9876"}]
[ { "name": "Alice", "email": "a******@example.com", "phone": "*******2671" }, { "name": "Bob", "email": "b**@work.org", "phone": "******9876" } ]
Given a JSON list of {"name", "email", "phone"} records, mask each email by keeping only the first character of the local part visible and replacing the rest of the local part with asterisks (domain unchanged), and mask each phone number by stripping non-digit characters and replacing all but the last 4 digits with ast...
cmsv8jp9o01hyg4p272s96mgr
contributor_item
Submission S96MGR
false
import json def transform(text): data = json.loads(text) out = [] max_depth = [0] def flatten(item, depth): max_depth[0] = max(max_depth[0], depth) if isinstance(item, list): for x in item: flatten(x, depth + 1) else: out.append({"value":...
[1, [2, 3], [4, [5, 6, [7]]], 8]
{ "items": [ { "value": 1, "depth": 1 }, { "value": 2, "depth": 2 }, { "value": 3, "depth": 2 }, { "value": 4, "depth": 2 }, { "value": 5, "depth": 3 }, { "value": 6, "depth": 3 }, { "valu...
Given a JSON value that is an arbitrarily nested list of numbers (lists inside lists inside lists), flatten it into a single sequence of {"value", "depth"} objects where 'depth' is the nesting level at which that number was found (top-level numbers directly in the outermost list have depth 1). Return JSON with 'items' ...
cmsv8k89y01i2g4p2jfazxnuv
contributor_item
Submission AZXNUV
false
import json def transform(text): seq = text.strip() if not seq: return json.dumps([]) result = [] count = 1 prev = seq[0] for ch in seq[1:]: if ch == prev: count += 1 else: result.append([prev, count]) prev = ch count = 1 ...
aaabbbcccaabb
[ [ "a", 3 ], [ "b", 3 ], [ "c", 3 ], [ "a", 2 ], [ "b", 2 ] ]
Given a raw string of characters, perform run-length encoding: return a JSON list of [character, count] pairs representing consecutive runs of identical characters in the order they appear in the string.
cmsv8kqxl01i6g4p2xl0orxxg
contributor_item
Submission 0ORXXG
false
import json def transform(text): matrix = json.loads(text) rows = len(matrix) cols = len(matrix[0]) if rows else 0 result = [] for diag in range(rows + cols - 1): diag_elems = [] r_start = max(0, diag - cols + 1) r_end = min(rows - 1, diag) for r in range(r_start, r_...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[ 1, 2, 4, 7, 5, 3, 6, 8, 9 ]
Given a JSON 2D matrix (list of equal-length row lists), produce its zigzag diagonal traversal order (as used for JPEG-style scans): traverse anti-diagonals in order, alternating the direction of each diagonal (even-indexed diagonals from bottom-left to top-right reversed to top-right-to-bottom-left order relative to s...
cmsv8lagw01i9g4p23c06k303
contributor_item
Submission 06K303
false
import json def transform(text): payload = json.loads(text) scores = payload["scores"] bin_width = payload["bin_width"] lo = payload.get("min", min(scores)) hi = payload.get("max", max(scores)) n_bins = int((hi - lo) // bin_width) + 1 bins = [{"range_start": lo + i * bin_width, "range_end"...
{"scores": [55, 62, 71, 68, 90, 95, 100, 45, 73, 80, 61], "bin_width": 10, "min": 40, "max": 100}
[ { "range_start": 40, "range_end": 50, "count": 1 }, { "range_start": 50, "range_end": 60, "count": 1 }, { "range_start": 60, "range_end": 70, "count": 3 }, { "range_start": 70, "range_end": 80, "count": 2 }, { "range_start": 80, "range_end": 90...
Given a JSON object with 'scores' (list of numbers), 'bin_width', and optional 'min'/'max' bounds (defaulting to the data's own min/max), bucket the scores into fixed-width bins starting at 'min' and covering at least up to 'max'. Values beyond the highest bin's range are clamped into the last bin. Return a JSON list o...
cmsv8lvef01icg4p28x1kblzk
contributor_item
Submission 1KBLZK
false
import json from datetime import date def transform(text): data = json.loads(text) users = data["users"] cohorts = {} for u in users: signup = u["signup_date"] cohorts.setdefault(signup, {"users": [], "count": 0}) cohorts[signup]["users"].append(u) cohorts[signup]["coun...
{"users": [{"id": "u1", "signup_date": "2026-01-01", "active_dates": ["2026-01-02", "2026-01-10", "2026-01-20"]}, {"id": "u2", "signup_date": "2026-01-01", "active_dates": ["2026-01-03"]}, {"id": "u3", "signup_date": "2026-01-01", "active_dates": ["2026-01-02", "2026-01-09"]}]}
[ { "cohort": "2026-01-01", "cohort_size": 3, "retention": [ { "week": 0, "active_users": 3, "retention_pct": 100 }, { "week": 1, "active_users": 2, "retention_pct": 66.7 }, { "week": 2, "active_users": 1, ...
Given a JSON object with 'users' (each having 'signup_date' YYYY-MM-DD and 'active_dates' a list of YYYY-MM-DD activity dates), group users into cohorts by signup_date, and for each cohort compute weekly retention: for week offset w (0, 1, 2, ...), the count and percentage of that cohort's users who had at least one ac...
cmsv8mic601igg4p2qgaprmgb
contributor_item
Submission APRMGB
false
import json def transform(text): result = {} current_section = None for raw_line in text.strip().split("\n"): line = raw_line.strip() if not line or line.startswith(";") or line.startswith("#"): continue if line.startswith("[") and line.endswith("]"): current...
; global config [server] host = localhost port = 8080 debug = true [database] name = mydb timeout = 30.5 ssl = false
{ "server": { "host": "localhost", "port": 8080, "debug": true }, "database": { "name": "mydb", "timeout": 30.5, "ssl": false } }
Given a plain-text INI-style config string with [section] headers, key = value lines, and comment lines starting with ';' or '#', parse it into a nested JSON object mapping each section name to an object of its key/value pairs. Coerce values: 'true'/'false' (case-insensitive) become booleans, values parseable as intege...
cmsv9q98m01kig4p2fpkjyebw
contributor_item
Submission KJYEBW
false
def transform(text): tokens = [] buf = [] in_quotes = False in_comment = False def flush(): if buf: tokens.append(''.join(buf)) del buf[:] for ch in text: if in_comment: if ch == '\n': in_comment = False continue ...
worker_processes auto; events { worker_connections 1024; } http { sendfile on; # push files fast gzip on; server { listen 443 ssl; server_name shop.example.com; location /api/ { proxy_pass http://backend; proxy_set_header Host $host; } ...
"worker_processes = auto\nevents/worker_connections = 1024\nhttp/sendfile = on\nhttp/gzip = on\nhttp/server/listen = 443 ssl\nhttp/server/server_name = shop.example.com\nhttp/server/location[/api/]/proxy_pass = http://backend\nhttp/server/location[/api/]/proxy_set_header = Host $host\nhttp/server/location[= /healthz]/r...
Flatten an nginx-style configuration file into one line per simple directive. Lexing rules: 1. A '#' starts a comment that runs to end of line, EXCEPT when the '#' is inside a double-quoted string. Comments are removed before anything else. 2. The three structural characters are '{', '}' and ';'. Outside double quo...
cmsv9q98m01kjg4p23azakamx
contributor_item
Submission ZAKAMX
false
import re HEADER = re.compile(r'^([a-z]+)(?:\(([^()]*)\))?(!)?: +(.*)$') TYPE_SECTION = { 'feat': 'Features', 'fix': 'Bug Fixes', 'perf': 'Performance', 'refactor': 'Refactoring', 'docs': 'Documentation', } ORDER = ['BREAKING CHANGES', 'Features', 'Bug Fixes', 'Performance', 'Refactoring',...
9f2a1c4 feat(auth): add device-code login flow 1b7de90 fix(api): return 422 instead of 500 on bad cursor c04ea11 chore: bump ruff to 0.6.2 77bb213 feat(api)!: drop the deprecated /v1/search endpoint aa10f5e docs(readme): clarify install steps 3ce9b02 fix: guard against empty upload manifests 5d8c447 refactor(core): ext...
"## BREAKING CHANGES\n- **api**: drop the deprecated /v1/search endpoint (77bb213)\n\n## Features\n- **auth**: add device-code login flow (9f2a1c4)\n- **api**: drop the deprecated /v1/search endpoint (77bb213)\n- **billing**: support annual invoicing (6620fd1)\n\n## Bug Fixes\n- **api**: return 422 instead of 500 on ba...
Turn `git log --oneline` output into grouped release notes. Each input line is '<sha> <subject>'. Split on the first space; the sha is the first field. Classify each subject against the Conventional Commits header grammar type[(scope)][!]: description where type is one or more lowercase ASCII letters, scope (opti...
cmsv9q98m01khg4p2zqo2gjmr
contributor_item
Submission O2GJMR
false
def transform(text): groups = [] current_agents = None current_rules = None expecting_agents = False for raw in text.split('\n'): line = raw.split('#', 1)[0].strip() if not line or ':' not in line: continue field, value = line.split(':', 1) field = field....
# Acme storefront robots policy User-agent: * Disallow: /cart Disallow: /checkout/ Allow: /checkout/help Crawl-delay: 10 User-agent: GoogleBot user-agent: bingbot Disallow: Allow: / User-agent: BadBot Disallow: / Crawl-delay: 3.5 Sitemap: https://example.com/sitemap.xml
"* | allow=/checkout/help | disallow=/cart,/checkout/ | delay=10.0\nbadbot | allow=none | disallow=/ | delay=3.5\nbingbot | allow=/ | disallow=none | delay=-\ngooglebot | allow=/ | disallow=none | delay=-"
Parse a robots.txt file into a per-user-agent report. Rules: 1. Strip everything from the first '#' on each line, then strip surrounding whitespace. Drop empty lines. 2. Each remaining line is 'field: value' split on the first ':'. Field names are matched case-insensitively and lowercased. Values keep their origina...
cmsv9q98m01kng4p2tm80ft83
contributor_item
Submission 80FT83
false
import re TOKEN = re.compile(r'^([A-G])(#*|b*)(-?\d+)$') BASE = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} def transform(text): out = [] valid = invalid = out_of_range = 0 for raw in text.split('\n'): tokens = raw.split() if not tokens: continue parts = ...
A4 C4 G#3 Bb5 C-1 B8 Fb4 E#4 Cbb4 G##2 H4 A 4b D9 A-2
"A4=69 C4=60 G#3=56 Bb5=82\nC-1=0 B8=119 Fb4=64 E#4=65\nCbb4=58 G##2=45\nH4=? A=? 4b=?\nD9=122 A-2=!\nvalid=11 invalid=3 out_of_range=1"
Each non-empty input line holds whitespace-separated scientific-pitch note tokens. Convert each token to a MIDI note number. Token grammar: a letter A-G (uppercase only), then zero or more accidentals which must be all '#' or all 'b' (mixing them is invalid), then an octave which is an optional '-' followed by one or ...
cmsv9q98m01kkg4p2uxpnzdli
contributor_item
Submission PNZDLI
false
import re TIMING = re.compile( r'^(\d+):(\d{2}):(\d{2}),(\d{3})\s*-->\s*(\d+):(\d{2}):(\d{2}),(\d{3})$') SHIFT_MS = 1500 def _fmt(ms): hours, rest = divmod(ms, 3600000) minutes, rest = divmod(rest, 60000) seconds, millis = divmod(rest, 1000) return '%02d:%02d:%02d,%03d' % (hours, minutes, seconds...
1 00:00:02,500 --> 00:00:05,000 Welcome back to the workshop. 2 00:00:05,000 --> 00:00:07,250 Today we are wiring the sensor board. 3 00:00:01,000 --> 00:00:03,750 - Hold on. - I dropped a screw. 4 00:59:58,900 --> 01:00:02,100 And that rolls us past the hour mark.
"1\n00:00:00,000 --> 00:00:02,250\n- Hold on.\n- I dropped a screw.\n\n2\n00:00:01,000 --> 00:00:03,500\nWelcome back to the workshop.\n\n3\n00:00:03,500 --> 00:00:05,750\nToday we are wiring the sensor board.\n\n4\n00:59:57,400 --> 01:00:00,600\nAnd that rolls us past the hour mark."
Shift every cue in an SRT subtitle file 1500 milliseconds EARLIER and re-emit valid SRT. Input blocks are separated by one or more blank lines. Each block is: an index line, a timing line 'HH:MM:SS,mmm --> HH:MM:SS,mmm', then one or more text lines. Rules: 1. Convert both timestamps to milliseconds and subtract 1500....
cmsv9q98m01klg4p2qloi2ed4
contributor_item
Submission OI2ED4
false
import re from decimal import Decimal, ROUND_HALF_EVEN NUMBER = re.compile(r'-?\d+(?:\.\d+)?') QUANT = Decimal('0.000001') def _fmt(value): return str(value.quantize(QUANT, rounding=ROUND_HALF_EVEN)) def transform(text): lines = [line for line in text.split('\n') if line.strip()] rows = [] for line...
parcel_id;geometry P-001;POLYGON ((-3.70379 40.41678, -3.70102 40.41681, -3.70098 40.41502, -3.70381 40.41499, -3.70379 40.41678)) P-002;POLYGON ((12.4924 41.8902, 12.4951 41.8902, 12.4951 41.8886, 12.4924 41.8886, 12.4924 41.8902), (12.4930 41.8898, 12.4945 41.8898, 12.4945 41.8890, 12.4930 41.8890, 12.4930 41.8898)) ...
"P-001|-3.703810|40.414990|-3.700980|40.416810|0.000005\nP-002|12.492400|41.888600|12.495100|41.890200|0.000004\nP-003|0.000000|0.000000|6.000000|6.000000|36.000000\nP-004|7.500000|-1.250000|7.500000|-1.250000|0.000000\nP-005|EMPTY|EMPTY|EMPTY|EMPTY|0.000000"
The input is a semicolon-delimited file with a header row 'parcel_id;geometry'. Each data row holds a WKT geometry. Emit a bounding-box table. Rules: 1. Skip the header row and any blank line. 2. Split each data row on the FIRST ';' only; the remainder is the WKT string. 3. Extract every coordinate pair from the WKT b...
cmsv9q98m01kmg4p2ym9mc7bd
contributor_item
Submission 9MC7BD
false
import re TOKEN = re.compile(r'([A-Z][a-z]{0,2})(\d*)|([\(\[])|([\)\]])(\d*)') def _parse_segment(segment): coefficient = 1 i = 0 while i < len(segment) and segment[i].isdigit(): i += 1 if i: coefficient = int(segment[:i]) segment = segment[i:] stack = [{}] pos = 0 ...
H2O Ca(OH)2 K4[Fe(CN)6] CuSO4.5H2O Mg(NO3)2 C6H5COOH Al2(SO4)3
"H2O -> H2, O1 = 3 atoms\nCa(OH)2 -> Ca1, H2, O2 = 5 atoms\nK4[Fe(CN)6] -> C6, Fe1, K4, N6 = 17 atoms\nCuSO4.5H2O -> Cu1, H10, O9, S1 = 21 atoms\nMg(NO3)2 -> Mg1, N2, O6 = 9 atoms\nC6H5COOH -> C7, H6, O2 = 15 atoms\nAl2(SO4)3 -> Al2, O12, S3 = 17 atoms"
Each non-empty input line is a chemical formula. Produce the element tally for each. Grammar: - An element symbol is one uppercase ASCII letter optionally followed by one or two lowercase letters. - A symbol or a closing bracket may be followed by a multiplier: one or more digits. Absent means 1. - '(' ... ')' and '['...
cmsv9q98m01kog4p2gxiupov0
contributor_item
Submission IUPOV0
false
from decimal import Decimal TYPE_RANK = {'CREDIT': 0, 'DEBIT': 1, 'FEE': 2} CENTS = Decimal('0.01') def _money(value): return str(value.quantize(CENTS)).rjust(10) def transform(text): lines = [line.strip() for line in text.split('\n') if line.strip()] header = lines[0].split(',') balance = Decima...
OPENING,2026-04-30,1420.55 2026-05-03,DEBIT,Rent Housing Co,-950.00 2026-05-02,CREDIT,Payroll ACME,2310.40 2026-05-03,DEBIT,Grocery Mart,-73.19 2026-05-03,FEE,Monthly service fee,-4.50 2026-05-05,DEBIT,Utility Gas,-118.07 2026-05-05,CREDIT,Refund Utility Gas,118.07 2026-05-01,DEBIT,Coffee Kiosk,-6.25 2026-05-06,DEBIT,C...
"OPENING 1420.55\n2026-05-01 Coffee Kiosk -6.25 1414.30\n2026-05-02 Payroll ACME 2310.40 3724.70\n2026-05-03 Rent Housing Co -950.00 2774.70\n2026-05-03 Grocery Mart -73.19 2701.51\n2026-05-03 Monthly service fee -4.50 2697.01\n2026-05-05 Ref...
The first line is 'OPENING,<date>,<amount>' giving the opening balance. Every following non-empty line is '<date>,<type>,<description>,<amount>' with an ISO date, a type of CREDIT, DEBIT or FEE, a description that never contains a comma, and a signed decimal amount with exactly two decimal places. Produce a running-ba...
cmsv9q98n01kug4p2irv21kam
contributor_item
Submission V21KAM
false
import csv import io from decimal import Decimal, ROUND_HALF_UP TENTH = Decimal('0.1') def transform(text): reader = csv.reader(io.StringIO(text)) rows = [row for row in reader if row and any(cell.strip() for cell in row)] body = rows[1:] ranked = [] excluded = [] for row in body: na...
student,score kim,88 ana,72 raj,95 lee,72 mo,61 tam,88 bo,40 wei,99 ivy,72 sam,55 eve, gus,83
"1\twei\t99\t90.9\ttop\n2\traj\t95\t81.8\thigh\n3\tkim\t88\t63.6\tmid\n3\ttam\t88\t63.6\tmid\n5\tgus\t83\t54.5\tmid\n6\tana\t72\t27.3\tlow\n6\tivy\t72\t27.3\tlow\n6\tlee\t72\t27.3\tlow\n9\tmo\t61\t18.2\tlow\n10\tsam\t55\t9.1\tlow\n11\tbo\t40\t0.0\tlow\nexcluded: eve\nranked=11 distinct_scores=8"
The input is CSV with header 'student,score'. Rank the students and assign percentile bands. Rules: 1. Rows whose score cell is empty or not an integer are EXCLUDED from ranking and from all statistics; they are reported separately at the end. 2. Ranking uses competition ranking ('1224'): sort scores descending; eq...
cmsv9q98n01kvg4p2u0xrzdrl
contributor_item
Submission XRZDRL
false
def transform(text): nodes = set() edges = set() for raw in text.split('\n'): line = raw.strip() if not line or line.startswith('#'): continue if '->' in line: left, right = line.split('->', 1) source, target = left.strip(), right.strip() ...
# service call graph api -> auth api -> billing auth -> cache billing -> cache api -> auth cache -> cache reports -> billing auth -- session orphan billing -> Reports
"Reports out:0 in:1 -> -\napi out:2 in:0 -> auth,billing\nauth out:2 in:2 -> cache,session\nbilling out:2 in:2 -> Reports,cache\ncache out:1 in:3 -> cache\norphan out:0 in:0 -> -\nreports out:1 in:0 -> billing\nsession out:1 in:1 -> auth\nnodes=8 edges=9 selfloops=1 sinks=2"
Build an adjacency report from a directed edge list. Parsing: 1. Lines are stripped; blank lines and lines starting with '#' are ignored. 2. An edge line contains '->' (directed, left to right) or '--' (undirected). '->' is tested first, so a line containing both is treated as directed on its FIRST '->'. An undirec...
cmsv9q98n01ksg4p2y09ujgl1
contributor_item
Submission 9UJGL1
false
import re UUID_RE = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') NIL = '00000000-0000-0000-0000-000000000000' GROUP_ORDER = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'nil', 'non-rfc', 'unknown', 'invalid'] def _normalise(token): value = token.strip() if ...
6fa459ea-ee8a-3ca4-894e-db77e160355e 886313e1-3b8a-5372-9b90-0c9aee199e5d F47AC10B-58CC-4372-A567-0E02B2C3D479 urn:uuid:016e6cb2-0b17-7c1a-8e6b-2f4d9a1c7c33 00000000-0000-0000-0000-000000000000 {c232ab00-9414-11ec-b3c8-9f6bdeced846} not-a-uuid-at-all f47ac10b-58cc-4372-a567-0e02b2c3d479 12345678-1234-6234-c234-12345678...
"v1: 1 -> c232ab00-9414-11ec-b3c8-9f6bdeced846\nv3: 1 -> 6fa459ea-ee8a-3ca4-894e-db77e160355e\nv4: 1 -> f47ac10b-58cc-4372-a567-0e02b2c3d479\nv5: 1 -> 886313e1-3b8a-5372-9b90-0c9aee199e5d\nv7: 1 -> 016e6cb2-0b17-7c1a-8e6b-2f4d9a1c7c33\nnil: 1 -> 00000000-0000-0000-0000-000000000000\nnon-rfc: 1 -> 12345678-1234-6234-c23...
Group a list of candidate UUID strings by RFC 9562 version. Normalisation before parsing: strip surrounding whitespace, remove a leading 'urn:uuid:' prefix (case-insensitive), and remove one pair of surrounding braces '{' '}' if present. Then lowercase. A token is a valid UUID only if what remains matches exactly 8-4-...
cmsv9q98n01kyg4p2pogoknw0
contributor_item
Submission GOKNW0
false
def _parse(line): if line.count('/') != 1: return None address, prefix_text = line.split('/') if not prefix_text.isdigit(): return None prefix = int(prefix_text) if prefix > 32: return None parts = address.split('.') if len(parts) != 4: return None value =...
10.0.0.0/24 192.168.1.128/25 172.16.5.7/32 203.0.113.6/31 10.0.0.0/8 198.51.100.77/26 0.0.0.0/0 10.0.0.5/24 256.1.1.1/24 192.168.1.0/33
"0.0.0.0/0 0.0.0.0-255.255.255.255 total=4294967296 usable=4294967294\n10.0.0.0/8 10.0.0.0-10.255.255.255 total=16777216 usable=16777214\n10.0.0.0/24 10.0.0.0-10.0.0.255 total=256 usable=254\n172.16.5.7/32 172.16.5.7-172.16.5.7 total=1 usable=1\n192.168.1.128/25 192.168.1.128-192.168.1.255 total=128 usable=126\n198.51....
Each non-empty input line is a candidate IPv4 CIDR block 'A.B.C.D/P'. Produce a network table. Validation: the address must be four dot-separated decimal octets, each 0-255 with no leading '+'/'-' and no empty part; the prefix must be an integer 0-32. Anything else is INVALID. For a valid entry: - network address = a...
cmsv9q98n01kzg4p2tn9hiqs7
contributor_item
Submission 9HIQS7
false
import re MOVE_NUMBER = re.compile(r'^\d+\.+$') NAG = re.compile(r'^\$\d+$') RESULTS = ('1-0', '0-1', '1/2-1/2', '*') SUFFIXES = ('!!', '??', '!?', '?!', '!', '?') def _strip_braces(text): out = [] depth = 0 for ch in text: if ch == '{': depth += 1 continue if ch =...
[Event "Club Championship"] [White "Ortiz, M."] [Black "Novak, P."] [Result "1/2-1/2"] 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 {the Morphy defence} 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8!? 10. d4 Nbd7 11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 $14 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5 Nxe4 (17... dxe5 18. Nb...
"1. W e4\n2. B e5\n3. W Nf3\n4. B Nc6\n5. W Bb5\n6. B a6\n7. W Ba4\n8. B Nf6\n9. W O-O\n10. B Be7\n11. W Re1\n12. B b5\n13. W Bb3\n14. B d6\n15. W c3\n16. B O-O\n17. W h3\n18. B Nb8 [!?]\n19. W d4\n20. B Nbd7\n21. W c4\n22. B c6\n23. W cxb5\n24. B axb5\n25. W Nc3\n26. B Bb7\n27. W Bg5\n28. B b4\n29. W Nb1\n30. B h6\n31...
Convert PGN movetext into a numbered ply list. Preprocessing, in this order: 1. Drop every tag-pair line, i.e. a stripped line starting with '['. 2. Remove brace comments '{...}' (they do not nest in this input). 3. Remove recursive variations delimited by '(' and ')', including everything inside; these MAY nest and ...
cmsv9q98m01kgg4p28eod9u5v
contributor_item
Submission OD9U5V
false
import datetime def transform(text): raw_lines = text.split('\n') unfolded = [] for line in raw_lines: line = line.rstrip('\r') if line[:1] in (' ', '\t') and unfolded: unfolded[-1] += line[1:] else: unfolded.append(line) def unescape(value): ou...
BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Acme Corp//Scheduler 4.1//EN BEGIN:VEVENT UID:evt-1001@acme.example DTSTART:20260914T090000Z DTEND:20260914T100000Z SUMMARY:Sprint planning LOCATION:Room 3B END:VEVENT BEGIN:VEVENT UID:evt-1002@acme.example DTSTART:20260914T090000Z DTEND:20260914T093000Z SUMMARY:Coffee sync with th...
"2026-09-13 23:30-00:30 | Release cutover | War room | 60m\n2026-09-14 09:00-09:30 | Coffee sync with the platform team, part two | TBD | 30m\n2026-09-14 09:00-10:00 | Sprint planning | Room 3B | 60m"
The input is an iCalendar (RFC 5545) stream in UTC. Produce a plain-text agenda. Parsing rules: 1. Consider only content between BEGIN:VEVENT and END:VEVENT lines. Ignore every other line. 2. Unfold folded content lines first: any line that begins with a single space or a horizontal tab is a continuation of the pre...
cmsv9q98m01kpg4p23a8a4nsr
contributor_item
Submission 8A4NSR
false
import json import re LINE = re.compile(r'^( *)- +(.*)$') def transform(text): roots = [] # stack of (indent, node); node is None for the synthetic root container stack = [(-1, None)] for raw in text.split('\n'): if not raw.strip(): continue match = LINE.match(raw.rstrip()...
- Platform - Ingest - Kafka bridge - S3 poller - Storage - Cold tier - Query - Frontend - Web - Dashboard - Mobile - Ops
[ { "name": "Platform", "children": [ { "name": "Ingest", "children": [ { "name": "Kafka bridge", "children": [] }, { "name": "S3 poller", "children": [] } ] }, { "name": "...
Convert an indented bullet outline into a JSON tree. Rules: 1. Ignore blank lines. Every other line matches optional spaces, then '- ', then the label. Tabs never appear. The label is stripped of surrounding whitespace. 2. Indentation is measured in leading spaces. Depth is derived from a stack of seen indent colum...
cmsv9q98m01kqg4p2k7c3uemk
contributor_item
Submission C3UEMK
false
import csv import io import re HEAD = re.compile(r'^\s*INSERT\s+INTO\s+([A-Za-z_][A-Za-z_0-9]*)\s*\(([^)]*)\)\s*VALUES\s*(.*)$', re.IGNORECASE | re.DOTALL) def _split_statements(text): kept = [] for line in text.split('\n'): if line.strip().startswith('--'): continue ...
INSERT INTO staff (id, name, title, salary, active) VALUES (1, 'Ada Lovelace', 'Analyst', 91000.00, TRUE); INSERT INTO staff (id, name, title, salary, active) VALUES (2, 'Grace O''Hara', 'Lead, Platform', 128500.5, TRUE), (3, 'Linus T', NULL, 74000, FALSE); -- a commented out row -- INSERT INTO staff (id, name) VAL...
"id,name,title,salary,active\n1,Ada Lovelace,Analyst,91000.00,true\n2,Grace O'Hara,\"Lead, Platform\",128500.5,true\n3,Linus T,,74000,false\n4,\"Ren \"\"Rex\"\" Diaz\",QA,66000,true"
Extract rows from SQL INSERT statements into RFC 4180 CSV, keeping only the table named 'staff'. Rules: 1. A line whose stripped form starts with '--' is a comment and is removed before parsing. '--' inside a single-quoted string literal is NOT a comment (only whole-line comments exist in this input). 2. Statements...
cmsv9q98m01krg4p288fwn30d
contributor_item
Submission FWN30D
false
from urllib.parse import unquote CANON = { 'domain': 'Domain', 'path': 'Path', 'expires': 'Expires', 'max-age': 'Max-Age', 'samesite': 'SameSite', 'secure': 'Secure', 'httponly': 'HttpOnly', } SAMESITE = {'strict': 'Strict', 'lax': 'Lax', 'none': 'None'} def transform(text): cookies =...
Set-Cookie: sid=3f9a2b; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600 Set-Cookie: theme=dark; Path=/; Expires=Wed, 09 Jun 2027 10:18:14 GMT Set-Cookie: sid=deadbeef; Domain=.example.com; Path=/admin; secure; samesite=strict Set-Cookie: tracking=; Path=/; Max-Age=0 Set-Cookie: prefs=lang%3Den-GB X-Frame-Options: ...
"prefs | lang=en-GB | domain=- | path=/ | flags=- | samesite=- | max-age=- | expires=-\nsid | 3f9a2b | domain=- | path=/ | flags=Secure+HttpOnly | samesite=Lax | max-age=3600 | expires=-\nsid | deadbeef | domain=.example.com | path=/admin | flags=Secure | samesite=Strict | max-age=- | expires=-\ntheme | dark | domain=-...
Parse HTTP Set-Cookie response headers into an attribute table. Rules: 1. Only lines whose header name is 'set-cookie' (case-insensitive, split on the first ':') are used; every other header line is ignored. 2. The value is split on ';'. The FIRST segment is 'name=value' (split on the first '='); later segments ...
cmsv9q98n01kxg4p245njq1y1
contributor_item
Submission NJQ1Y1
false
import csv import io from decimal import Decimal, ROUND_HALF_UP REGIONS = { 'Europe': ['DE', 'FR', 'GB', 'ES', 'IT', 'NL', 'PL', 'SE'], 'Americas': ['US', 'CA', 'BR', 'MX', 'AR', 'CL'], 'Asia': ['JP', 'IN', 'CN', 'SG', 'KR', 'ID'], 'Africa': ['ZA', 'KE', 'NG', 'EG', 'MA'], 'Oceania': ['AU', 'NZ', '...
order_id,country,amount_minor A-1,de,4500 A-2,FR,12000 A-3,us,3999 A-4,JP,88000 A-5,gb,15050 A-6,BR,7200 A-7,ZZ,1000 A-8,IN,2500 A-9,CA,6100 A-10,de,500 A-11,,900 A-12,ke,3300 A-13,AU,20000
"Asia: orders=2 total=905.00 share=54.8% codes=IN/JP\nEurope: orders=4 total=320.50 share=19.4% codes=DE/FR/GB\nOceania: orders=1 total=200.00 share=12.1% codes=AU\nAmericas: orders=3 total=172.99 share=10.5% codes=BR/CA/US\nAfrica: orders=1 total=33.00 share=2.0% codes=KE\nUnknown: orders=2 total=19.00 share=1.2% code...
The input is CSV with header 'order_id,country,amount_minor'. Roll order amounts up to macro regions. Use exactly this ISO 3166-1 alpha-2 to region map (codes compared case-insensitively after stripping): Europe: DE, FR, GB, ES, IT, NL, PL, SE Americas: US, CA, BR, MX, AR, CL Asia: JP, IN, CN, SG, KR, ID Afric...
cmsv9q98n01ktg4p2xto16yot
contributor_item
Submission O16YOT
false
CODES = { '.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', ...
.... . .-.. .-.. --- / .-- --- .-. .-.. -.. ... --- ... / -. --- .-- .-.-.- / .- - / ..--- .---- ....- ---.. -- .- -.-- -.. .- -.-- ..!! / ---... / -.-.-- -.-.-.-.-.- / .- -... -.-.
"1. HELLO WORLD\n2. SOS NOW. AT 2148\n3. MAYDAY[?] : !\n4. [?] ABC\nundecodable=2"
Decode International Morse Code into text. Structure: each input line is a message. Within a line, ' / ' (slash surrounded by spaces, or a bare '/' token) separates words, and single spaces separate letters. Blank lines are skipped entirely and produce no output line. Supported codes: the 26 ASCII letters A-Z, the di...
cmsv9q98n01kwg4p20kx3orpc
contributor_item
Submission X3ORPC
false
MAJOR_CATS = {'removed', 'breaking'} MINOR_CATS = {'added', 'changed', 'deprecated'} PATCH_CATS = {'fixed', 'security', 'performance'} def transform(text): blocks = [] current = [] for raw in text.split('\n'): line = raw.strip() if line == '---': blocks.append(current) ...
current: 2.4.9 --- added: streaming export endpoint fixed: crash when the manifest is empty deprecated: legacy /v1/search remains but warns security: patch header smuggling in the proxy --- current: 0.7.3 --- removed: the XML serialiser fixed: retry accounting off by one --- current: 1.0.0 --- changed: default page siz...
"2.4.9 -> 2.5.0 (minor)\n0.7.3 -> 0.8.0 (minor(major-demoted))\n1.0.0 -> 1.1.0 (minor)\n3.1.4 -> 3.1.4 (none)\n1.9.2-rc.1+build.7 -> 1.9.3 (patch)"
Decide the next SemVer 2.0.0 version for each release block. Input structure: a sequence of blocks separated by lines containing exactly '---'. A block that starts with 'current: <version>' opens a release; the block that follows it holds that release's change lines. Each change line is '<category>: <text>'; the categ...
cmsvchtev01o0g4p2xuy6extl
contributor_item
Submission Y6EXTL
false
def transform(text): rows = [] for line in text.strip().split('\n')[1:]: if not line.strip(): continue name, dept, salary = [p.strip() for p in line.split(',')] rows.append((dept, name, int(salary))) groups = {} for dept, name, salary in rows: groups.setdefaul...
name,dept,salary zed,eng,100 amy,eng,120 bo,ops,90 cy,eng,120 dee,ops,95
"eng: 3, 340, amy\nops: 2, 185, dee"
Given rows of 'name,dept,salary', return one line per department as 'dept: count, total, top' where top is the highest-paid member, ties broken alphabetically. Departments are ordered alphabetically.
cmsvchtev01nyg4p23hte49vy
contributor_item
Submission TE49VY
false
def transform(text): seen = {} for part in text.split(';'): if not part.strip(): continue key, _, value = part.partition('=') seen[key.strip()] = value.strip() return '\n'.join('{} -> {}'.format(k, seen[k]) for k in sorted(seen))
b=2;a=1;;c=3;a=9; d = 4 ;
"a -> 9\nb -> 2\nc -> 3\nd -> 4"
Read semicolon-separated key=value pairs and return them as sorted 'key -> value' lines, where a key repeated later overrides the earlier value and blank segments are ignored.
cmsvchtev01o1g4p21fy4vznb
contributor_item
Submission Y4VZNB
false
def transform(text): counters = [] out = [] for line in text.strip().split('\n'): if not line.strip(): continue depth_s, _, title = line.partition('|') depth = int(depth_s) while len(counters) > depth + 1: counters.pop() if len(counters) == dep...
0|Intro 1|Scope 1|Audience 0|Method 1|Setup 2|Hardware 0|Results
"1. Intro\n1.1. Scope\n1.2. Audience\n2. Method\n2.1. Setup\n2.1.1. Hardware\n3. Results"
Convert an ordered list of 'depth|text' outline rows into numbered section headings such as 1., 1.1., 1.2., 2. Depth 0 is a top-level section. Output 'number text' per line.
cmsvchtev01nzg4p2qs6o4nrk
contributor_item
Submission 6O4NRK
false
import re def transform(text): words = re.findall(r"[A-Za-z']+", text.lower()) counts = {} for w in words: counts[w] = counts.get(w, 0) + 1 ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])) return ','.join('{}:{}'.format(w, c) for w, c in ordered)
The cat sat. The CAT ran! A dog's day; the dog's day.
"the:3,cat:2,day:2,dog's:2,a:1,ran:1,sat:1"
Given a block of text, return each distinct word lowercased with its count, ordered by descending count then alphabetically, as 'word:count' on one line separated by commas. Words are runs of letters and apostrophes; punctuation is stripped.