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
cmssnl4rm000kg4p2iuxoc8p1
contributor_item
Submission XOC8P1
false
def transform(text): import csv, io, json reader = csv.DictReader(io.StringIO(text)) totals = {} for row in reader: cat = row['category'] try: price = float(row['price']) except (ValueError, TypeError): price = 0.0 try: qty = float(row[...
category,product,price,qty Electronics,Widget,19.99,3 Electronics,Gadget,,5 Groceries,Apple,0.50,10 Groceries,Bread,2.00, Electronics,Gizmo,9.99,2 Toys,Ball,5.00,4 Groceries,Milk,abc,3
{ "Electronics": 79.95, "Groceries": 5, "Toys": 20 }
Parse this CSV of product sales. Treat missing or non-numeric price/qty values as 0. Compute total revenue (price*qty) per category, round to 2 decimals, and return a JSON object mapping category name to total revenue, with keys sorted alphabetically.
cmssnl4rm000rg4p277p7nilx
contributor_item
Submission P7NILX
false
def transform(text): import csv, io, json from collections import defaultdict reader = csv.DictReader(io.StringIO(text)) sums = defaultdict(float) counts = defaultdict(int) for row in reader: try: amt = float(row['amount']) except (ValueError, TypeError): ...
region,salesperson,amount East,Tom,1200 West,Anna,900 East,Lisa,800 West,Mike,1100 East,Tom,500 North,Sam,700
[ { "region": "East", "total": 2500, "average": 833.33 }, { "region": "West", "total": 2000, "average": 1000 }, { "region": "North", "total": 700, "average": 700 } ]
Parse this CSV of sales records and group them by region. For each region compute the total sale amount and the average sale amount (both rounded to 2 decimals). Return a JSON array of objects with keys 'region', 'total', 'average', sorted by total descending.
cmssnl4rm000pg4p2kd2gk6sy
contributor_item
Submission 2GK6SY
false
def transform(text): import json records = [] for rec in text.split(';'): rec = rec.strip() if not rec: continue fields = rec.split('|') d = {} for f in fields: k, v = f.split(':', 1) k = k.strip() if k == 'scores': ...
id:1|name:Alice|scores:90,85,88;id:2|name:Bob|scores:70,75;id:3|name:Carol|scores:100,95,90
[ { "id": 1, "name": "Alice", "scores": [ 90, 85, 88 ] }, { "id": 2, "name": "Bob", "scores": [ 70, 75 ] }, { "id": 3, "name": "Carol", "scores": [ 100, 95, 90 ] } ]
This text encodes student records separated by ';', with fields inside each record separated by '|' as key:value pairs. The 'scores' field is a comma-separated list of integers and 'id' is an integer. Parse this into a JSON array of objects with properly typed fields.
cmssnl4rm000ug4p2cuigx5fj
contributor_item
Submission IGX5FJ
false
def transform(text): import csv, io rows = [] keys_order = [] for line in text.strip().splitlines(): fields = line.split('|') d = {} for f in fields: k, v = f.split('=', 1) d[k] = v if k not in keys_order: keys_order.append(k) ...
timestamp=2026-08-10T10:00:00|user=jdoe|action=login|status=success timestamp=2026-08-10T10:05:00|user=asmith|action=login|status=failed timestamp=2026-08-10T10:06:00|user=jdoe|action=logout|status=success
"timestamp,user,action,status\n2026-08-10T10:00:00,jdoe,login,success\n2026-08-10T10:05:00,asmith,login,failed\n2026-08-10T10:06:00,jdoe,logout,success\n"
This log has one event per line, with pipe-separated key=value fields. Extract the fields from every line and convert the whole log into standard CSV text, using the key names from the first line as column headers, in the order they first appear.
cmssnl4rm000vg4p2cva9eg68
contributor_item
Submission A9EG68
false
def transform(text): import json from collections import Counter counts = Counter() for line in text.strip().splitlines(): if not line.strip(): continue obj = json.loads(line) level = obj.get('level', 'INFO') counts[level] += 1 return json.dumps(dict(sorte...
{"msg": "start", "level": "INFO"} {"msg": "disk low", "level": "WARNING"} {"msg": "oops"} {"msg": "crash", "level": "ERROR"} {"msg": "another warn", "level": "WARNING"} {"msg": "ok"}
{ "ERROR": 1, "INFO": 3, "WARNING": 2 }
This is a JSON Lines (JSONL) log where each line is an independent JSON object with a 'msg' field and an optional 'level' field. Entries missing 'level' should be treated as 'INFO'. Count how many entries fall into each level and return a JSON object mapping level name to count, with keys sorted alphabetically.
cmssnl4rm000tg4p2s3xe597x
contributor_item
Submission XE597X
false
def transform(text): import json seen = [] seen_set = set() for line in text.splitlines(): line = line.strip() if not line: continue normalized = ' '.join(line.split()).title() if normalized not in seen_set: seen_set.add(normalized) see...
ALICE johnson Bob SMITH alice Johnson CAROL white BOB smith
[ "Alice Johnson", "Bob Smith", "Carol White" ]
Each line is a person's name with inconsistent capitalization and irregular internal/leading/trailing whitespace (tabs, multiple spaces). Normalize each name to Title Case with single spaces between words, remove duplicate names (case-insensitive after normalization), and return a JSON array of the unique names in thei...
cmssnl4rm000zg4p256qqyrz0
contributor_item
Submission QQYRZ0
false
def transform(text): import csv, io, json reader = csv.reader(io.StringIO(text), delimiter='\t') rows = list(reader) header = rows[0] data_rows = rows[1:] result = [] for row in data_rows: merged = {} for h, v in zip(header, row): if h not in merged: ...
id name name email 1 Alice a@example.com 2 Bob b@example.com
[ { "id": "1", "name": "Alice", "email": "a@example.com" }, { "id": "2", "name": "Bob", "email": "b@example.com" } ]
This is tab-separated data whose header row contains a duplicated column name ('name' appears twice, representing two data-entry attempts for the same field). For each row, merge the duplicate columns by keeping the first non-empty value among them. Return a JSON array of objects with one 'name' key per row (duplicate ...
cmssnl4rm0013g4p2gq3d4ieq
contributor_item
Submission 3D4IEQ
false
def transform(text): import csv, io, json from datetime import datetime formats = ["%m/%d/%Y", "%Y-%m-%d", "%d-%b-%Y"] reader = csv.DictReader(io.StringIO(text)) result = [] for row in reader: d = dict(row) raw = row['signup_date'].strip() parsed = None if raw: ...
id,name,signup_date 1,Alice,08/10/2026 2,Bob,2026-08-11 3,Carol, 4,Dave,11-Aug-2026
[ { "id": "1", "name": "Alice", "signup_date": "2026-08-10" }, { "id": "2", "name": "Bob", "signup_date": "2026-08-11" }, { "id": "3", "name": "Carol", "signup_date": null }, { "id": "4", "name": "Dave", "signup_date": "2026-08-11" } ]
Parse this CSV of user signups whose 'signup_date' column mixes MM/DD/YYYY, YYYY-MM-DD, and DD-Mon-YYYY formats, with some rows missing the date entirely. Normalize every present date to ISO 8601 (YYYY-MM-DD) and use null for missing dates. Return a JSON array of the row objects with the normalized 'signup_date' field.
cmssnl4rm0012g4p23pea6ic2
contributor_item
Submission EA6IC2
false
def transform(text): import json tree = {} for line in text.strip().splitlines(): parts = [p.strip() for p in line.split('>')] node = tree for p in parts: node = node.setdefault(p, {}) return json.dumps(tree)
Home > Electronics > Phones > Smartphones Home > Electronics > Laptops Home > Garden > Tools Home > Electronics > Phones > Accessories
{ "Home": { "Electronics": { "Phones": { "Smartphones": {}, "Accessories": {} }, "Laptops": {} }, "Garden": { "Tools": {} } } }
Each line is a category breadcrumb path with segments separated by '>'. Merge all the paths into a single nested tree structure where each category name maps to an object of its child categories (leaf categories map to an empty object). Return the tree as a JSON object.
cmssnl4rm0010g4p27wyah7bg
contributor_item
Submission YAH7BG
false
def transform(text): import json result = {} for line in text.strip().splitlines(): line = line.strip() if not line.startswith('export '): continue line = line[len('export '):] key, val = line.split('=', 1) val = val.strip() if val.startswith('"') ...
export DEBUG=true export MAX_RETRIES=5 export TIMEOUT=30.0 export APP_NAME="My App" export FEATURE_FLAGS=beta,new_ui,dark_mode
{ "DEBUG": true, "MAX_RETRIES": 5, "TIMEOUT": 30, "APP_NAME": "My App", "FEATURE_FLAGS": [ "beta", "new_ui", "dark_mode" ] }
Parse these shell-style 'export KEY=VALUE' lines into a single JSON object. Coerce 'true'/'false' to booleans, plain integers and decimals to numbers, strip surrounding double quotes from quoted string values, and split comma-separated values (with no quotes) into a JSON array of strings. Return the resulting JSON obje...
cmssq261b003dg4p26bbpnl59
contributor_item
Submission BPNL59
false
def transform(text): versions = [v.strip() for v in text.split(',') if v.strip()] versions.sort(key=lambda v: tuple(int(p) for p in v.split('.'))) return ', '.join(versions)
1.9.2, 1.10.0, 0.4.12, 1.9.10, 2.0.0, 0.4.2
"0.4.2, 0.4.12, 1.9.2, 1.9.10, 1.10.0, 2.0.0"
Sort semantic version strings in ascending order by numeric component (so 1.10.0 comes after 1.9.2) and return them comma-separated.
cmssq261b003cg4p2ofduxq69
contributor_item
Submission DUXQ69
false
def transform(text): lines = [l for l in text.strip().split('\n') if l.strip()] rows = [l.split('\t') for l in lines[1:]] metrics = sorted({r[1] for r in rows}) dates = [] table = {} for date, metric, value in rows: if date not in table: table[date] = {} dates.app...
date metric value 2026-01-01 clicks 5 2026-01-01 views 90 2026-01-02 views 70
"date\tclicks\tviews\n2026-01-01\t5\t90\n2026-01-02\t0\t70"
Pivot long-format 'date\tmetric\tvalue' TSV into wide TSV with a header row of 'date' plus each metric sorted alphabetically. Missing combinations become 0.
cmssq261b003gg4p2sz669sy9
contributor_item
Submission 669SY9
false
import re def transform(text): units = {'h': 3600, 'm': 60, 's': 1} out = [] for line in text.split('\n'): spec = line.strip() if not spec: continue total = 0 for amount, unit in re.findall(r'(\d+)([hms])', spec): total += int(amount) * units[unit] ...
1h30m 45s 2h 3m10s 10h0m1s
"1h30m=5400\n45s=45\n2h=7200\n3m10s=190\n10h0m1s=36001"
Parse compact duration strings like '1h30m', '45s', '2h', '3m10s' into total seconds and return 'original=seconds' lines in the input order.
cmssq261b003kg4p22evglt7o
contributor_item
Submission VGLT7O
false
import re def transform(text): entries = [] for line in text.split('\n'): match = re.match(r'^(#+)\s+(.*)$', line.strip()) if match: entries.append((len(match.group(1)), match.group(2).strip())) if not entries: return '' base = min(level for level, _ in entries) ...
# Getting Started some text ## Install & Setup ### Windows Notes ## FAQ
"- Getting Started (#getting-started)\n - Install & Setup (#install-setup)\n - Windows Notes (#windows-notes)\n - FAQ (#faq)"
Build a table of contents from Markdown ATX headings: indent two spaces per level below the top level found, and render each as '- <title> (#<slug>)' with a lowercase hyphen slug.
cmssq261b003jg4p2zrqnwk0w
contributor_item
Submission QNWK0W
false
import re def transform(text): out = [] for line in text.split('\n'): raw = line.strip() if not raw: continue digits = re.sub(r'\D', '', raw) if len(digits) == 11 and digits.startswith('1'): digits = digits[1:] if len(digits) != 10: ou...
(415) 555-0132 +1 415 555 9000 555-0100 14155552671
"+1-415-555-0132\n+1-415-555-9000\nINVALID:555-0100\n+1-415-555-2671"
Normalize phone numbers to '+1-XXX-XXX-XXXX' when they have exactly 10 digits (or 11 starting with 1); otherwise emit 'INVALID:<original>'. One result per input line.
cmssq261b003bg4p2h17r5qi9
contributor_item
Submission 7R5QI9
false
def transform(text): seen = set() kept = [] for line in text.split('\n'): addr = line.strip() if not addr: continue key = addr.lower() if key in seen: continue seen.add(key) kept.append(addr) return '\n'.join(kept + ['count={}'.form...
Ana@Example.com bob@example.com ANA@example.com carl@Example.COM bob@Example.com
"Ana@Example.com\nbob@example.com\ncarl@Example.COM\ncount=3"
Deduplicate a newline-separated list of email addresses case-insensitively, keeping the first spelling seen, and return them one per line followed by a final 'count=N' line.
cmssq261b003hg4p22iabmml1
contributor_item
Submission ABMML1
false
def transform(text): cells = {} max_row = max_col = 0 for line in text.split('\n'): if not line.strip(): continue row, col, value = [p.strip() for p in line.split(',')] row, col = int(row), int(col) cells[(row, col)] = value max_row = max(max_row, row) ...
0,0,7 2,3,4 1,1,9 0,3,2
"7 . . 2\n. 9 . .\n. . . 4"
Convert 'row,col,value' triplets into a dense space-separated grid sized to the maximum row and column present, filling absent cells with '.'.
cmssq261b0037g4p2s6pajz16
contributor_item
Submission PAJZ16
false
import json def transform(text): rows = [] for line in text.split('\n'): if not line.strip(): continue rows.append({ 'sku': line[0:7].strip(), 'name': line[7:20].strip(), 'qty': int(line[20:].strip()), }) return json.dumps(rows)
A1001 widget bolt 42 A1002 hex nut 7 A1003 washer plate 115
[ { "sku": "A1001", "name": "widget bolt", "qty": 42 }, { "sku": "A1002", "name": "hex nut", "qty": 7 }, { "sku": "A1003", "name": "washer plate", "qty": 115 } ]
Parse fixed-width records (cols 0-6 sku, 7-19 name, 20-end qty) into a JSON array of objects with keys sku, name, qty (qty as integer). Trim padding whitespace; skip blank lines.
cmssq261b003ag4p272rnhn15
contributor_item
Submission RNHN15
false
import json def transform(text): result = {} section = None for raw in text.split('\n'): line = raw.strip() if not line or line.startswith(';'): continue if line.startswith('[') and line.endswith(']'): section = line[1:-1] result[section] = {} ...
; deployment [server] host = localhost port = 8080 debug = false [cache] ttl = 300 name = edge-1
{ "server": { "host": "localhost", "port": 8080, "debug": false }, "cache": { "ttl": 300, "name": "edge-1" } }
Parse an INI-style config into nested JSON by section. Coerce 'true'/'false' to booleans and bare integers to numbers; leave everything else as a string. Ignore ';' comment lines.
cmssq261b0038g4p2twuuz5kf
contributor_item
Submission UUZ5KF
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['amount']) ordered = sorted(totals.items(), key=lambda kv: (-kv[1], kv[0])) return '\n'.join('{}={}'.format(k,...
region,amount north,120 south,80 north,45 east,80 south,20
"north=165\nsouth=100\neast=80"
Read CSV with headers region,amount and return lines 'region=total' sorted by descending total then ascending region name. Totals are integers.
cmssq261b003fg4p2ntf8tqha
contributor_item
Submission F8TQHA
false
import csv, io, json def transform(text): rows = json.loads(text) keys = sorted({k for row in rows for k in row}) out = io.StringIO() writer = csv.DictWriter(out, fieldnames=keys, restval='', lineterminator='\n') writer.writeheader() for row in rows: writer.writerow(row) return out....
[{"name": "Ada, R.", "note": "said \"hi\"", "id": 1}, {"id": 2, "name": "Bo"}]
"id,name,note\n1,\"Ada, R.\",\"said \"\"hi\"\"\"\n2,Bo,"
Convert a JSON array of objects into CSV. Use the union of all keys sorted alphabetically as the header, leave missing values empty, and quote fields per standard CSV rules.
cmssq261b003ig4p2uckc1aio
contributor_item
Submission KC1AIO
false
def transform(text): nums = sorted({int(p) for p in text.split(',') if p.strip()}) parts = [] start = prev = nums[0] for value in nums[1:] + [None]: if value is not None and value == prev + 1: prev = value continue parts.append(str(start) if start == prev else '{}...
3, 1, 2, 7, 8, 9, 12, 15, 16
"1-3,7-9,12,15-16"
Collapse a comma-separated list of integers into sorted ranges: consecutive runs become 'start-end', isolated values stay bare, joined by commas.
cmssq261b003lg4p2ea9gfeza
contributor_item
Submission 9GFEZA
false
import json def transform(text): data = json.loads(text) before, after = data['before'], data['after'] lines = [] for key in sorted(set(before) | set(after)): if key not in before: lines.append('added {} {}'.format(key, after[key])) elif key not in after: lines.a...
{"before": {"a": 10, "b": 20, "c": 30}, "after": {"a": 10, "b": 25, "d": 40}}
"changed b 20->25\nremoved c 30\nadded d 40"
Given a JSON object with 'before' and 'after' maps of id->price, report changes as sorted lines: 'added id price', 'removed id price', or 'changed id old->new'. Skip unchanged ids.
cmssq261b0039g4p2zy440vo1
contributor_item
Submission 440VO1
false
import json def transform(text): data = json.loads(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 e...
{"user": {"name": "dana", "tags": ["a", "b"]}, "active": true, "meta": {"score": 4}}
{ "active": true, "meta.score": 4, "user.name": "dana", "user.tags.0": "a", "user.tags.1": "b" }
Flatten a nested JSON object into dotted key paths, indexing list elements numerically, and return the result as a JSON object with keys sorted alphabetically.
cmssq261b003eg4p2dylw9s28
contributor_item
Submission LW9S28
false
def transform(text): s = text.strip() out = [] index = 0 while index < len(s): run = 1 while index + run < len(s) and s[index + run] == s[index]: run += 1 if run >= 3: out.append('{}{}'.format(run, s[index])) else: out.append(s[index] *...
aaabccddddde
"3abcc5de"
Run-length encode a string, but only collapse runs of 3 or more characters into '<count><char>'; shorter runs are emitted literally.
cmssuehje0087g4p2hwbt2amc
contributor_item
Submission BT2AMC
false
import json def transform(text): out={} for part in text.strip().split(','): k,v=part.split('=',1); out[k]=int(v) return json.dumps(out)
a=3,b=4,c=5
{ "a": 3, "b": 4, "c": 5 }
Parse comma-separated key=value pairs and return a JSON object with integer values.
cmssuehje0089g4p2r13snugu
contributor_item
Submission 3SNUGU
false
import json from collections import Counter def transform(text): return json.dumps(dict(Counter(text.split())))
red red blue green red blue
{ "red": 3, "blue": 2, "green": 1 }
Count whitespace-separated tokens and return a JSON object of token frequencies.
cmssuehje008eg4p2y6iymqgl
contributor_item
Submission IYMQGL
false
import json def transform(text): return json.dumps({k:float(v) for k,v in (line.split(',') for line in text.strip().splitlines())})
A,12.5 B,7 C,3.25
{ "A": 12.5, "B": 7, "C": 3.25 }
Convert label,value rows into a JSON object with floating-point values.
cmssuehjg008ig4p2x3skqvio
contributor_item
Submission SKQVIO
false
import csv,io,json def transform(text): rows=list(csv.DictReader(io.StringIO(text))) for r in rows:r['id']=int(r['id']) return json.dumps(rows)
id,name 1,Ada 2,Linus 3,Grace
[ { "id": 1, "name": "Ada" }, { "id": 2, "name": "Linus" }, { "id": 3, "name": "Grace" } ]
Convert a two-column CSV with header into a JSON array of records, converting id to integer.
cmssuehjg008lg4p2f7ybpgny
contributor_item
Submission YBPGNY
false
import json def transform(text): m=[[int(x) for x in line.split()] for line in text.strip().splitlines()] return json.dumps([sum(col) for col in zip(*m)])
1 2 3 4 5 6 7 8 9
[ 12, 15, 18 ]
Parse a whitespace-separated integer matrix and return its column sums as a JSON array.
cmssuehjg008ng4p201gibav2
contributor_item
Submission GIBAV2
false
import json def transform(text): return json.dumps([line.strip().lower() for line in text.splitlines() if line.strip()])
Alpha Beta Gamma
[ "alpha", "beta", "gamma" ]
Trim each line, remove blank lines, lowercase the remaining values, and return a JSON array.
cmssuehjg008pg4p21zdsn6on
contributor_item
Submission DSN6ON
false
import json def transform(text): return json.dumps([int(a)-int(b) for a,b in (line.split(',') for line in text.strip().splitlines())])
100,20 50,5 25,0
[ 80, 45, 25 ]
For each comma-separated gross,discount row, compute net=gross-discount and return nets as a JSON array.
cmssuehjg008qg4p2fq45lnqn
contributor_item
Submission 45LNQN
false
import json def transform(text): obj=json.loads(text) return json.dumps([u['name'] for u in obj['users'] if u['active']])
{"users":[{"name":"Ada","active":true},{"name":"Bob","active":false},{"name":"Cara","active":true}]}
[ "Ada", "Cara" ]
Parse the JSON and return a JSON array containing names of active users.
cmssuehjg008rg4p21r8oh7ab
contributor_item
Submission 8OH7AB
false
import json def transform(text): rows=[line.split(',') for line in text.strip().splitlines()] return json.dumps([list(col) for col in zip(*rows)])
a,b,c d,e,f
[ [ "a", "d" ], [ "b", "e" ], [ "c", "f" ] ]
Transpose comma-separated rows and return the transposed matrix as JSON.
cmssuehjg008tg4p2kdsd1ubv
contributor_item
Submission SD1UBV
false
import csv,io,json def transform(text): rows=csv.DictReader(io.StringIO(text)) return json.dumps([r['first_name']+' '+r['last_name'] for r in rows])
first_name,last_name Ada,Lovelace Grace,Hopper
[ "Ada Lovelace", "Grace Hopper" ]
Convert CSV rows into full-name strings and return them as a JSON array.
cmssuehjg008yg4p2hy3tkivx
contributor_item
Submission 3TKIVX
false
import json def transform(text): out=[] for line in text.strip().splitlines(): k,v=line.split('='); out.extend([k]*int(v)) return json.dumps(out)
cat=2 dog=5 bird=1
[ "cat", "cat", "dog", "dog", "dog", "dog", "dog", "bird" ]
Parse key=count lines and expand them into a JSON array repeating each key count times, preserving input key order.
cmssuehjg008xg4p28c91lqhv
contributor_item
Submission 91LQHV
false
import json def transform(text): total=0; out=[] for x in map(int,text.split(',')): total+=x; out.append(total) return json.dumps(out)
5,10,15,20
[ 5, 15, 30, 50 ]
Convert comma-separated integers into cumulative sums and return them as a JSON array.
cmssuehjg008zg4p2nsxnjoae
contributor_item
Submission XNJOAE
false
import json def transform(text): out={} for line in text.strip().splitlines(): k,a,b=line.split(); out[k]=max(int(a),int(b)) return json.dumps(out)
A 3 7 B 10 4 C 6 6
{ "A": 7, "B": 10, "C": 6 }
For each whitespace-separated label,x,y row, return a JSON object mapping label to the larger integer.
cmssuehjh0090g4p2csskniau
contributor_item
Submission SKNIAU
false
import json from collections import Counter def transform(text): c=Counter(text.split(',')) return json.dumps(sorted(c,key=lambda k:(-c[k],k)))
alpha,beta,gamma,beta,alpha,alpha
[ "alpha", "beta", "gamma" ]
Return a JSON array of tokens sorted by decreasing frequency and then alphabetically.
cmssuehje008bg4p2t8cpxd7m
contributor_item
Submission CPXD7M
false
import json def transform(text): out={} for line in text.strip().splitlines(): k,v=line.split(':',1); v=v.strip(); out[k.strip()]= True if v=='true' else False if v=='false' else v return json.dumps(out)
name: Ada Lovelace role: Engineer active: true
{ "name": "Ada Lovelace", "role": "Engineer", "active": true }
Parse colon-separated lines into a JSON object, converting true/false values to booleans.
cmssuehje008ag4p21v289yez
contributor_item
Submission 289YEZ
false
import json def transform(text): nums=[int(x) for x in text.split(',') if x] return json.dumps({'count':len(nums),'sum':sum(nums),'min':min(nums),'max':max(nums)})
10,20,30,40,50
{ "count": 5, "sum": 150, "min": 10, "max": 50 }
Parse comma-separated integers and return a JSON object containing count, sum, minimum, and maximum.
cmssuehje0088g4p2imv9vrhj
contributor_item
Submission V9VRHJ
false
import json def transform(text): rows=[] for line in text.strip().splitlines(): name,score=line.split('|'); rows.append({'name':name,'score':int(score)}) return json.dumps(rows)
alice|90 bob|75 carol|88
[ { "name": "alice", "score": 90 }, { "name": "bob", "score": 75 }, { "name": "carol", "score": 88 } ]
Convert pipe-delimited name-score rows into a JSON array of objects with score as an integer.
cmssuehje008cg4p2hirfgsq5
contributor_item
Submission RFGSQ5
false
import json from collections import defaultdict def transform(text): d=defaultdict(int) for line in text.strip().splitlines(): day,val=line.split(','); d[day]+=int(val) return json.dumps(dict(d))
2026-08-14,12 2026-08-15,8 2026-08-14,5
{ "2026-08-14": 17, "2026-08-15": 8 }
Aggregate comma-separated date,value rows by date and return summed values as JSON.
cmssuehje008fg4p2lxy7in63
contributor_item
Submission Y7IN63
false
import json def transform(text): return json.dumps([w for w in text.split() if len(w)>=4])
one two three four five
[ "three", "four", "five" ]
Return a JSON array containing only words with length at least four, preserving order.
cmssuehje008dg4p201ypmvy3
contributor_item
Submission YPMVY3
false
import json def transform(text): seen=set(); out=[] for line in text.strip().splitlines(): if line not in seen: seen.add(line); out.append(line) return json.dumps(out)
alpha beta alpha gamma beta alpha
[ "alpha", "beta", "gamma" ]
Return a JSON array of unique lines in first-seen order.
cmssuehjg008jg4p2r8b8qhfe
contributor_item
Submission B8QHFE
false
import json def transform(text): rows=[line.split(':',1) for line in text.strip().splitlines()] rows.sort(key=lambda x:int(x[0])) return json.dumps([v for _,v in rows])
3:apple 1:pear 2:banana
[ "pear", "banana", "apple" ]
Sort colon-separated priority:text rows by numeric priority and return only the text values as JSON array.
cmssuehjg008kg4p21lrl4io6
contributor_item
Submission RL4IO6
false
import json def transform(text): s=text.strip(); out=[] for ch in s: if out and out[-1][0]==ch: out[-1][1]+=1 else: out.append([ch,1]) return json.dumps(out)
aaabccccdd
[ [ "a", 3 ], [ "b", 1 ], [ "c", 4 ], [ "d", 2 ] ]
Run-length encode the input string as a JSON array of [character,count] pairs.
cmssuehjg008hg4p2li1g7yfe
contributor_item
Submission 1G7YFE
false
import json def transform(text): nums=[int(x) for x in text.splitlines() if x.strip()] return json.dumps({'negative':[x for x in nums if x<0],'zero':[x for x in nums if x==0],'positive':[x for x in nums if x>0]})
5 -2 7 0 -1
{ "negative": [ -2, -1 ], "zero": [ 0 ], "positive": [ 5, 7 ] }
Partition newline-separated integers into negative, zero, and positive arrays in JSON.
cmssuehjg008mg4p2r1rqhiq3
contributor_item
Submission RQHIQ3
false
import json from collections import defaultdict def transform(text): d=defaultdict(float) for line in text.strip().splitlines(): k,v=line.split(':'); d[k]+=float(v) return json.dumps({k:round(v,2) for k,v in d.items()})
usd:10.50 eur:3.25 usd:2.00
{ "usd": 12.5, "eur": 3.25 }
Aggregate currency:value lines by currency and return totals rounded to two decimals in JSON.
cmssuehjg008og4p2locb51ad
contributor_item
Submission CB51AD
false
import json from collections import defaultdict def transform(text): d=defaultdict(list) for line in text.strip().splitlines(): i,c=line.split(','); d[c].append(i) return json.dumps(dict(d))
p1,red p2,blue p3,red p4,green
{ "red": [ "p1", "p3" ], "blue": [ "p2" ], "green": [ "p4" ] }
Group first-column IDs by second-column category and return a JSON object mapping category to ID arrays.
cmssuehjg008sg4p2b5en7jxp
contributor_item
Submission EN7JXP
false
import json def transform(text): vals=[float(x) for x in text.splitlines() if x.strip()] return json.dumps({'mean':round(sum(vals)/len(vals),2),'count':len(vals)})
10.4 11.6 9.9 12.1
{ "mean": 11, "count": 4 }
Parse newline-separated floats and return a JSON object with the rounded arithmetic mean and count.
cmssuehjg008ug4p2ze2cq8ya
contributor_item
Submission 2CQ8YA
false
import json def transform(text): pairs=[part.split(':') for part in text.strip().split(';')] pairs.sort(key=lambda kv:(-int(kv[1]),kv[0])) return json.dumps([k for k,_ in pairs])
a:1;b:2;c:3
[ "c", "b", "a" ]
Parse semicolon-separated key:value entries and return keys sorted by descending numeric value as a JSON array.
cmssuehjg008vg4p2zzt0lot7
contributor_item
Submission T0LOT7
false
import json from datetime import datetime def transform(text): ts=[datetime.fromisoformat(x.replace('Z','+00:00')) for x in text.strip().splitlines()] return json.dumps([int((ts[i+1]-ts[i]).total_seconds()) for i in range(len(ts)-1)])
2026-08-14T10:00:00Z 2026-08-14T10:02:30Z 2026-08-14T10:10:00Z
[ 150, 450 ]
Parse ISO timestamps and return elapsed seconds between each adjacent pair as a JSON array.
cmssuehjg008wg4p2llegmawc
contributor_item
Submission EGMAWC
false
import json from collections import defaultdict def transform(text): d=defaultdict(list) for line in text.strip().splitlines(): k,v=line.split('='); d[k].append(int(v)) return json.dumps(dict(d))
a=1 b=2 a=3 c=4
{ "a": [ 1, 3 ], "b": [ 2 ], "c": [ 4 ] }
Parse repeated key=value lines and return a JSON object mapping each key to an array of integer values.
cmst2i3cz00bag4p2r84ifkti
contributor_item
Submission 4IFKTI
false
import csv, io, json def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) return json.dumps([dict(row) for row in reader])
id,name,active 1,Alice,true 2,Bob,false
[ { "id": "1", "name": "Alice", "active": "true" }, { "id": "2", "name": "Bob", "active": "false" } ]
Parse CSV text with a header row and return a JSON array of objects, one per data row, with values kept as strings.
cmst2i3cz00bdg4p28u7icgtn
contributor_item
Submission 7ICGTN
false
def transform(text): def camel(s): parts = s.split('_') return parts[0] + ''.join(p.capitalize() for p in parts[1:]) return '\n'.join(camel(l) for l in text.strip().split('\n'))
user_id first_name is_active_now x
"userId\nfirstName\nisActiveNow\nx"
Convert a snake_case identifier list (one per line) into camelCase, returned as a newline-separated string in the same order.
cmst2i3cz00bcg4p2zmmx9lsv
contributor_item
Submission MX9LSV
false
import json def transform(text): d = {} for line in text.strip().split('\n'): if ':' in line: k, v = line.split(':', 1) d[k.strip()] = v.strip() return json.dumps(d)
host: localhost port: 8080 host: 127.0.0.1 debug: true
{ "host": "127.0.0.1", "port": "8080", "debug": "true" }
Given lines of 'key: value' pairs, return them as a JSON object. If a key repeats, the last value wins.
cmst2i3cz00bhg4p2x4qpcp4q
contributor_item
Submission QPCP4Q
false
import json def transform(text): line = text.rstrip('\n') return json.dumps({'name': line[0:10].strip(), 'age': line[10:13].strip(), 'city': line[13:].strip()})
Alice 030New York
{ "name": "Alice", "age": "030", "city": "New York" }
Given a fixed-width record where columns are at positions 0-9 (name), 10-12 (age), 13+ (city), return a JSON object with those three trimmed fields.
cmst2i3cz00bfg4p2v7uxwpuo
contributor_item
Submission UXWPUO
false
import json from collections import Counter def transform(text): words = text.strip().lower().split() c = Counter(words) return json.dumps({k: c[k] for k in sorted(c)})
the Cat sat on the mat the cat
{ "cat": 2, "mat": 1, "on": 1, "sat": 1, "the": 3 }
Given a block of text, return a JSON object mapping each distinct word (lowercased, split on whitespace) to its count, with keys sorted alphabetically.
cmst2i3cz00big4p23j1k7h42
contributor_item
Submission 1K7H42
false
import json def transform(text): out = [] total = 0.0 for l in text.strip().split('\n'): total += float(l) out.append(round(total, 1)) return json.dumps(out)
1.5 2.25 0.25 -1.0
[ 1.5, 3.8, 4, 3 ]
Given newline-separated floats, return a JSON array of the running (cumulative) sum after each value, each rounded to one decimal place.
cmst2i3cz00bog4p2ixzp16jr
contributor_item
Submission ZP16JR
false
import json, io, csv def transform(text): reader = csv.DictReader(io.StringIO(text.strip()), delimiter='\t') out = [] for row in reader: obj = {} for k, v in row.items(): obj[k] = int(v) if v.isdigit() else v out.append(obj) return json.dumps(out)
name age zip Alice 30 07008 Bob 25 10001
[ { "name": "Alice", "age": 30, "zip": 7008 }, { "name": "Bob", "age": 25, "zip": 10001 } ]
Given tab-separated values with a header, return a JSON array of objects, coercing any all-digit field to an integer.
cmst2i3cz00bpg4p203m7jo6l
contributor_item
Submission M7JO6L
false
import json def transform(text): ips = [l.strip() for l in text.strip().split('\n') if l.strip()] ips.sort(key=lambda ip: tuple(int(o) for o in ip.split('.'))) return json.dumps(ips)
10.0.0.2 10.0.0.10 9.255.255.255 10.0.0.1
[ "9.255.255.255", "10.0.0.1", "10.0.0.2", "10.0.0.10" ]
Given a list of IPv4 addresses (one per line), return a JSON array sorted numerically by octet, not lexicographically.
cmst2i3cz00bmg4p2k6yhkzgr
contributor_item
Submission YHKZGR
false
import json def transform(text): rows = json.loads(text) out = {} for r in rows: out[r['category']] = out.get(r['category'], 0) + r['amount'] return json.dumps(out)
[{"category": "food", "amount": 10}, {"category": "toys", "amount": 5}, {"category": "food", "amount": 7}]
{ "food": 17, "toys": 5 }
Given a JSON array of objects each with 'category' and 'amount', return a JSON object summing amount per category, keys in first-seen order.
cmst2i3cz00bqg4p2eqey3ivk
contributor_item
Submission EY3IVK
false
import json def transform(text): out = {} for line in text.strip().split('\n'): k, v = line.split('=', 1) vl = v.strip().lower() if vl == 'true': out[k.strip()] = True elif vl == 'false': out[k.strip()] = False elif v.strip().isdigit(): ...
enabled=TRUE retries=3 name=server1 verbose=False
{ "enabled": true, "retries": 3, "name": "server1", "verbose": false }
Given key-value lines in 'k=v' form, return a JSON object where any value that is 'true' or 'false' (case-insensitive) becomes a boolean and any all-digit value becomes an integer.
cmst2i3d000bsg4p2zdgk98nl
contributor_item
Submission GK98NL
false
import json def transform(text): d = json.loads(text) mean = sum(d.values()) / len(d) return json.dumps(sorted(k for k, v in d.items() if v >= mean))
{"a": 50, "b": 90, "c": 70, "d": 30}
[ "b", "c" ]
Given a JSON object of scores, return a JSON array of keys whose value is at or above the mean, sorted alphabetically.
cmst2i3d000btg4p282fj5k8v
contributor_item
Submission FJ5K8V
false
import re def transform(text): out = [] for ch, count in re.findall(r'([a-z])(\d+)', text.strip()): out.append(ch * int(count)) return ''.join(out)
a3b1c2z5
"aaabcczzzzz"
Given a run-length spec like 'a3b1c2', expand it into the full string 'aaabcc'.
cmst2i3d000brg4p20zbpufyr
contributor_item
Submission BPUFYR
false
def transform(text): lines = text.split('\n') return '\n'.join('{}:\t{}'.format(i, l) for i, l in enumerate(lines, 1))
first second third
"1:\tfirst\n2:\tsecond\n3:\tthird"
Given a multi-line string, return it with each line prefixed by its 1-based line number, a colon, and a tab; join with newlines.
cmst2i3cz00bbg4p2p2z9qyd2
contributor_item
Submission Z9QYD2
false
import json def transform(text): nums = [int(l) for l in text.strip().split('\n') if l.strip()] return json.dumps({'sum': sum(nums), 'min': min(nums), 'max': max(nums), 'mean': round(sum(nums)/len(nums), 2)})
4 8 15 16 23 42
{ "sum": 108, "min": 4, "max": 42, "mean": 18 }
Given newline-separated integers, return a JSON object with keys 'sum', 'min', 'max', and 'mean' where mean is rounded to two decimal places.
cmst2i3cz00beg4p21cfm44o9
contributor_item
Submission FM44O9
false
import json from collections import Counter def transform(text): nums = json.loads(text) c = Counter(nums) return json.dumps(sorted(n for n in c if c[n] > 1))
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
[ 1, 3, 5 ]
Given a JSON array of numbers, return a JSON array containing only the numbers that appear more than once, in ascending order, each listed once.
cmst2i3cz00bng4p2bzthy2uk
contributor_item
Submission THY2UK
false
import re def transform(text): m = re.search(r'[.!?]', text) if not m: return text.strip() return text[:m.end()].strip()
Hello there. This is the second one! And a third.
"Hello there."
Given a paragraph, return the first sentence (text up to and including the first period, question mark, or exclamation mark), trimmed.
cmst2i3cz00bgg4p21s5p28jv
contributor_item
Submission 5P28JV
false
def transform(text): pairs = [] for part in text.strip().split(';'): name, score = part.split('=') pairs.append((name.strip(), int(score))) pairs.sort(key=lambda p: (-p[1], p[0])) return '\n'.join(p[0] for p in pairs)
alice=90;bob=85;carol=90;dave=85
"alice\ncarol\nbob\ndave"
Parse a semicolon-separated list of 'name=score' pairs and return the names sorted by descending score, then alphabetically for ties, as a newline-separated string.
cmst2i3cz00bjg4p2uz2fhyjv
contributor_item
Submission 2FHYJV
false
import json def transform(text): d = json.loads(text) lines = [] for k in sorted(d): v = d[k] if isinstance(v, bool): v = 'true' if v else 'false' lines.append('{}={}'.format(k, v)) return '\n'.join(lines)
{"zebra": 1, "apple": true, "mango": false}
"apple=true\nmango=false\nzebra=1"
Convert a flat JSON object into a list of 'key=value' lines sorted by key, joining with newlines. Boolean values become lowercase 'true'/'false'.
cmst2i3cz00bkg4p2osb4qvw0
contributor_item
Submission B4QVW0
false
import json def transform(text): def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True nums = [int(x) for x in text.strip().split(',')] return json.dumps([[n, is_prim...
1,2,3,4,17,18
[ [ 1, false ], [ 2, true ], [ 3, true ], [ 4, false ], [ 17, true ], [ 18, false ] ]
Given a comma-separated list of integers, return a JSON array of [value, is_prime] pairs preserving order, where is_prime is a boolean.
cmst2i3cz00blg4p2slgkmhvm
contributor_item
Submission GKMHVM
false
import re def transform(text): total = 0 for line in text.strip().split('\n'): m = re.match(r'(?:(\d+)h)?(?:(\d+)m)?$', line.strip()) h = int(m.group(1)) if m and m.group(1) else 0 mins = int(m.group(2)) if m and m.group(2) else 0 total += h * 60 + mins return str(total)
1h30m 45m 2h 15m
270
Given lines each containing a duration like '1h30m' or '45m' or '2h', return the total number of minutes as a plain integer string.
cmst5hn7o00d6g4p28em3boyg
contributor_item
Submission M3BOYG
false
MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') DAYS = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') def join_list(items): if len(items) == 1: return items[0] return ', '.join...
*/15 * * * * 0 9,17 * * 1-5 30 2 1 * * 0 0 * 12 0 0 12 * *
"*/15 * * * * => every 15th minute, every hour, every day of the month, every month, every day of the week\n0 9,17 * * 1-5 => minute 0, hours 9 and 17, every day of the month, every month, Monday through Friday\n30 2 1 * * => minute 30, hour 2, day-of-month 1, every month, every day of the week\n0 0 * 12 0 => minute 0,...
Describe each cron expression in English. Each non-blank input line is one expression; split it on whitespace. If it does not have exactly 5 fields, the description is 'ERROR: expected 5 fields'. Otherwise the fields are minute, hour, day-of-month, month and day-of-week, and each is rendered by these rules: - minute: '...
cmst5hn7o00d9g4p2oqkeobs8
contributor_item
Submission KEOBS8
false
import base64 def transform(text): lines = text.split('\n') width = int(lines[0].split('=', 1)[1].strip()) payload = ''.join(''.join(line.split()) for line in lines[1:]) payload = payload.replace('=', '') while len(payload) % 4 != 0: payload += '=' out = [payload[i:i + width] for i in ...
WIDTH=20 SGVsbG8sIER hdGFCb3VudHkh IFRoaXMgaXMg YSBiYXNlNjQg cmV3cmFwIHRlc3Q
"SGVsbG8sIERhdGFCb3Vu\ndHkhIFRoaXMgaXMgYSBi\nYXNlNjQgcmV3cmFwIHRl\nc3Q=\nbytes=47"
Re-wrap a base64 payload that arrived in ragged, unpadded chunks. The first line is 'WIDTH=N' giving the target line width in characters. Every following line is a fragment of one single base64 payload. Concatenate the fragments after removing ALL whitespace characters (including the line breaks and any spaces inside a...
cmst5hn7o00ddg4p26u61a7gn
contributor_item
Submission 61A7GN
false
import json def transform(text): head, body = text.split('\n', 1) maxdepth = int(head.split('=', 1)[1].strip()) data = json.loads(body) out = [] def walk(array, level): for element in array: if isinstance(element, list) and level <= maxdepth: walk(element, leve...
maxdepth=2 [1, [2, 3, [4, [5, 6]]], "a", [], [[7], 8], null]
"1\n2\n3\n4\n[5,6]\n\"a\"\n7\n8\nnull"
Flatten a nested JSON array, but only down to a given nesting depth. The first line is 'maxdepth=N'. Everything after the first line is one JSON array (the outermost array). Assign levels like this: the direct elements of the outermost array are at level 1, the elements of an array at level L are at level L+1. Walk the...
cmst5hn7o00dfg4p203l13nl2
contributor_item
Submission L13NL2
false
def transform(text): files = [] minus_path = None current = None for line in text.split('\n'): if line.startswith('\\'): continue if line.startswith('--- '): minus_path = line[4:].strip() current = None continue if line.startswith('...
diff --git a/app/main.py b/app/main.py index 83db48f..bf269f4 100644 --- a/app/main.py +++ b/app/main.py @@ -1,5 +1,6 @@ import sys -import os +import pathlib +import json def main(): pass diff --git a/README.md b/README.md deleted file mode 100644 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Project -Docs \...
"app/main.py | 3 ++-\nREADME.md | 2 --\n2 files changed, 2 insertions(+), 3 deletions(-)"
Produce a git-style diffstat from a unified diff. Scan the input line by line. A line starting with '--- ' or '+++ ' is a file header, a line starting with '@@' is a hunk header, and a line starting with '\' (such as '\ No newline at end of file') is ignored. Inside a hunk, a line starting with '+' counts as one insert...
cmst5hn7o00d0g4p25nr9la3x
contributor_item
Submission R9LA3X
false
def transform(text): def to_minutes(hhmm): hours, minutes = hhmm.split(':') return int(hours) * 60 + int(minutes) def to_clock(total): return '{:02d}:{:02d}'.format(total // 60, total % 60) intervals = [] for line in text.split('\n'): line = line.strip() if not ...
09:00-10:30 10:30-11:00 13:15-14:00 09:45-10:00 16:00-15:00 12:00-12:00
"09:00-11:00\n13:15-14:00\ntotal=165"
Merge a list of same-day time ranges. Each non-blank input line is 'HH:MM-HH:MM' and describes the half-open interval [start, end) in minutes since midnight. 1. Discard any interval whose end is less than or equal to its start (this drops reversed and zero-length ranges). 2. Sort the surviving intervals by start ascend...
cmst5hn7o00d1g4p277eqhmv6
contributor_item
Submission EQHMV6
false
PAIRS = ( (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ) DIGITS = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} def to_roman(number): out = [] remaining = number for va...
1994 XLII 0 4000 IIII MMXXVI 58 iv
"1994 -> MCMXCIV\nXLII -> 42\n0 -> ERROR\n4000 -> ERROR\nIIII -> ERROR\nMMXXVI -> 2026\n58 -> LVIII\niv -> ERROR"
Convert each non-blank line of a mixed list between Arabic integers and Roman numerals. For each line, strip surrounding whitespace and classify the token: 1. If it consists only of decimal digits, parse it as an integer. If the integer is between 1 and 3999 inclusive, convert it to a Roman numeral using the standard s...
cmst5hn7o00d8g4p2p7ynk12v
contributor_item
Submission YNK12V
false
def transform(text): kept = [] seen = {} skipped = 0 for raw in text.split('\n'): address = raw.strip() if not address: continue if address.count('@') != 1: skipped += 1 continue local, domain = address.lower().split('@') if not...
First.Last+news@Gmail.com firstlast@gmail.com Bob@Example.COM bob@example.com b.o.b@example.com carol@googlemail.com c.a.r.o.l@gmail.com not-an-email dave@@example.com Eve@Example.com
"First.Last+news@Gmail.com\nBob@Example.COM\nb.o.b@example.com\ncarol@googlemail.com\nEve@Example.com\nskipped=2"
Deduplicate a list of email addresses using provider-aware canonical keys. Strip surrounding whitespace from every line and skip lines that are then empty. A line is invalid, and is skipped and counted, if it does not contain exactly one '@', or if the part before or after the '@' is empty. For a valid address build it...
cmst5hn7o00czg4p2in512vp6
contributor_item
Submission 512VP6
false
def transform(text): def key(version): core = version build = '' if '+' in core: core, build = core.split('+', 1) pre = '' if '-' in core: core, pre = core.split('-', 1) major, minor, patch = (int(p) for p in core.split('.')) if pre == ...
1.0.0 1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1+build.5 v2.1.0 0.9.10
"0.9.10\n1.0.0-alpha\n1.0.0-alpha.1\n1.0.0-alpha.beta\n1.0.0-beta.2\n1.0.0-beta.11\n1.0.0-rc.1+build.5\n1.0.0\n2.1.0"
Sort a newline-separated list of SemVer 2.0.0 version strings into ascending precedence order. Ignore blank lines. A single optional leading 'v' is stripped from each version and is NOT present in the output. Precedence rules: 1. Compare major, then minor, then patch as integers. 2. Build metadata (everything from the ...
cmst5hn7o00d2g4p2jvryxnvw
contributor_item
Submission RYXNVW
false
def transform(text): lines = text.split('\n') if lines and lines[-1] == '': lines = lines[:-1] header = lines[0] shift = int(header.split(':', 1)[1].strip()) % 26 out = [] for line in lines[1:]: chars = [] for ch in line: if 'a' <= ch <= 'z': c...
shift: -3 Attack at Dawn, 07:00! Zulu & aardvark -- ready?
"Xqqxzh xq Axtk, 07:00!\n\nWrir & xxoasxoh -- obxav?"
Apply a Caesar shift to a block of text. The FIRST line of the input has the form 'shift: N' where N is an integer that may be negative or larger than 26; reduce it modulo 26 to get the effective shift. Every line after the first is body text. Shift each ASCII letter forward by the effective shift, wrapping within its ...
cmst5hn7o00d7g4p2bu7ijk9g
contributor_item
Submission 7IJK9G
false
import urllib.parse SMALL_WORDS = ('and', 'of', 'the', 'in') SUFFIXES = ('.html', '.htm', '.php') def render_segment(segment): for suffix in SUFFIXES: if segment.endswith(suffix): segment = segment[:-len(suffix)] break words = [w for w in segment.replace('-', ' ').replace('_',...
https://example.com/docs/getting-started/install-guide.html?ref=nav https://example.com/ https://example.com/blog/2026/the-art-of-data_cleaning /shop/mens-shoes/#reviews
"Home > Docs > Getting Started > Install Guide\nHome\nHome > Blog > 2026 > The Art of Data Cleaning\nHome > Shop > Mens Shoes"
Turn each URL into a breadcrumb trail. For every non-blank line: discard anything from the first '#' onward, then anything from the first '?' onward. Remove a leading scheme and host by deleting a leading 'scheme://host' when the remainder starts with '://' after a scheme; concretely, if the text contains '://', drop e...
cmst5hn7o00deg4p2sj3j3ij6
contributor_item
Submission 3J3IJ6
false
import csv RATES = {'food': 0, 'book': 5, 'general': 10, 'luxury': 20} def transform(text): lines = [l for l in text.split('\n') if l != ''] reader = csv.DictReader(lines) out = [] subtotal_sum = 0 tax_sum = 0 skipped = 0 for row in reader: qty_text = (row.get('qty') or '').strip(...
name,qty,unit_price_cents,category Sourdough Loaf,2,650,food Novel,1,1899,book USB Cable,3,999,general Perfume,1,12500,luxury Mystery Item,1,500,widgets Broken Row,,300,general Free Sample,0,250,food
"Sourdough Loaf x2 = 1300 (tax 0)\nNovel x1 = 1899 (tax 95)\nUSB Cable x3 = 2997 (tax 300)\nPerfume x1 = 12500 (tax 2500)\nMystery Item x1 = 500 (tax 50)\nFree Sample x0 = 0 (tax 0)\nSUBTOTAL=19196\nTAX=2945\nTOTAL=22141\nSKIPPED=1"
Total a shopping cart whose tax rate depends on the line's category. The input is CSV with the header 'name,qty,unit_price_cents,category'. All money is in integer cents. Tax rates by category: 'food' 0 percent, 'book' 5 percent, 'general' 10 percent, 'luxury' 20 percent. Any other category is taxed at the 'general' ra...
cmst5hn7o00dhg4p27t7tv6ms
contributor_item
Submission 7TV6MS
false
import re KEY_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$') REF_RE = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}') def transform(text): values = {} interpolating = {} ignored = 0 for raw in text.split('\n'): line = raw.strip() if not line or line.startswith('#'): continue ...
# database settings DB_HOST=localhost DB_PORT=5432 DB_URL=postgres://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/app DB_USER=admin export DB_PASS='s3cr3t#1' GREETING="Hello ${DB_USER}" EMPTY= LITERAL='raw ${DB_USER}' badline PATH_EXTRA=$HOME/bin TIMEOUT=${MISSING}30
"DB_HOST=localhost\nDB_PASS=s3cr3t#1\nDB_PORT=5432\nDB_URL=postgres://admin:s3cr3t#1@localhost:5432/app\nDB_USER=admin\nEMPTY=\nGREETING=Hello admin\nLITERAL=raw ${DB_USER}\nPATH_EXTRA=$HOME/bin\nTIMEOUT=30\nignored=1"
Parse a .env style file and resolve '${VAR}' references. Ignore lines that are empty after stripping and lines whose first non-space character is '#'. Strip a leading 'export ' prefix. A line is ignored and counted as ignored if it has no '=' or if the text before the first '=', once stripped, does not match the regula...
cmst5hn7o00cyg4p2mou3rcs2
contributor_item
Submission U3RCS2
false
def transform(text): values = {} for line in text.split('\n'): if not line.strip(): continue if ':' not in line: continue raw_name, raw_value = line.split(':', 1) parts = raw_name.strip().lower().split('-') name = '-'.join(p[:1].upper() + p[1:] for...
content-type: application/json X-Request-ID: abc-123 accept: text/html set-cookie: session=a1 this line has no colon SET-COOKIE: theme=dark x-empty: Host: api.example.com
"Accept: text/html\nContent-Type: application/json\nHost: api.example.com\nSet-Cookie: session=a1, theme=dark\nX-Empty:\nX-Request-Id: abc-123"
Normalise a raw HTTP header block into a canonical, sorted list. 1. Process the input line by line, ignoring lines that are empty after stripping and lines that contain no ':' character. 2. Split each remaining line at the FIRST ':' only: the part before is the name, the part after is the value. 3. Canonicalise the nam...
cmst5hn7o00d5g4p25zrbub5i
contributor_item
Submission RBUB5I
false
def transform(text): lines = [l for l in text.split('\n') if l.strip()] cc = lines[0].split('=', 1)[1].strip() out = [] for raw in lines[1:]: body = raw for marker in ('x', 'X'): position = body.find(marker) if position != -1: body = body[:position...
cc=61 +61 2 9374 4000 (02) 9374 4002 00 44 20 7946 0958 0412 345 678 x102 1234 +1-800-555-0199
"+61293744000\n+61293744002\n+442079460958\n+61412345678\nINVALID\n+18005550199"
Normalise a list of raw phone numbers to E.164. The first line is 'cc=N' giving the default country calling code as digits. Every following non-blank line is one raw number. For each raw number, in this order: 1. Drop an extension: if the line contains 'x' or 'X', discard that character and everything after it. 2. Note...
cmst5hn7o00d3g4p2wv6j2gac
contributor_item
Submission 6J2GAC
false
def transform(text): lines = [l for l in text.split('\n') if l.strip()] rows, cols = (int(p) for p in lines[0].split()) grid = [[0] * cols for _ in range(rows)] for line in lines[1:]: row, col, value = (int(p) for p in line.split()) if 0 <= row < rows and 0 <= col < cols: gri...
3 4 0 0 5 1 2 -12 2 3 7 1 2 34 5 0 9 2 -1 4
" 5 0 0 0\n 0 0 34 0\n 0 0 0 7"
Expand a sparse matrix given as triplets into a dense text grid. The first non-blank line holds two integers 'ROWS COLS' separated by whitespace. Every following non-blank line holds three integers 'ROW COL VALUE' with zero-based indices. Rules: start from a grid of all zeros; ignore any triplet whose row is not in [0,...
cmst5hn7o00d4g4p27b2z6rbn
contributor_item
Submission 2Z6RBN
false
import re PLACEHOLDER = re.compile(r'\{\{([^{}]*)\}\}') def transform(text): lines = text.split('\n') if lines and lines[-1] == '': lines = lines[:-1] separator = lines.index('---') table = {} for line in lines[:separator]: if '=' not in line: continue key, val...
name=Ada city= title=Engineer --- Hello {{ name }}, welcome to {{city|Unknown}}. Role: {{title}} / Team: {{team|Core}} Contact: {{email}}
"Hello Ada, welcome to .\nRole: Engineer / Team: Core\nContact:"
Render a small text template against a variable table. The input has two sections separated by a line containing exactly '---'. Lines before it are variable definitions 'key=value' split at the FIRST '='; the key is stripped of surrounding whitespace and the value is taken verbatim after the '=' (so 'city=' defines cit...
cmst5hn7o00dbg4p2fzjacqg4
contributor_item
Submission JACQG4
false
from decimal import Decimal, ROUND_HALF_UP FACTORS = { 'in': ('cm', Decimal('2.54')), 'ft': ('m', Decimal('0.3048')), 'mi': ('km', Decimal('1.609344')), 'lb': ('kg', Decimal('0.45359237')), 'oz': ('g', Decimal('28.349523125')), 'gal': ('L', Decimal('3.785411784')), } CENT = Decimal('0.01') de...
12 in 3 ft 26.2 mi 150 lb 8 oz 98.6 F -40 F 5 gal 7 furlong
"12 in = 30.48 cm\n3 ft = 0.91 m\n26.2 mi = 42.16 km\n150 lb = 68.04 kg\n8 oz = 226.80 g\n98.6 F = 37.00 C\n-40 F = -40.00 C\n5 gal = 18.93 L\n7 furlong = UNSUPPORTED"
Convert a list of imperial measurements to metric. Each non-blank line is '<number> <unit>' separated by whitespace, where the number may be negative or fractional. Supported units and their exact conversions are: 'in' -> cm, multiply by 2.54; 'ft' -> m, multiply by 0.3048; 'mi' -> km, multiply by 1.609344; 'lb' -> kg,...
cmst5hn7o00dag4p2kk8m8b1g
contributor_item
Submission 8M8B1G
false
import csv import io def transform(text): lines = text.split('\n') if lines and lines[-1] == '': lines = lines[:-1] separator = lines.index('---') mapping = [] for line in lines[:separator]: if '->' not in line: continue source, target = line.split('->', 1) ...
sku->Item Code name->Product price->Unit Price discount->Discount --- name,sku,price,notes "Widget, large",W-100,19.99,n/a Gadget,G-200,5.00 Doohickey,D-300,,extra,ignored
"Item Code,Product,Unit Price,Discount\nW-100,\"Widget, large\",19.99,\nG-200,Gadget,5.00,\nD-300,Doohickey,,"
Reorder and rename the columns of a CSV according to a header map. The input has two sections separated by a line containing exactly '---'. Each line before the separator is 'source_column->output_column'; the order of these lines is the order of the output columns. Lines after the separator are CSV data parsed with st...
cmst5hn7o00dcg4p2jdk0udhg
contributor_item
Submission K0UDHG
false
def transform(text): out = [] for raw in text.split('\n'): line = raw.strip() if not line: continue digits = line.replace(' ', '').replace('-', '') if not digits.isdigit() or not digits.isascii(): out.append(line + ': INVALID_CHARS') continue ...
4539 1488 0343 6467 4539-1488-0343-6468 79927398713 6011 1111 1111 1117 5500 0000 0000 0004 1234 5678 9012 345a
"************6467: VALID\n************6468: FAILED_CHECKSUM\n79927398713: INVALID_LENGTH\n************1117: VALID\n************0004: VALID\n1234 5678 9012 345a: INVALID_CHARS"
Validate a list of payment card numbers with the Luhn algorithm and mask them. For each non-blank line, strip surrounding whitespace, then remove every space and every '-' character. Then, in order: 1. If the remaining text contains any character that is not an ASCII digit, the line's status is 'INVALID_CHARS'. 2. Othe...
cmst5hn7o00dgg4p2wlgc3p1s
contributor_item
Submission GC3P1S
false
import json def to_scalar(raw): value = raw if not value.startswith('"') and not value.startswith("'"): position = value.find(' #') if position != -1: value = value[:position] value = value.strip() if len(value) >= 2 and ((value[0] == '"' and value[-1] == '"') or (value[0] ...
# service configuration name: api-gateway version: 2 enabled: true replicas: 3 # desired count timeout: 1.5 notes: null owner: team: platform email: "ops@example.com" tags: - production - "eu-west" - 42 limits: cpu: 500m memory: 1Gi
{ "name": "api-gateway", "version": 2, "enabled": true, "replicas": 3, "timeout": 1.5, "notes": null, "owner": { "team": "platform", "email": "ops@example.com" }, "tags": [ "production", "eu-west", 42 ], "limits": { "cpu": "500m", "memory": "1Gi" } }
Parse a restricted YAML-like configuration block into JSON. Ignore lines that are empty after stripping and lines whose first non-space character is '#'. Indentation is always a multiple of two spaces, and a nested block is always indented exactly two spaces deeper than the 'key:' line that introduces it. A line of the...
cmsu45j0500fgg4p2tg3a30f5
contributor_item
Submission 3A30F5
false
def transform(text): added = 0 removed = 0 for line in text.split('\n'): if line.startswith('+++') or line.startswith('---'): continue if line.startswith('+'): added += 1 elif line.startswith('-'): removed += 1 return 'added={} removed={} net={...
--- a/app.py +++ b/app.py @@ -1,4 +1,5 @@ context -old one -old two +new one +new two +new three context
"added=3 removed=2 net=1"
Collapse a unified-diff hunk into a summary: count added and removed lines (ignoring the +++/--- headers) and return 'added=N removed=M net=K' where net is added minus removed.
cmsu45j0500fhg4p2ts9frwvl
contributor_item
Submission 9FRWVL
false
def transform(text): totals = {} for line in text.strip().split('\n'): if not line.strip(): continue code, amount = line.split() totals[code] = totals.get(code, 0.0) + float(amount) return '\n'.join('{} {:.2f}'.format(c, totals[c]) for c in sorted(totals))
USD 10.5 EUR 3 USD 0.25 GBP 7.125 EUR 1.5
"EUR 4.50\nGBP 7.12\nUSD 10.75"
Given 'currency amount' lines, sum per currency and return 'CUR total' lines sorted by currency code, with totals formatted to exactly two decimal places.
cmsu45j0500feg4p2bjz4cde7
contributor_item
Submission Z4CDE7
false
def transform(text): children = {} seen_child = set() nodes = set() for line in text.strip().split('\n'): if not line.strip(): continue parent, child = line.strip().split('>') children.setdefault(parent, []).append(child) seen_child.add(child) nodes.ad...
app>web app>api web>static api>db lib>util
"app\n api\n db\n web\n static\nlib\n util"
Given lines of 'parent>child', emit an indented tree from every root (a node that is never a child), two spaces per level, children sorted alphabetically, roots sorted alphabetically.
cmsu45j0500ffg4p2j5779mzj
contributor_item
Submission 779MZJ
false
def transform(text): rows = [] for line in text.strip().split('\n')[1:]: if not line.strip(): continue name, score = line.split(',') rows.append((name.strip(), int(score))) def grade(score): for cutoff, letter in ((90, 'A'), (80, 'B'), (70, 'C')): if s...
name,score rhea,90 olu,89 mina,70 kade,69 bea,90
"bea A\nrhea A\nolu B\nmina C\nkade F"
Read 'name,score' CSV lines and return 'name grade' lines where the grade is the letter band A (>=90), B (>=80), C (>=70), else F, ordered by descending score then ascending name.
cmsu45j0500fdg4p27m7or3ys
contributor_item
Submission 7OR3YS
false
def transform(text): entries = [] for line in text.strip().split('\n'): if not line.strip(): continue clock, name = line.split(None, 1) hours, minutes = clock.split(':') entries.append((int(hours) * 60 + int(minutes), name.strip())) entries.sort() lines = ['{}...
09:15 standup 14:05 review 08:00 prep 17:30 wrapup
"prep: 480\nstandup: 555\nreview: 845\nwrapup: 1050\nspan=570"
Parse 'HH:MM name' schedule lines and return each entry as 'name: minutes-since-midnight', sorted chronologically, followed by a final 'span=N' line giving minutes between first and last.
cmsue07fp00ghg4p2e0h0inqd
contributor_item
Submission H0INQD
false
import csv, io, json def transform(text): readings = {} for row in csv.DictReader(io.StringIO(text.strip())): readings.setdefault(row["sensor"], []).append(float(row["reading"])) summary = {} for sensor, values in readings.items(): summary[sensor] = { "min": min(values), ...
sensor,reading t1,20.5 t1,22.5 t2,-3.0 t2,-5.0 t2,1.0
{ "t1": { "min": 20.5, "max": 22.5, "mean": 21.5 }, "t2": { "min": -5, "max": 1, "mean": -2.33 } }
For each sensor return min, max and mean of its readings as JSON, mean rounded to 2 decimals. Sensors are listed in first-seen order. Negative readings are included.