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
cmssjmldo00tgjmp213xmhyk9
contributor_item
Submission XMHYK9
false
import re,json def transform(text): out={} for l in text.splitlines(): if re.fullmatch(r'[^@\s]+@[^@\s]+\.[^@\s]+',l.strip()): d=l.rsplit('@',1)[1].lower(); out[d]=out.get(d,0)+1 return json.dumps(dict(sorted(out.items())))
Ana@Example.COM invalid bo@sub.example.com cy@example.com @missing
{ "example.com": 2, "sub.example.com": 1 }
Convert newline-separated email addresses into a JSON object counting normalized domains, ignoring malformed lines.
cmssjmldo00tijmp2qjbeede9
contributor_item
Submission BEEDE9
false
import statistics def transform(text): seen=[];out=[] for l in text.splitlines(): seen.append(int(l));out.append(str(statistics.median(seen))) return ','.join(out)
5 1 9 3 8
"5,3.0,5,4.0,5"
Parse one integer per line and return a comma-separated running median after each value.
cmssjmldo00tjjmp2ng5r65be
contributor_item
Submission 5R65BE
false
import json,base64 def transform(text): out=[] for s in json.loads(text): try:out.append(base64.b64decode(s,validate=True).decode()) except (ValueError,UnicodeDecodeError):out.append(None) return json.dumps(out)
["aGVsbG8=","4pyT","////"]
[ "hello", "✓", null ]
Decode a JSON array of base64 strings as UTF-8 and return a JSON array, replacing invalid entries with null.
cmssjmldo00tkjmp29612e6ey
contributor_item
Submission 12E6EY
false
def transform(text): versions=[] for l in text.splitlines(): parts=list(map(int,l.split('.')));parts += [0]*(3-len(parts));versions.append(tuple(parts[:3])) return '\n'.join('.'.join(map(str,v)) for v in sorted(versions))
1.10 1.2.3 2 1.2 0.9.9
"0.9.9\n1.2.0\n1.2.3\n1.10.0\n2.0.0"
Parse version strings, sort them numerically by dot-separated components, and return normalized three-component versions.
cmssjmldo00tmjmp2p8j6iy8x
contributor_item
Submission J6IY8X
false
import json def transform(text): merged=[] for a,b in sorted(json.loads(text)): if merged and a<=merged[-1][1]:merged[-1][1]=max(b,merged[-1][1]) else:merged.append([a,b]) return str(sum(b-a for a,b in merged))
[[1,4],[3,6],[8,10],[10,12],[15,16]]
10
Parse JSON time intervals and return their total covered length after merging overlaps, treating endpoints as continuous.
cmssjmldo00tnjmp2p8rlm5as
contributor_item
Submission RLM5AS
false
import json from pathlib import PurePosixPath def transform(text): out={} for l in text.splitlines(): p=PurePosixPath(l);ext=p.suffix[1:].lower() if p.suffix else '(none)';out.setdefault(ext,[]).append(p.name) return json.dumps({k:sorted(v) for k,v in sorted(out.items())})
src/app.PY README archive.tar.gz docs/guide.md .test
{ "(none)": [ ".test", "README" ], "gz": [ "archive.tar.gz" ], "md": [ "guide.md" ], "py": [ "app.PY" ] }
Parse newline-delimited paths and return JSON grouped by lowercase extension, using '(none)' for extensionless files.
cmssjmldo00t1jmp2m7ny3ss9
contributor_item
Submission NY3SS9
false
import json def transform(text): out=[] for order in json.loads(text): for i in order['items']: out.append({'order_id':order['order_id'],'sku':i['sku'],'line_total':round(i['qty']*i['price'],2)}) return json.dumps(out)
[{"order_id":"o1","items":[{"sku":"A","qty":2,"price":3.5},{"sku":"B","qty":1,"price":9}]},{"order_id":"o2","items":[{"sku":"A","qty":4,"price":3.5}]}]
[ { "order_id": "o1", "sku": "A", "line_total": 7 }, { "order_id": "o1", "sku": "B", "line_total": 9 }, { "order_id": "o2", "sku": "A", "line_total": 14 } ]
Explode a JSON array of orders into one JSON row per line item, carrying order_id and computing line_total.
cmssjmldo00tcjmp2grohub0c
contributor_item
Submission OHUB0C
false
import csv,io,json def transform(text): out={} for r in csv.DictReader(io.StringIO(text)): out[r['id']]={'name':r['name'],'score':int(r['score'])} return json.dumps(out)
id,name,score 1,Ana,4 2,Bo,7 1,Ana,9
{ "1": { "name": "Ana", "score": 9 }, "2": { "name": "Bo", "score": 7 } }
Convert CSV rows into a JSON mapping from id to the last row for that id, coercing score to integer.
cmssjmldo00thjmp2zp51fvka
contributor_item
Submission 51FVKA
false
import csv,io,json def transform(text): out=[] for r in csv.DictReader(io.StringIO(text)): lat,lon=float(r['lat']),float(r['lon']) if 10<=lat<=15 and 20<=lon<=25: out.append({'id':r['id'],'lat':lat,'lon':lon}) return json.dumps(out)
id,lat,lon a,10,20 b,15,25 c,9,22 d,12,30
[ { "id": "a", "lat": 10, "lon": 20 }, { "id": "b", "lat": 15, "lon": 25 } ]
Parse CSV latitude/longitude rows and return only points inside an inclusive bounding box as JSON.
cmssjmldo00tljmp28u13tbdd
contributor_item
Submission 13TBDD
false
def transform(text): rows=[(l.rsplit(' ',1)[0],int(l.rsplit(' ',1)[1])) for l in text.splitlines()];m=max(v for _,v in rows) return '\n'.join(f'{k}: '+('#'*round(v/m*10)) for k,v in rows)
alpha 5 beta 10 gamma 2
"alpha: #####\nbeta: ##########\ngamma: ##"
Convert a text histogram of 'label count' rows into proportional ASCII bars scaled to a maximum width of 10.
cmssjmldo00tpjmp24k9y58cw
contributor_item
Submission 9Y58CW
false
def transform(text): return '\n'.join(':'.join(part.zfill(4) for part in l.split(':')) for l in text.splitlines())
a:b:0:ff 1:20:300:4000
"000a:000b:0000:00ff\n0001:0020:0300:4000"
Parse colon-separated IPv6-like hex groups, left-pad each group to four characters, and join with colons.
cmssjmldo00tyjmp2fpvllxbo
contributor_item
Submission VLLXBO
false
import json def transform(text): out={} for l in text.splitlines(): name,raw=l.split(':',1) for dep in raw.split(','):out.setdefault(dep.strip(),set()).add(name.strip()) return json.dumps({k:sorted(v) for k,v in sorted(out.items())})
app: api, db worker: db, queue api: db
{ "api": [ "app" ], "db": [ "api", "app", "worker" ], "queue": [ "worker" ] }
Convert lines of 'name: comma-separated dependencies' into a JSON reverse-dependency map with sorted unique dependents.
cmssjmldn00srjmp2bzdg05wr
contributor_item
Submission DG05WR
false
import json def transform(text): out={} for line in text.splitlines(): status=int(line.split()[2]); key=f"{status//100}xx"; out[key]=out.get(key,0)+1 return json.dumps(dict(sorted(out.items())))
GET /a 200 12ms POST /b 503 9ms GET /c 404 2ms PUT /d 201 30ms GET /e 500 1ms
{ "2xx": 2, "4xx": 1, "5xx": 2 }
Parse Apache-style request lines and return a JSON object counting status-code classes (2xx, 4xx, 5xx).
cmssjmldo00tojmp2pyfv2csi
contributor_item
Submission FV2CSI
false
import csv,io,json def transform(text): out={} for r in csv.DictReader(io.StringIO(text)): x=out.setdefault(r['session'],{'first':int(r['ts']),'last':int(r['ts']),'count':0});t=int(r['ts']);x['first']=min(x['first'],t);x['last']=max(x['last'],t);x['count']+=1 return json.dumps(dict(sorted(out.items(...
session,ts,event a,10,start b,11,start a,15,click a,21,end b,18,end
{ "a": { "first": 10, "last": 21, "count": 3 }, "b": { "first": 11, "last": 18, "count": 2 } }
Convert CSV event rows to a JSON session summary using the first and last timestamps and event count per session.
cmssjmldo00trjmp2vfxdyc74
contributor_item
Submission XDYC74
false
import json def transform(text): edges=json.loads(text);nodes={x for e in edges for x in e};out={n:[] for n in nodes} for a,b in edges:out[a].append(b) return json.dumps({k:sorted(v) for k,v in sorted(out.items())})
[["root","b"],["root","a"],["a","x"],["b","x"]]
{ "a": [ "x" ], "b": [ "x" ], "root": [ "a", "b" ], "x": [] }
Convert a JSON list of parent-child edges into a JSON mapping of each node to its sorted children, including leaf nodes.
cmssjmldo00tqjmp285kf73tt
contributor_item
Submission KF73TT
false
import json,re def transform(text): d=json.loads(text);return re.sub(r'\{\{(\w+)\}\}',lambda m:str(d['values'].get(m.group(1),m.group(0))),d['template'])
{"template":"Hi {{name}}, status={{status}}, id={{id}}","values":{"name":"Ana","status":"ready"}}
"Hi Ana, status=ready, id={{id}}"
Apply ordered text replacement rules from a JSON object to a template containing {{name}} placeholders, leaving unknown placeholders unchanged.
cmssjmldo00ttjmp2tni1odn8
contributor_item
Submission I1ODN8
false
import json,csv,io def transform(text): rows=[json.loads(l) for l in text.splitlines()];fields=sorted({k for r in rows for k in r});out=io.StringIO();w=csv.DictWriter(out,fieldnames=fields,lineterminator='\n');w.writeheader();w.writerows(rows);return out.getvalue().strip()
{"b":2,"a":1} {"c":4,"a":3}
"a,b,c\n1,2,\n3,,4"
Convert one JSON object per line into a CSV string whose columns are the sorted union of all keys.
cmssjmldo00tsjmp2k523pwg4
contributor_item
Submission 23PWG4
false
import json def transform(text): lines=text.splitlines();headers=lines[0].split();out=[] for l in lines[1:]:out.append(dict(zip(headers,l.split(maxsplit=len(headers)-1)))) return json.dumps(out)
ID SCORE NOTE 1 90 excellent work 2 75 needs review
[ { "ID": "1", "SCORE": "90", "NOTE": "excellent work" }, { "ID": "2", "SCORE": "75", "NOTE": "needs review" } ]
Parse a whitespace-separated table and return JSON rows using the first line as headers, while keeping the final column's remaining words together.
cmssjmldo00twjmp2pljgu96n
contributor_item
Submission JGU96N
false
import json def transform(text): x=y=0 for token in text.split(','): d,n=token[0],int(token[1:]);x += n if d=='E' else -n if d=='W' else 0;y += n if d=='N' else -n if d=='S' else 0 return json.dumps({'x':x,'y':y,'distance':abs(x)+abs(y)})
N3,E2,S5,W1,N1
{ "x": 1, "y": -1, "distance": 2 }
Convert a sequence of compass moves such as N3,E2 into the final coordinate and Manhattan distance as JSON.
cmssjmldo00tujmp26ygj3dro
contributor_item
Submission GJ3DRO
false
import json def transform(text): groups={} for w in text.splitlines():groups.setdefault(''.join(sorted(w)),[]).append(w) out=[sorted(v) for v in groups.values() if len(v)>1];out.sort(key=lambda v:v[0]);return json.dumps(out)
listen silent enlist rat tar solo
[ [ "enlist", "listen", "silent" ], [ "rat", "tar" ] ]
Parse a list of words and return JSON anagram groups with at least two members, sorting words and then groups by first word.
cmssjmldo00tvjmp227546r92
contributor_item
Submission 546R92
false
import json def transform(text): rows=[r for r in json.loads(text) if r['weight']];return str(round(sum(r['score']*r['weight'] for r in rows)/sum(r['weight'] for r in rows),3))
[{"score":80,"weight":2},{"score":95,"weight":1},{"score":10,"weight":0}]
85
Parse a JSON list of weighted scores and return the weighted mean rounded to three decimals, ignoring zero-weight rows.
cmssjmldo00txjmp25pzh0xli
contributor_item
Submission ZH0XLI
false
import json def transform(text): out={} for r in json.loads(text): if r['id'] not in out or r['rev']>=out[r['id']]['rev']:out[r['id']]=r return json.dumps([out[k] for k in sorted(out)])
[{"id":"a","rev":1,"v":"old"},{"id":"b","rev":2,"v":"x"},{"id":"a","rev":3,"v":"new"},{"id":"b","rev":2,"v":"last"}]
[ { "id": "a", "rev": 3, "v": "new" }, { "id": "b", "rev": 2, "v": "last" } ]
Parse JSON records and retain the highest revision per id, breaking equal-revision ties by the last occurrence.
cmssjmldo00tzjmp2haimxgfh
contributor_item
Submission IMXGFH
false
import json def transform(text): m=json.loads(text);return json.dumps({'rows':[sum(r) for r in m],'columns':[sum(c) for c in zip(*m)],'diagonal':sum(m[i][i] for i in range(len(m)))})
[[2,3,4],[5,6,7],[8,9,10]]
{ "rows": [ 9, 18, 27 ], "columns": [ 15, 18, 21 ], "diagonal": 18 }
Parse a JSON matrix and return JSON containing row sums, column sums, and the main diagonal sum.
cmssjmldo00u0jmp2dtg5pd41
contributor_item
Submission G5PD41
false
def transform(text): out=[] for l in text.splitlines(): if ',' in l:last,first=map(str.strip,l.split(',',1)) else:first,last=l.split(maxsplit=1) out.append(f'{last.title()}, {first.title()}') return '\n'.join(sorted(out,key=str.lower))
Ada Lovelace Hopper, Grace alan turing Liskov, Barbara
"Hopper, Grace\nLiskov, Barbara\nLovelace, Ada\nTuring, Alan"
Normalize newline-separated names to 'Last, First' form, accepting either 'First Last' or 'Last, First', then sort case-insensitively.
cmssjmldo00u2jmp22fod2jnd
contributor_item
Submission OD2JND
false
import re,json def transform(text): terms=re.findall(r'[+-]?[^+-]+',text.replace(' ',''));out={} for term in terms: sign=-1 if term.startswith('-') else 1;t=term.lstrip('+-') if 'x' in t: raw=t.split('x')[0];coef=sign*(int(raw) if raw else 1);power=int(t.split('^')[1]) if '^' in t el...
3x^2-2x+5
{ "0": 5, "1": -2, "2": 3 }
Parse a compact polynomial like '3x^2-2x+5' and return coefficient values for descending powers as JSON.
cmssjmldo00u1jmp2pu4ao4aa
contributor_item
Submission 4AO4AA
false
import json def transform(text): last={};out={} for l in text.splitlines(): r=json.loads(l);d=r['device'];out.setdefault(d,[]) if d in last:out[d].append(r['value']-last[d]) last[d]=r['value'] return json.dumps(dict(sorted(out.items())))
{"device":"a","value":10} {"device":"b","value":3} {"device":"a","value":14} {"device":"a","value":9} {"device":"b","value":8}
{ "a": [ 4, -5 ], "b": [ 5 ] }
Parse newline-delimited JSON measurements and compute consecutive deltas per device, returning JSON arrays keyed by device.
cmssjn52m00u3jmp2tqjdjgf6
contributor_item
Submission JDJGF6
false
import csv, io, json def transform(input): rows = [] for r in csv.DictReader(io.StringIO(input.strip())): qty = int(r["qty"]) price = float(r["unit_price"]) rows.append({ "sku": r["sku"], "qty": qty, "unit_price": price, "line_total": roun...
sku,qty,unit_price A-100,3,4.50 B-220,1,19.99 C-005,12,0.75
[ { "sku": "A-100", "qty": 3, "unit_price": 4.5, "line_total": 13.5 }, { "sku": "B-220", "qty": 1, "unit_price": 19.99, "line_total": 19.99 }, { "sku": "C-005", "qty": 12, "unit_price": 0.75, "line_total": 9 } ]
Parse the CSV and emit a JSON array of objects. Coerce qty to an integer and unit_price to a float, and add a computed line_total rounded to 2 decimals. Output compact JSON with keys in the order sku, qty, unit_price, line_total.
cmssjn52m00u5jmp2rhzygwxw
contributor_item
Submission ZYGWXW
false
import json def transform(input): def walk(node, prefix, out): if isinstance(node, dict): for k, v in node.items(): walk(v, "%s.%s" % (prefix, k) if prefix else k, out) elif isinstance(node, list): for i, v in enumerate(node): walk(v, "%s.%d" ...
{"user":{"name":"ada","langs":["py","js"],"addr":{"city":"London","zip":null}},"active":true}
"active=true\nuser.addr.city=London\nuser.addr.zip=null\nuser.langs.0=py\nuser.langs.1=js\nuser.name=ada"
Flatten the nested JSON object into dotted key paths, one 'path=value' line per leaf, sorted by path. Index list elements numerically. Render null as 'null' and booleans lowercase.
cmssjn52m00u6jmp2e8elaoh2
contributor_item
Submission ELAOH2
false
def transform(input): lines = input.strip("\n").split("\n")[1:] out = [] for line in lines: if not line.strip(): continue name = line[0:10].strip() dept = line[10:19].strip() hours = line[19:].strip() out.append("%s|%s|%s" % (name, dept, hours)) return...
NAME DEPT HOURS Ada Eng 38 Grace Research 41 Linus Eng 7
"Ada|Eng|38\nGrace|Research|41\nLinus|Eng|7"
The input is fixed-width: NAME is columns 0-9, DEPT is 10-18, HOURS is 19 onward. Skip the header, strip each field, and emit 'name|dept|hours' lines preserving input order.
cmssjn52m00u8jmp2hq7mm0m3
contributor_item
Submission 7MM0M3
false
import re from datetime import datetime MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] def transform(input): out = [] for line in input.strip("\n").split("\n"): s = line.strip() iso = "INVALID" m = re.fullmatch(r"(\d{1,2})[/-](\d...
03/04/2021 2021-4-5 Apr 6 2021 06-04-2021 not a date
"2021-04-03\n2021-04-05\n2021-04-06\n2021-04-06\nINVALID"
Normalise each line to ISO YYYY-MM-DD. Slash and dash numeric forms are DD/MM/YYYY. Accept 'Mon D YYYY'. Emit 'INVALID' for anything unparseable. One output line per input line, order preserved.
cmssjn52m00uajmp236mrqfpj
contributor_item
Submission MRQFPJ
false
def transform(input): last = {} for line in input.strip("\n").split("\n"): if not line.strip(): continue user, event, time = line.split(",") last[user] = (event, time) return "\n".join( "%s,%s,%s" % (u, last[u][0], last[u][1]) for u in sorted(last) )
u1,login,09:00 u2,login,09:05 u1,logout,17:30 u3,login,09:07 u2,logout,18:00 u1,login,19:00
"u1,login,19:00\nu2,logout,18:00\nu3,login,09:07"
Each line is 'user,event,time'. Keep only the LAST row for each user, then emit them sorted by user id ascending as 'user,event,time'.
cmssjn52m00ucjmp2v662ilb9
contributor_item
Submission 62ILB9
false
import json def transform(input): rows = json.loads(input) cols = list(rows[0].keys()) widths = {c: max(len(c), *(len(str(r[c])) for r in rows)) for c in cols} def line(cells): return "| " + " | ".join(cells) + " |" out = [line([c.ljust(widths[c]) for c in cols]), line(["-" * wid...
[{"id":1,"name":"ada"},{"id":42,"name":"grace hopper"},{"id":7,"name":"bob"}]
"| id | name |\n| -- | ------------ |\n| 1 | ada |\n| 42 | grace hopper |\n| 7 | bob |"
Render the JSON array as a GitHub-flavoured markdown table. Columns come from the first object's keys in order. Pad every cell with spaces so each column is as wide as its widest value (including the header), and use '---' dashes matching that width.
cmssjn52m00uejmp21m1jk2bo
contributor_item
Submission 1JK2BO
false
import csv, io, json def transform(input): out = [] for r in csv.DictReader(io.StringIO(input.strip("\n"))): tags = [t for t in (r["tags"] or "").split(",") if t] out.append({"id": int(r["id"]), "title": r["title"], "tags": tags}) return json.dumps(out, indent=2)
id,title,tags 1,"Hello, World","intro,basics" 2,"Say ""hi""","greeting" 3,Plain,
[ { "id": 1, "title": "Hello, World", "tags": [ "intro", "basics" ] }, { "id": 2, "title": "Say \"hi\"", "tags": [ "greeting" ] }, { "id": 3, "title": "Plain", "tags": [] } ]
Parse the CSV honouring quoted fields and escaped double quotes. Split the tags field on commas into a list (empty field becomes an empty list). Emit a JSON array with 2-space indentation.
cmssjn52m00u7jmp2rcvj3oad
contributor_item
Submission VJ3OAD
false
def transform(input): lines = input.strip("\n").split("\n")[1:] agg = {} for line in lines: if not line.strip(): continue region, amount = line.split("\t") entry = agg.setdefault(region, [0, 0]) entry[0] += 1 entry[1] += int(amount) rows = sorted(agg.i...
region amount north 120 south 80 north 45 east 200 south 20
"region,count,total,mean\neast,1,200,200.0\nnorth,2,165,82.5\nsouth,2,100,50.0"
Group the TSV rows by region and emit 'region,count,total,mean' lines. Mean is rounded to 1 decimal. Sort by total descending, then region ascending. Include a header row.
cmssjn52m00ubjmp2p7x0znea
contributor_item
Submission X0ZNEA
false
def transform(input): quarters = ["Q1", "Q2", "Q3", "Q4"] table = {} for line in input.strip("\n").split("\n")[1:]: if not line.strip(): continue product, quarter, units = line.split(",") table.setdefault(product, {})[quarter] = int(units) out = ["product," + ",".join...
product,quarter,units widget,Q1,10 widget,Q3,7 gadget,Q1,4 gadget,Q2,9
"product,Q1,Q2,Q3,Q4\ngadget,4,9,0,0\nwidget,10,0,7,0"
Pivot the long CSV into a wide table with one row per product and a column per quarter Q1..Q4 in order. Use 0 for missing combinations. Emit CSV with a header row, products sorted alphabetically.
cmssjn52m00udjmp2nszqmt54
contributor_item
Submission ZQMT54
false
from itertools import groupby def transform(input): runs = [(ch, len(list(grp))) for ch, grp in groupby(input.strip())] encoded = ",".join("%s:%d" % (ch, n) for ch, n in runs) best_ch, best_n = runs[0] for ch, n in runs[1:]: if n > best_n: best_ch, best_n = ch, n return "%s\nrun...
aaabbbbcccaadddddd
"a:3,b:4,c:3,a:2,d:6\nruns=5 longest=d"
Run-length encode the string as 'char:count' pairs joined by commas in order of appearance, then append a second line 'runs=N longest=CHAR' where longest is the character of the single longest run (earliest wins on a tie).
cmssjn52m00ufjmp2mb0ycyad
contributor_item
Submission 0YCYAD
false
import re from collections import Counter STOP = {"the", "a"} def transform(input): words = re.findall(r"[a-z']+", input.lower()) counts = Counter(w for w in words if w not in STOP) top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:5] return ",".join("%s=%d" % (w, n) for w, n in top)
The quick brown fox jumps over the lazy dog. The dog barks; the fox runs! A quick escape.
"dog=2,fox=2,quick=2,barks=1,brown=1"
Count word frequencies case-insensitively, stripping punctuation. Exclude the stopwords 'the' and 'a'. Emit the top 5 as 'word=count' sorted by count descending then word ascending, comma separated on one line.
cmssjn52m00u4jmp2bjrke4ml
contributor_item
Submission RKE4ML
false
from urllib.parse import unquote_plus def transform(input): pairs = {} for part in input.strip().split("&"): if not part: continue key, sep, val = part.partition("=") key = unquote_plus(key) val = unquote_plus(val) if sep else "<flag>" seen = pairs.setdefault...
tag=red&size=10&tag=blue&debug&size=10&name=wide%20grip
"debug: <flag>\nname: wide grip\nsize: 10\ntag: red|blue"
Parse the URL query string. Percent-decode values, represent a bare key with no '=' as the literal token <flag>, collapse exact duplicate values for the same key, and emit one 'key: v1|v2' line per key sorted alphabetically by key.
cmssjn52m00u9jmp2blrsxelc
contributor_item
Submission RSXELC
false
import json def transform(input): data, section = {}, None for raw in input.strip("\n").split("\n"): line = raw.strip() if not line or line.startswith(";"): continue if line.startswith("[") and line.endswith("]"): section = line[1:-1] data.setdefault(...
; app config [server] port = 8080 host = 0.0.0.0 debug = false [cache] ttl = 300 enabled = true
{ "cache": { "enabled": true, "ttl": 300 }, "server": { "debug": false, "host": "0.0.0.0", "port": 8080 } }
Parse the INI text into nested JSON. Ignore comment lines starting with ';'. Coerce integer-looking values to ints and true/false to booleans. Emit JSON with 2-space indentation and sorted keys.
cmssjn52m00uhjmp2c7mwa55l
contributor_item
Submission MWA55L
false
from decimal import Decimal def transform(input): cents, out = 0, [] for line in input.strip("\n").split("\n"): s = line.strip().replace(",", "") neg = s.startswith("-") s = s.lstrip("-").lstrip("$") value = int(Decimal(s) * 100) if neg: value = -value ...
$1,234.56 -$0.07 $12 $1,000,000.00
"123456\n-7\n1200\n100000000\ntotal=100124649"
Convert each currency string to an exact integer number of cents (no floating point rounding error), one per line, then append a final line 'total=N' with the sum in cents.
cmssjn52m00ujjmp2hf3ui6u9
contributor_item
Submission 3UI6U9
false
def transform(input): sets = {} for line in input.strip("\n").split("\n"): name, _, vals = line.partition(":") sets[name.strip()] = {int(v) for v in vals.strip().split(",") if v.strip()} left, right = sets["left"], sets["right"] def render(s): return ",".join(str(v) for v in sort...
left: 1,2,5,8,13 right: 2,3,5,13,21
"only_left=1,8\nboth=2,5,13\nonly_right=3,21"
Compare the two comma-separated id lists. Emit exactly three lines: 'only_left=...', 'both=...', 'only_right=...', each a comma-separated ascending list of integers, using '-' when a set is empty.
cmssjn52m00ugjmp2pbyw839t
contributor_item
Submission YW839T
false
import json def transform(input): index = {} for line in input.strip("\n").split("\n"): if not line.strip(): continue rec = json.loads(line) index.setdefault(rec["sym"], set()).add(rec["file"]) return "\n".join( "%s -> %s" % (sym, ", ".join(sorted(index[sym]))) f...
{"file":"a.py","sym":"parse"} {"file":"b.py","sym":"parse"} {"file":"a.py","sym":"emit"} {"file":"c.py","sym":"emit"} {"file":"a.py","sym":"parse"}
"emit -> a.py, c.py\nparse -> a.py, b.py"
Build an inverted index from symbol to the sorted unique list of files defining it. Emit 'sym -> f1, f2' lines sorted by symbol name.
cmssjn52n00ukjmp2niid4ym3
contributor_item
Submission ID4YM3
false
def transform(input): lines = [l for l in input.strip("\n").split("\n") if l.strip()] depths = [(len(l) - len(l.lstrip(" "))) // 2 for l in lines] names = [l.strip() for l in lines] out, stack = [], [] for i, (d, name) in enumerate(zip(depths, names)): stack = stack[:d] + [name] is_l...
src api routes.py schema.py utils io.py tests test_api.py
"src/api/routes.py\nsrc/api/schema.py\nsrc/utils/io.py\ntests/test_api.py"
The input is a two-space-indented tree. Emit the full slash-joined path of every LEAF node (a line with no more-indented line after it), in input order.
cmssjn52m00uijmp2tj77g71j
contributor_item
Submission 77G71J
false
def transform(input): limit = 20 lines, current = [], "" for word in input.split(): if not current: current = word elif len(current) + 1 + len(word) <= limit: current += " " + word else: lines.append(current) current = word if curre...
The quick brown fox jumps over the extraordinarily lazy dog near the riverbank
"The quick brown fox\njumps over the\nextraordinarily lazy\ndog near the\nriverbank"
Greedily wrap the text to a maximum line width of 20 characters without splitting words. A word longer than the limit gets its own line. Emit the wrapped lines.
cmssjn52n00uljmp243gqxprd
contributor_item
Submission GQXPRD
false
def transform(input): out = [] for line in input.strip("\n").split("\n"): if not line.strip(): continue email, _, age = line.partition(",") local, at, domain = email.partition("@") if not at or "@" in domain or "." not in domain or not local: out.append("R...
alice@example.com,32 bob@example,17 carol@example.org,abc dave@example.net,45
"VALID alice@example.com 32\nREJECT bob@example bad_email\nREJECT carol@example.org bad_age\nVALID dave@example.net 45"
Each line is 'email,age'. A record is valid when the email contains exactly one '@' with a dot in the domain and the age is an integer between 18 and 120 inclusive. Emit 'VALID <email> <age>' or 'REJECT <email> <reason>' where reason is 'bad_email', 'bad_age' or 'underage', checking email first. Preserve input order.
cmssjn52n00umjmp27pis1akd
contributor_item
Submission IS1AKD
false
def transform(input): rows = [line.split(",") for line in input.strip("\n").split("\n") if line.strip()] width = max(len(r) for r in rows) padded = [r + [""] * (width - len(r)) for r in rows] return "\n".join(",".join(col) for col in zip(*padded))
a,b,c 1,2,3,4 x,y
"a,1,x\nb,2,y\nc,3,\n,4,"
Transpose the ragged CSV. Pad short rows with empty strings out to the longest row length first, then emit the transposed rows as comma-separated lines.
cmssl1xtl014rjmp20g3dokux
contributor_item
Submission 3DOKUX
false
import json def transform(text): totals = {} for line in text.strip().split('\n'): fields = {} for token in line.strip().split(): if '=' in token: key, value = token.split('=', 1) fields[key] = value endpoint = fields.get('endpoint') d...
endpoint=/login duration_ms=120 status=200 endpoint=/login duration_ms=95 status=200 endpoint=/data duration_ms=340 status=500 endpoint=/data duration_ms=210 status=200 endpoint=/login duration_ms=80 status=404
{ "/login": 295, "/data": 550 }
Parse space-separated key=value log lines and compute the total 'duration_ms' per 'endpoint', returning a JSON object mapping endpoint to total duration.
cmssl1xtl014qjmp2zy50g0i2
contributor_item
Submission 50G0I2
false
import json def transform(text): result = {} current = None for raw_line in text.strip().split('\n'): line = raw_line.strip() if not line: continue if line.startswith('[') and line.endswith(']'): current = line[1:-1] result[current] = {} e...
[server] host = 127.0.0.1 port = 8080 [auth] enabled = true timeout = 30
{ "server": { "host": "127.0.0.1", "port": "8080" }, "auth": { "enabled": "true", "timeout": "30" } }
Parse a simple INI-style config with [section] headers and key=value lines into a nested JSON object of sections to key/value maps, stripping whitespace.
cmssl1xtl014pjmp2rpcrgfwo
contributor_item
Submission CRGFWO
false
import csv import io import json def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) result = [] for row in reader: parsed = {} for key, value in row.items(): value = value.strip() if value.isdigit(): parsed[key] = int(value) ...
name,age,score Alice,30,92.5 Bob,25,88 Cara,22,79.25
[ { "name": "Alice", "age": 30, "score": 92.5 }, { "name": "Bob", "age": 25, "score": 88 }, { "name": "Cara", "age": 22, "score": 79.25 } ]
Parse a CSV block with a header row into a JSON array of objects, converting numeric-looking values to int or float.
cmssl1xtl014sjmp2cwvjzjx8
contributor_item
Submission VJZJX8
false
import re import json def transform(text): pattern = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' matches = re.findall(pattern, text) unique = sorted(set(m.lower() for m in matches)) return json.dumps(unique)
Contact Alice at alice@example.com or Alice@Example.com for support. Bob's email is bob@example.org. For urgent issues, reach alice@example.com again or try admin@example.com.
[ "admin@example.com", "alice@example.com", "bob@example.org" ]
Extract all email addresses from a block of free text, remove duplicates (case-insensitive), and return a JSON array of the unique addresses sorted alphabetically in lowercase.
cmssl1xtl014ujmp2dlwh59jn
contributor_item
Submission WH59JN
false
import re import json def transform(text): slugs = [] for line in text.split('\n'): line = line.strip() if not line: continue lowered = line.lower() cleaned = re.sub(r'[^a-z0-9]+', '-', lowered) slug = cleaned.strip('-') slugs.append(slug) return ...
Hello, World! Python -- The Amazing Language AI & Machine Learning: 2024 Trends ???Weird***Title###
[ "hello-world", "python-the-amazing-language", "ai-machine-learning-2024-trends", "weird-title" ]
Convert each line of text (article titles) into a URL-friendly slug: lowercase, alphanumeric with hyphens replacing whitespace/punctuation, collapsing consecutive hyphens and stripping leading/trailing hyphens. Skip blank lines. Return a JSON array of slugs in the original order.
cmssl1xtl014tjmp251xedbg6
contributor_item
Submission XEDBG6
false
import json def transform(text): result = {} stack = [(-1, result)] for raw_line in text.rstrip('\n').split('\n'): if not raw_line.strip(): continue indent = len(raw_line) - len(raw_line.lstrip(' ')) key, _, value = raw_line.strip().partition(':') key = key.strip...
database: host: localhost port: 5432 cache: provider: redis ttl: 60
{ "database": { "host": "localhost", "port": "5432" }, "cache": { "provider": "redis", "ttl": "60" } }
Parse a minimal YAML-like structure using 2-space indentation to denote nested keys under a parent, and convert it into a nested JSON object. Leaf values are strings.
cmssl1xtm014wjmp2g477hu0z
contributor_item
Submission 77HU0Z
false
import json def transform(text): results = [] for line in text.strip().split('\n'): parts = line.strip().split() a, op, b = parts[0], parts[1], parts[2] a_num = int(a) b_num = int(b) if op == '+': results.append(a_num + b_num) elif op == '-': ...
12 + 8 10 - 15 6 * 7 9 / 4 20 / 5
[ 20, -5, 42, 2.25, 4 ]
Parse a list of simple two-operand arithmetic expressions (format 'NUM OP NUM', where OP is +, -, *, or /), compute each result, and return a JSON array of results. Division should always produce a float per Python true-division semantics; other operations should produce integers when both operands are integers.
cmssl1xtl014vjmp2ushe7bsd
contributor_item
Submission HE7BSD
false
def transform(text): lines = [l for l in text.strip().split('\n') if l.strip()] rows = [line.split('\t') for line in lines] header = rows[0] body = rows[1:] header_line = '| ' + ' | '.join(header) + ' |' separator_line = '| ' + ' | '.join(['---'] * len(header)) + ' |' body_lines = ['| ' + ' ...
Name Role Years Alice Engineer 5 Bob Manager 8
"| Name | Role | Years |\n| --- | --- | --- |\n| Alice | Engineer | 5 |\n| Bob | Manager | 8 |"
Convert tab-separated values (TSV) text with a header row into a Markdown table string, including the header separator row of dashes.
cmssl1xtm014xjmp2oxly6es5
contributor_item
Submission LY6ES5
false
import json ROMAN_VALUES = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} def roman_to_int(s): total = 0 prev = 0 for ch in reversed(s): value = ROMAN_VALUES[ch] if value < prev: total -= value else: total += value prev = value ...
XIV IX XL MCMXCIV III
{ "values": [ 14, 9, 40, 1994, 3 ], "total": 2060 }
Convert each line (a Roman numeral, uppercase) into its integer value using standard subtractive notation rules, and return a JSON object with a 'values' array (in original order) and a 'total' field equal to their sum.
cmssl1xtm014yjmp22dvptqjf
contributor_item
Submission VPTQJF
false
import json def transform(text): records = [] for line in text.strip().split('\n'): record = {} for pair in line.split(';'): pair = pair.strip() if not pair: continue key, _, value = pair.partition(':') key = key.strip() ...
id: 1; name: Widget; price: 25; in_stock: true id: 2; name: Gadget; price: 40; in_stock: false id: 3; name: Gizmo; price: 15; in_stock: true
[ { "id": 1, "name": "Widget", "price": 25, "in_stock": "true" }, { "id": 2, "name": "Gadget", "price": 40, "in_stock": "false" }, { "id": 3, "name": "Gizmo", "price": 15, "in_stock": "true" } ]
Parse text where each line is a record of semicolon-separated 'key: value' pairs, and convert it into a JSON array of objects. Values that look like integers should be converted to int; all other values (including 'true'/'false') remain strings.
cmssl2whj0155jmp209jo2tjc
contributor_item
Submission JO2TJC
false
import csv, io, json def transform(text): reader = csv.reader(io.StringIO(text.strip())) rows = list(reader) header = rows[0] data_rows = rows[1:] transposed = {header[i]: [row[i] for row in data_rows] for i in range(len(header))} return json.dumps(transposed)
name,age,city Alice,30,NYC Bob,25,LA
{ "name": [ "Alice", "Bob" ], "age": [ "30", "25" ], "city": [ "NYC", "LA" ] }
Parse a CSV table and transpose it into a JSON object mapping each column header to a list of that column's values.
cmssl2whj0156jmp2sg72upqs
contributor_item
Submission 72UPQS
false
import re def transform(text): return re.sub(r'[\w.+-]+@[\w-]+\.[\w.-]+', '[REDACTED]', text)
Contact us at support@example.com or sales@example.org for help. CC: admin@internal.net
"Contact us at [REDACTED] or [REDACTED] for help.\nCC: [REDACTED]"
Redact all email addresses in the input text, replacing each with the literal string '[REDACTED]', leaving all other text unchanged.
cmssl2whj0154jmp23r3jgi1d
contributor_item
Submission 3JGI1D
false
import json from collections import defaultdict def transform(text): groups = defaultdict(list) for line in text.strip().split('\n'): line = line.strip() if not line: continue level = line[1:line.index(']')] msg = line[line.index(']')+2:] groups[level].append...
[ERROR] Connection refused [INFO] Server started [ERROR] Timeout occurred [WARN] Disk space low [INFO] Request handled
{ "ERROR": [ "Connection refused", "Timeout occurred" ], "INFO": [ "Server started", "Request handled" ], "WARN": [ "Disk space low" ] }
Group bracketed log lines like '[LEVEL] message' by their level into a JSON object mapping level to a list of messages, preserving order.
cmssl2whi0153jmp2q2rrdq4e
contributor_item
Submission RRDQ4E
false
import json def transform(text): result = {} 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] result[section] = {} elif '=' ...
[server] host = 0.0.0.0 port = 8080 [database] name = mydb timeout = 30
{ "server": { "host": "0.0.0.0", "port": "8080" }, "database": { "name": "mydb", "timeout": "30" } }
Parse an INI-style config file with [section] headers into a nested JSON object of section -> {key: value}.
cmssldaii015njmp26p0rucir
contributor_item
Submission 0RUCIR
false
import json def transform(text): data = json.loads(text) pairs = [] def walk(node, prefix): if isinstance(node, dict): for k, v in node.items(): walk(v, prefix + '.' + k if prefix else k) elif isinstance(node, list): for i, v in enumerate(node): ...
{"service": {"name": "auth", "retries": 3}, "limits": {"cpu": "500m", "tags": ["prod", "eu"]}, "active": true}
"active=true\nlimits.cpu=500m\nlimits.tags[0]=prod\nlimits.tags[1]=eu\nservice.name=auth\nservice.retries=3"
Flatten a nested JSON object into dotted-path 'key=value' lines sorted alphabetically by key. Index list elements with a bracketed position, for example limits.tags[0]. Render booleans lowercase as true/false.
cmssldaii015ojmp23k50ckkx
contributor_item
Submission 50CKKX
false
import json, re LINE = re.compile(r'^(\S+) \S+ \S+ \[[^\]]+\] "(\w+) (\S+) [^"]*" (\d{3}) (\d+)$') def transform(text): stats = {} for raw in text.strip().split('\n'): m = LINE.match(raw.strip()) if not m: continue _, _, path, status, size = m.groups() entry = stats...
10.0.0.4 - - [12/Aug/2026:09:14:02] "GET /api/users HTTP/1.1" 200 431 10.0.0.9 - - [12/Aug/2026:09:14:05] "POST /api/users HTTP/1.1" 201 88 10.0.0.4 - - [12/Aug/2026:09:15:41] "GET /api/orders HTTP/1.1" 500 12 10.0.0.7 - - [12/Aug/2026:09:16:00] "GET /api/users HTTP/1.1" 404 0 10.0.0.4 - - [12/Aug/2026:09:16:22] "GET /...
[ { "path": "/api/users", "requests": 3, "error_rate": 0.33, "bytes": 519 }, { "path": "/api/orders", "requests": 2, "error_rate": 1, "bytes": 24 } ]
Parse Common Log Format lines and emit a JSON array of objects, one per request path, containing 'path', 'requests', 'error_rate' (share of responses with status 400 or above, rounded to two decimals) and 'bytes' (total bytes). Sort by requests descending, then path ascending.
cmssldaii015kjmp2yjb07w4g
contributor_item
Submission B07W4G
false
import json def transform(text): result = {} section = None for raw in text.strip().split('\n'): line = raw.strip() if not line or line.startswith((';', '#')): continue if line.startswith('[') and line.endswith(']'): section = line[1:-1].strip() c...
[db] host = localhost port = 5432 [cache] host = redis.internal ttl = 300 enabled = yes
{ "db.host": "localhost", "db.port": 5432, "cache.host": "redis.internal", "cache.ttl": 300, "cache.enabled": true }
Parse an INI-style config into a flat JSON object whose keys are 'section.option'. Coerce values that are all digits to integers and the words yes/no to booleans; leave everything else as strings. Keys must appear in the order they occur in the input.
cmssldaii015ljmp2k8ylnxvm
contributor_item
Submission YLNXVM
false
def transform(text): def key(tag): body = tag.lstrip('v') core, _, pre = body.partition('-') nums = [int(p) for p in core.split('.')] if not pre: return (nums, 1, []) parts = [] for p in pre.split('.'): parts.append((0, int(p), '') if p.isdigit...
v1.10.0 v1.2.0 v1.10.0-rc.2 v2.0.0 v1.10.0-rc.10 v1.2.10
"v1.2.0\nv1.2.10\nv1.10.0-rc.2\nv1.10.0-rc.10\nv1.10.0\nv2.0.0"
Sort a list of semantic version tags in ascending precedence order, one per line. Compare major, minor and patch numerically (not lexicographically), and rank a pre-release version below the same version without a pre-release. Compare numeric pre-release identifiers numerically. Keep the leading 'v' in the output.
cmssldaii015mjmp20uqim3fh
contributor_item
Submission QIM3FH
false
import csv, io def transform(text): rows = list(csv.DictReader(io.StringIO(text.strip()))) products = sorted({r['product'] for r in rows}) totals = {} order = [] for r in rows: region = r['region'] if region not in totals: totals[region] = {} order.append(reg...
region,product,units "West, Coastal",widget,12 East,widget,5 "West, Coastal",gadget,3 East,gadget,8 East,widget,7
"region,gadget,widget\n\"West, Coastal\",3,12\nEast,8,12"
Read a CSV where some fields are quoted and contain commas. Produce a pivot table as CSV: the first column is 'region', followed by one column per distinct product sorted alphabetically, with each cell the summed units for that region and product (0 when absent). Region rows appear in first-seen order. Use \n line endi...
cmsslvn1o0178jmp2hb6asu2y
contributor_item
Submission 6ASU2Y
false
import csv, io from datetime import datetime def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) latest = {} for row in reader: sku = row['sku'] ts = datetime.fromisoformat(row['updated_at']) if sku not in latest or ts > latest[sku][0]: latest[sku] = ...
sku,name,quantity,updated_at A100,Widget,50,2026-01-01T09:00:00 A100,Widget,45,2026-01-03T14:00:00 B200,Gadget,10,2026-01-02T11:00:00 A100,Widget,48,2026-01-02T08:00:00 B200,Gadget,12,2026-01-01T10:00:00
"sku,name,quantity,updated_at\r\nA100,Widget,45,2026-01-03T14:00:00\r\nB200,Gadget,10,2026-01-02T11:00:00"
Given a CSV inventory log with columns sku,name,quantity,updated_at where the same sku may appear multiple times with different updated_at timestamps, deduplicate so only the row with the most recent updated_at is kept per sku. Return the deduplicated rows as CSV sorted by sku ascending.
cmsslvn1o0175jmp2l4nxd2id
contributor_item
Submission NXD2ID
false
import csv, io, json from collections import defaultdict def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) totals = defaultdict(float) for row in reader: totals[row['region']] += float(row['revenue']) result = {region: round(total, 2) for region, total in sorted(totals.ite...
region,product,revenue East,Widget,120.50 West,Gadget,89.99 East,Gizmo,45.00 North,Widget,200.00 West,Widget,75.25 East,Widget,60.00
{ "East": 225.5, "North": 200, "West": 165.24 }
Parse CSV sales records with columns region, product, revenue. Sum revenue per region (rounding to 2 decimals) and return a JSON object mapping region name to total revenue, with keys in alphabetical order.
cmsslvn1o017bjmp2opfs9b83
contributor_item
Submission FS9B83
false
import csv, io def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) subjects = [f for f in reader.fieldnames if f != 'student'] rows = [] for row in reader: for subj in subjects: rows.append({'student': row['student'], 'subject': subj, 'score': row[subj]}) row...
student,math,science,english Alice,85,90,78 Bob,70,65,80
"student,subject,score\r\nAlice,english,78\r\nAlice,math,85\r\nAlice,science,90\r\nBob,english,80\r\nBob,math,70\r\nBob,science,65"
Convert a wide-format CSV of student scores (columns: student, plus one column per subject) into long format with columns student, subject, score — one row per student-subject pair. Sort rows by student, then by subject name alphabetically. Return as CSV.
cmsslvn1o017fjmp26zqjrb1u
contributor_item
Submission QJRB1U
false
import json, csv, io def transform(text): data = json.loads(text) out = io.StringIO() writer = csv.writer(out) writer.writerow(['order_id', 'customer', 'sku', 'qty', 'unit_price', 'line_total']) for item in data['items']: line_total = round(item['qty'] * item['unit_price'], 2) write...
{"order_id": "ORD-500", "customer": "Dana Lee", "items": [{"sku": "X1", "qty": 2, "unit_price": 9.99}, {"sku": "X2", "qty": 1, "unit_price": 24.5}]}
"order_id,customer,sku,qty,unit_price,line_total\r\nORD-500,Dana Lee,X1,2,9.99,19.98\r\nORD-500,Dana Lee,X2,1,24.5,24.5"
Given a JSON order object with order_id, customer, and a nested 'items' array (each with sku, qty, unit_price), explode it into one CSV row per line item with columns order_id, customer, sku, qty, unit_price, line_total (line_total = qty * unit_price, rounded to 2 decimals). Return as CSV.
cmsslvn1o017jjmp2ifxi3fo8
contributor_item
Submission XI3FO8
false
import json def transform(text): data = json.loads(text) names = [p['name'] for p in data if p['in_stock'] and p['price'] < 20.00] return json.dumps(sorted(names))
[{"name": "Widget", "price": 12.5, "in_stock": true}, {"name": "Gadget", "price": 45.0, "in_stock": true}, {"name": "Gizmo", "price": 8.0, "in_stock": false}, {"name": "Doohickey", "price": 19.99, "in_stock": true}]
[ "Doohickey", "Widget" ]
Given a JSON array of product objects with name, price, in_stock, filter to only products that are in stock AND priced strictly below 20.00. Return a JSON array of just the matching product names, sorted alphabetically.
cmsslvn1o017ljmp28qkwzd3r
contributor_item
Submission KWZD3R
false
import csv, io from collections import defaultdict def transform(text): reader = list(csv.DictReader(io.StringIO(text.strip()))) questions = sorted(set(r['question'] for r in reader)) users = defaultdict(dict) for r in reader: users[r['user']][r['question']] = r['answer'] out = io.StringIO(...
user,question,answer u1,q1,Yes u1,q2,No u2,q1,No u2,q2,No u3,q1,Yes u3,q2,Yes
"user,q1,q2\r\nu1,Yes,No\r\nu2,No,No\r\nu3,Yes,Yes"
Given a long-format CSV of survey responses with columns user, question, answer, pivot it to wide format: one row per user, one column per distinct question (columns sorted alphabetically by question id), with cell values being the answer. Return as CSV with header 'user' followed by the question columns, rows sorted b...
cmsslvn1o0176jmp25ojfckr4
contributor_item
Submission JFCKR4
false
import json, csv, io def transform(text): data = json.loads(text) out = io.StringIO() fieldnames = ['id', 'name', 'address_city', 'address_zip', 'active'] writer = csv.DictWriter(out, fieldnames=fieldnames) writer.writeheader() for rec in data: row = { 'id': rec['id'], ...
[{"id": 1, "name": "Alice", "address": {"city": "Boston", "zip": "02118"}, "active": true}, {"id": 2, "name": "Bob", "address": {"city": "Austin", "zip": "73301"}, "active": false}]
"id,name,address_city,address_zip,active\r\n1,Alice,Boston,02118,True\r\n2,Bob,Austin,73301,False"
Given a JSON array of user records where each record has a nested 'address' object with 'city' and 'zip', flatten each record into a flat CSV row with columns id,name,address_city,address_zip,active (address fields prefixed with 'address_'). Return the CSV as a string.
cmsslvn1o017ajmp2vxj2sjuq
contributor_item
Submission J2SJUQ
false
import re, json from collections import Counter STOPWORDS = {'the', 'and', 'over', 'while', 'a', 'an', 'to', 'of', 'in', 'is', 'it'} def transform(text): words = re.findall(r"[a-zA-Z']+", text.lower()) words = [w for w in words if w not in STOPWORDS] counts = Counter(words) top = sorted(counts.items()...
The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs away quickly. The lazy dog sleeps while the fox watches.
[ [ "dog", 3 ], [ "fox", 3 ], [ "lazy", 2 ], [ "away", 1 ], [ "barks", 1 ] ]
Given a paragraph of English text, tokenize it into lowercase alphabetic words (apostrophes allowed), remove a small fixed stopword list ('the','and','over','while','a','an','to','of','in','is','it'), count word frequencies, and return the top 5 most frequent words as a JSON array of [word, count] pairs sorted by count...
cmsslvn1o017djmp2754jqr9x
contributor_item
Submission 4JQR9X
false
import json def transform(text): data = json.loads(text) cust_map = {c['customer_id']: c['name'] for c in data['customers']} result = [] for order in data['orders']: result.append({ 'order_id': order['order_id'], 'customer_name': cust_map.get(order['customer_id'], 'Unkno...
{"orders": [{"order_id": 1001, "customer_id": "C1", "amount": 250.0}, {"order_id": 1002, "customer_id": "C2", "amount": 75.5}, {"order_id": 1003, "customer_id": "C1", "amount": 120.0}], "customers": [{"customer_id": "C1", "name": "Alice Chen"}, {"customer_id": "C2", "name": "Bob Martin"}]}
[ { "order_id": 1001, "customer_name": "Alice Chen", "amount": 250 }, { "order_id": 1002, "customer_name": "Bob Martin", "amount": 75.5 }, { "order_id": 1003, "customer_name": "Alice Chen", "amount": 120 } ]
Given a JSON object with two keys 'orders' (list of order_id, customer_id, amount) and 'customers' (list of customer_id, name), join each order with its customer's name via customer_id, producing a JSON array of objects with order_id, customer_name, amount, sorted by order_id ascending. Use 'Unknown' for any order whos...
cmsslvn1o017mjmp2iflic069
contributor_item
Submission LIC069
false
import json def flatten(d, prefix=''): items = {} for k, v in d.items(): new_key = f'{prefix}.{k}' if prefix else k if isinstance(v, dict): items.update(flatten(v, new_key)) else: items[new_key] = v return items def transform(text): data = json.loads(tex...
{"app": {"name": "EMORA", "server": {"host": "localhost", "port": 8080, "tls": {"enabled": true}}}, "debug": false}
{ "app.name": "EMORA", "app.server.host": "localhost", "app.server.port": 8080, "app.server.tls.enabled": true, "debug": false }
Given a deeply nested JSON configuration object, flatten it into a single-level JSON object whose keys are dot-separated paths to each leaf value (non-dict values). Return the flattened object as JSON with keys sorted alphabetically.
cmsslvn1o0177jmp2kie2x5rh
contributor_item
Submission E2X5RH
false
import json 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: parts = line.split() status = int(parts[-1]) path = parts[-2] if status >= 500: counts[path] += 1 ...
2026-01-01T10:00:00Z GET /api/users 200 2026-01-01T10:00:05Z GET /api/orders 503 2026-01-01T10:00:07Z POST /api/orders 500 2026-01-01T10:00:09Z GET /api/users 500 2026-01-01T10:00:11Z GET /api/health 200
{ "/api/orders": 2, "/api/users": 1 }
Parse space-delimited server log lines of the form '<timestamp> <method> <path> <status>'. Keep only lines with an HTTP status code of 500 or greater, count how many such error lines occurred per path, and return a JSON object mapping path to count, ordered by count descending (ties broken alphabetically by path).
cmsslvn1o017cjmp294f3hnpl
contributor_item
Submission F3HNPL
false
import csv, io from collections import defaultdict MONTH_ORDER = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) totals = defaultdict(lambda: defaultdict(int)) months_seen = set() for row in reader: ...
region,month,amount East,Jan,100 East,Feb,150 West,Jan,80 West,Feb,90 East,Jan,50
"region,Jan,Feb\r\nEast,150,150\r\nWest,80,90"
Given a long-format CSV of transactions with columns region, month, amount (month values are 3-letter abbreviations, integer amounts), pivot into a wide table: one row per region, one column per month (ordered chronologically Jan..Dec, only including months present in the data), with cell values being the sum of amount...
cmsslvn1o0179jmp23hzacazk
contributor_item
Submission ZACAZK
false
import json def transform(text): data = json.loads(text) temps = [d['temp'] for d in data] result = [] for i, d in enumerate(data): window = temps[max(0, i-2):i+1] avg = round(sum(window) / len(window), 2) result.append({'time': d['time'], 'rolling_avg': avg}) return json.du...
[{"time": "08:00", "temp": 20.0}, {"time": "08:05", "temp": 21.0}, {"time": "08:10", "temp": 22.0}, {"time": "08:15", "temp": 23.0}, {"time": "08:20", "temp": 24.0}]
[ { "time": "08:00", "rolling_avg": 20 }, { "time": "08:05", "rolling_avg": 20.5 }, { "time": "08:10", "rolling_avg": 21 }, { "time": "08:15", "rolling_avg": 22 }, { "time": "08:20", "rolling_avg": 23 } ]
Given a JSON array of sensor readings each with 'time' and 'temp', compute a trailing rolling average of temp over a window of up to 3 readings (the current reading plus the up-to-2 preceding readings; early readings use whatever readings are available). Return a JSON array of objects with 'time' and 'rolling_avg' (rou...
cmsslvn1o017gjmp2iaqx11s8
contributor_item
Submission QX11S8
false
import csv, io, json, re def clean_name(name): name = name.strip() name = re.sub(r'\s+', ' ', name) return name.title() def clean_email(email): email = email.strip().lower() email = email.replace(' ', '') return email def transform(text): reader = csv.DictReader(io.StringIO(text.strip()))...
raw_name,raw_email " ALICE Johnson ","Alice.Johnson@EXAMPLE.com " "bob DAVIS"," bob_davis@Example.COM" " CARLA ruiz","carla.ruiz@example.com "
[ { "name": "Alice Johnson", "email": "alice.johnson@example.com" }, { "name": "Bob Davis", "email": "bob_davis@example.com" }, { "name": "Carla Ruiz", "email": "carla.ruiz@example.com" } ]
Given a CSV of raw_name, raw_email pairs with inconsistent capitalization and extraneous whitespace, clean each name into title case with single spaces (trimmed), and clean each email by trimming whitespace, removing internal spaces, and lowercasing. Return a JSON array of objects with 'name' and 'email' in original ro...
cmsslvn1o017ejmp2n9airp1d
contributor_item
Submission AIRP1D
false
import csv, io, json from datetime import datetime def parse_date(s): for fmt in ('%m/%d/%Y', '%Y-%m-%d', '%d-%m-%Y'): try: return datetime.strptime(s, fmt).strftime('%Y-%m-%d') except ValueError: continue raise ValueError(f'Unrecognized date format: {s}') def transform...
item,price,purchase_date Laptop,"$1,299.99",03/15/2026 Mouse,$25.00,2026-03-16 Keyboard,"$89.5",15-03-2026
[ { "item": "Laptop", "price": 1299.99, "purchase_date": "2026-03-15" }, { "item": "Mouse", "price": 25, "purchase_date": "2026-03-16" }, { "item": "Keyboard", "price": 89.5, "purchase_date": "2026-03-15" } ]
Given a CSV of purchases with columns item, price (formatted as a dollar amount, possibly with thousands-separator commas and quoted), purchase_date (in one of three inconsistent formats: MM/DD/YYYY, YYYY-MM-DD, or DD-MM-YYYY), normalize price to a plain float and purchase_date to ISO format YYYY-MM-DD. Return a JSON a...
cmsslvn1o017ijmp2plrhyggh
contributor_item
Submission RHYGGH
false
import json from collections import defaultdict def transform(text): data = json.loads(text) groups = defaultdict(list) for rec in data: groups[rec['department']].append(rec['salary']) result = {} for dept in sorted(groups): salaries = groups[dept] result[dept] = { ...
[{"name": "Alice", "department": "Engineering", "salary": 95000}, {"name": "Bob", "department": "Sales", "salary": 65000}, {"name": "Carla", "department": "Engineering", "salary": 105000}, {"name": "Dan", "department": "Sales", "salary": 70000}, {"name": "Eve", "department": "Marketing", "salary": 60000}]
{ "Engineering": { "count": 2, "avg_salary": 100000 }, "Marketing": { "count": 1, "avg_salary": 60000 }, "Sales": { "count": 2, "avg_salary": 67500 } }
Given a JSON array of employee records with name, department, salary, group employees by department and compute the count of employees and average salary (rounded to 2 decimals) per department. Return a JSON object mapping department name to an object with 'count' and 'avg_salary', with department keys in alphabetical ...
cmsslvn1o017hjmp2wxl80ry3
contributor_item
Submission L80RY3
false
import csv, io def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) seen = set() rows = [] for row in reader: key = row['email'].lower() if key not in seen: seen.add(key) rows.append(row) out = io.StringIO() writer = csv.DictWriter(out,...
id,name,email 1,Alice,alice@example.com 2,Alice Cooper,ALICE@example.com 3,Bob,bob@example.com 4,Bob Two,bob@example.com 5,Carla,carla@example.com
"id,name,email\r\n1,Alice,alice@example.com\r\n3,Bob,bob@example.com\r\n5,Carla,carla@example.com"
Given a CSV of id,name,email rows where the same email address may appear more than once with different casing, deduplicate rows by email (case-insensitive), keeping only the first occurrence in file order. Return the deduplicated rows as CSV, preserving original row order among the kept rows.
cmsslvn1o017kjmp2rxif6fr9
contributor_item
Submission IF6FR9
false
import csv, io def transform(text): reader = list(csv.DictReader(io.StringIO(text.strip()))) closes = [float(r['close']) for r in reader] out = io.StringIO() writer = csv.writer(out) writer.writerow(['date', 'moving_avg_3']) for i in range(2, len(reader)): window = closes[i-2:i+1] ...
date,close 2026-01-01,100.0 2026-01-02,102.0 2026-01-03,101.0 2026-01-04,105.0 2026-01-05,107.0
"date,moving_avg_3\r\n2026-01-03,101.0\r\n2026-01-04,102.67\r\n2026-01-05,104.33"
Given a CSV of daily stock closing prices with columns date, close, compute a 3-day trailing moving average of close, emitting a result only once a full 3-day window is available (i.e., starting from the 3rd row onward). Return a CSV with columns date, moving_avg_3 (rounded to 2 decimals), where date is the date of the...
cmsslvn1o017njmp2thsbabgf
contributor_item
Submission SBABGF
false
import re, json EMAIL_RE = re.compile(r'[\w.+-]+@[\w-]+\.[\w.-]+') PHONE_RE = re.compile(r'\(?\d{3}\)?[\s.-]?\d{3}-\d{4}') def transform(text): emails = sorted(set(EMAIL_RE.findall(text))) phones = sorted(set(PHONE_RE.findall(text))) return json.dumps({'emails': emails, 'phones': phones})
Contact us: John Doe - john.doe@company.com or call (555) 123-4567. Alternatively reach Sales at sales@company.org, phone 555-987-6543.
{ "emails": [ "john.doe@company.com", "sales@company.org" ], "phones": [ "(555) 123-4567", "555-987-6543" ] }
Given an unstructured block of text containing contact information, extract all email addresses and all US-style phone numbers (formats like '(555) 123-4567' or '555-987-6543'). Return a JSON object with keys 'emails' and 'phones', each a sorted, de-duplicated JSON array of the extracted strings.
cmsslvn1o017ojmp279ow3vvw
contributor_item
Submission OW3VVW
false
import json from collections import defaultdict, Counter def transform(text): data = json.loads(text) by_day = defaultdict(Counter) for rec in data: day = rec['timestamp'].split('T')[0] by_day[day][rec['event']] += 1 result = {} for day in sorted(by_day): result[day] = dict(...
[{"timestamp": "2026-02-01T09:15:00", "event": "login"}, {"timestamp": "2026-02-01T10:00:00", "event": "click"}, {"timestamp": "2026-02-01T11:30:00", "event": "login"}, {"timestamp": "2026-02-02T08:00:00", "event": "logout"}, {"timestamp": "2026-02-02T08:05:00", "event": "click"}, {"timestamp": "2026-02-02T08:10:00", "...
{ "2026-02-01": { "click": 1, "login": 2 }, "2026-02-02": { "click": 2, "logout": 1 } }
Given a JSON array of event log records with 'timestamp' (ISO datetime string) and 'event' (event type name), group events by calendar day (YYYY-MM-DD portion of the timestamp) and count occurrences of each event type within each day. Return a nested JSON object: outer keys are dates (sorted ascending), inner keys are ...
cmssm4xl101bujmp2k0r8yfxx
contributor_item
Submission R8YFXX
false
def transform(text): temps = [float(x) for x in text.strip().split(',')] celsius = [round((f - 32) * 5 / 9, 1) for f in temps] return ','.join(str(c) for c in celsius)
32,68,98.6,212
"0.0,20.0,37.0,100.0"
Convert a comma-separated list of Fahrenheit temperatures into Celsius, rounded to 1 decimal place, comma-separated.
cmssm4xl101bsjmp25dxw8wr2
contributor_item
Submission XW8WR2
false
import csv, json, io def transform(text): reader = csv.DictReader(io.StringIO(text.strip())) return json.dumps(list(reader))
name,age,city Alice,30,NYC Bob,25,LA
[ { "name": "Alice", "age": "30", "city": "NYC" }, { "name": "Bob", "age": "25", "city": "LA" } ]
Parse a CSV with a header row into a JSON array of objects, one object per data row.
cmssm4xl101btjmp2lrkzfiug
contributor_item
Submission KZFIUG
false
import json def transform(text): data = json.loads(text) def flatten(obj, prefix=''): items = {} for k, v in obj.items(): new_key = f"{prefix}.{k}" if prefix else k if isinstance(v, dict): items.update(flatten(v, new_key)) else: ...
{"user": {"name": "Ada", "address": {"city": "London", "zip": "E1"}}, "active": true}
{ "user.name": "Ada", "user.address.city": "London", "user.address.zip": "E1", "active": true }
Flatten a nested JSON object into a single-level JSON object with dot-notation keys.
cmssm4xl101bwjmp2dds4l2fw
contributor_item
Submission S4L2FW
false
import json def transform(text): data = json.loads(text) def to_camel(key): parts = key.split('_') return parts[0] + ''.join(p.capitalize() for p in parts[1:]) result = {to_camel(k): v for k, v in data.items()} return json.dumps(result)
{"first_name": "Ada", "last_name": "Lovelace", "user_id": 42}
{ "firstName": "Ada", "lastName": "Lovelace", "userId": 42 }
Convert all snake_case keys in a flat JSON object to camelCase, keeping values unchanged.
cmssm4xl101bvjmp2w3zfn2xx
contributor_item
Submission ZFN2XX
false
import re, json def transform(text): emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.-]+', text) emails = [e.rstrip('.') for e in emails] unique_sorted = sorted(set(emails)) return json.dumps(unique_sorted)
Contact us at support@example.com or sales@example.com. For urgent issues email support@example.com again or admin@test.org.
[ "admin@test.org", "sales@example.com", "support@example.com" ]
Extract all unique email addresses from the text, sort them alphabetically, and return as a JSON array of strings.
cmssnl4rm000xg4p2o39ql7fo
contributor_item
Submission 9QL7FO
false
def transform(text): import json records = [] for line in text.strip().splitlines(): parts = line.split(';') d = {} for p in parts: k, v = p.split(':', 1) k = k.strip() v = v.strip() d[k] = None if v.upper() == 'N/A' else v reco...
Name: Alice Johnson; Phone: 555-1234; Email: alice@example.com Name: Bob Smith; Phone: N/A; Email: bob@example.com Name: Carol White; Phone: 555-9876; Email: N/A
[ { "Name": "Alice Johnson", "Phone": "555-1234", "Email": "alice@example.com" }, { "Name": "Bob Smith", "Phone": null, "Email": "bob@example.com" }, { "Name": "Carol White", "Phone": "555-9876", "Email": null } ]
Each line is a semi-structured contact record with 'Key: value' pairs separated by semicolons (Name, Phone, Email). Parse each line into a JSON object with lowercase-preserved original keys, converting any value of 'N/A' (case-insensitive) to null. Return a JSON array of these objects.
cmssnl4rm000yg4p24bvre6as
contributor_item
Submission VRE6AS
false
def transform(text): import csv, io, json reader = csv.DictReader(io.StringIO(text)) return json.dumps(list(reader))
name,quote Alice,"She said, ""Hello, world!""" Bob,"Simple text" Carol,"Multi, part, quote"
[ { "name": "Alice", "quote": "She said, \"Hello, world!\"" }, { "name": "Bob", "quote": "Simple text" }, { "name": "Carol", "quote": "Multi, part, quote" } ]
Parse this CSV file correctly, respecting RFC-4180 quoting rules where fields may contain embedded commas and doubled double-quotes as escaped quote characters. Return a JSON array of objects, one per row, keyed by the header column names.
cmssnl4rm000ng4p2zybb071w
contributor_item
Submission BB071W
false
def transform(text): import csv, io lines = [l for l in text.splitlines() if l.strip() != ''] header_line = lines[0] starts = [i for i, c in enumerate(header_line) if c != ' ' and (i == 0 or header_line[i - 1] == ' ')] max_len = max(len(l) for l in lines) starts.append(max_len) def split_li...
NAME AGE CITY John Doe 34 New York Jane Smith 29 Boston Al Lee 45 San Francisco
"NAME,AGE,CITY\nJohn Doe,34,New York\nJane Smith,29,Boston\nAl Lee,45,San Francisco\n"
This is a fixed-width text table (columns aligned by the header's start positions). Detect column boundaries from the header row, extract each column's values by slicing at those positions and stripping whitespace, and return the data reformatted as standard comma-separated CSV text (including the header row).
cmssnl4rm000wg4p20jksceih
contributor_item
Submission KSCEIH
false
def transform(text): import json lines = [l for l in text.strip().splitlines() if l.strip()] header = [c.strip() for c in lines[0].strip('|').split('|')] rows = lines[2:] result = [] for line in rows: cells = [c.strip() for c in line.strip('|').split('|')] d = {} for h, c...
| Name | Score | Grade | |------|-------|-------| | Alice | 92 | A | | Bob | 78 | C | | Carol | | B |
[ { "Name": "Alice", "Score": 92, "Grade": "A" }, { "Name": "Bob", "Score": 78, "Grade": "C" }, { "Name": "Carol", "Score": null, "Grade": "B" } ]
Parse this Markdown table (header row, separator row, then data rows) into a JSON array of objects keyed by column name. Numeric-looking cell values should become integers, empty cells should become null, and all other cells stay strings.
cmssnl4rm000og4p2pw2zg0fn
contributor_item
Submission 2ZG0FN
false
def transform(text): import configparser, json cp = configparser.ConfigParser() cp.read_string(text) def coerce(v): vl = v.lower() if vl in ('true', 'false'): return vl == 'true' try: if '.' in v: return float(v) return int(v) ...
[server] host = localhost port = 8080 debug = true timeout = 30.5 [database] name = mydb user = admin ssl = false
{ "server": { "host": "localhost", "port": 8080, "debug": true, "timeout": 30.5 }, "database": { "name": "mydb", "user": "admin", "ssl": false } }
Parse this INI-style configuration text into a JSON object keyed by section name, where each section maps its keys to values coerced to the correct type: 'true'/'false' become booleans, numeric strings become int or float, everything else stays a string.
cmssnl4rm000qg4p2p88jc5tj
contributor_item
Submission 8JC5TJ
false
def transform(text): import json from datetime import datetime formats = ["%m/%d/%Y", "%d-%b-%Y", "%B %d, %Y", "%Y.%m.%d"] results = [] for line in text.strip().splitlines(): line = line.strip() parsed = None for fmt in formats: try: parsed = datet...
08/10/2026 15-Aug-2026 August 20, 2026 2026.09.05 not-a-date
[ "2026-08-10", "2026-08-15", "2026-08-20", "2026-09-05", null ]
Each line contains a date in one of several inconsistent formats (MM/DD/YYYY, DD-Mon-YYYY, Month DD, YYYY, or YYYY.MM.DD). Normalize every parseable date to ISO 8601 (YYYY-MM-DD). If a line cannot be parsed as any known format, use null for that entry. Return a JSON array preserving the original line order.
cmssnl4rm0011g4p24b9j2j4r
contributor_item
Submission 9J2J4R
false
def transform(text): import csv, io, json from collections import defaultdict reader = csv.DictReader(io.StringIO(text)) sums = defaultdict(float) counts = defaultdict(int) order = [] for row in reader: minute_key = row['timestamp'][:16] if minute_key not in sums: ...
timestamp,value 2026-08-10 10:00:01,20 2026-08-10 10:00:15,22 2026-08-10 10:00:47,21 2026-08-10 10:01:05,30 2026-08-10 10:01:50,28
[ { "minute": "2026-08-10 10:00", "average": 21 }, { "minute": "2026-08-10 10:01", "average": 29 } ]
This CSV has timestamped sensor readings with second-level precision and multiple readings per minute. Truncate each timestamp to the minute (drop seconds), group readings by minute, and compute the average value per minute (rounded to 2 decimals). Return a JSON array of objects with keys 'minute' and 'average', in chr...
cmssnl4rm000sg4p2sln4jgin
contributor_item
Submission N4JGIN
false
def transform(text): import html, re decoded = html.unescape(text) decoded = decoded.replace('\xa0', ' ') normalized = re.sub(r'\s+', ' ', decoded).strip() return normalized
Price: &lt;$50&gt; &nbsp; Free Shipping! Hurry &amp; save now. Limited time offer... &quot;Don&#39;t miss it&quot;
"Price: <$50> Free Shipping! Hurry & save now. Limited time offer... \"Don't miss it\""
This text contains HTML entities (&lt;, &gt;, &amp;, &quot;, &#39;, &nbsp;) and irregular whitespace (tabs, multiple spaces, blank lines). Decode all HTML entities to their literal characters, convert non-breaking spaces to regular spaces, collapse all runs of whitespace into single spaces, and trim leading/trailing wh...
cmssnl4rm000lg4p2dikj0k1i
contributor_item
Submission KJ0K1I
false
def transform(text): import re, json from collections import defaultdict pattern = re.compile(r'^(\S+) - - \[.*?\] "\S+ \S+ \S+" (\d{3})') counts = defaultdict(lambda: defaultdict(int)) for line in text.strip().splitlines(): m = pattern.match(line) if not m: continue ...
192.168.1.1 - - [10/Aug/2026:13:55:36] "GET /index.html HTTP/1.1" 200 1024 192.168.1.2 - - [10/Aug/2026:13:56:01] "GET /about HTTP/1.1" 404 512 192.168.1.1 - - [10/Aug/2026:13:57:22] "POST /login HTTP/1.1" 200 256 192.168.1.1 - - [10/Aug/2026:13:58:10] "GET /missing HTTP/1.1" 404 128 192.168.1.3 - - [10/Aug/2026:13:59:...
{ "192.168.1.1": { "200": 2, "404": 1 }, "192.168.1.2": { "200": 1, "404": 1 }, "192.168.1.3": { "500": 1 } }
Parse this Apache-style access log. For each client IP address, count how many requests resulted in each HTTP status code. Return a JSON object mapping IP address to an object of {status_code: count}, with IP addresses and status codes both sorted ascending.
cmssnl4rm000mg4p2tibvvn2d
contributor_item
Submission BVVN2D
false
def transform(text): import json from urllib.parse import unquote from collections import defaultdict grouped = defaultdict(list) for part in text.split('&'): if not part: continue if '=' in part: k, v = part.split('=', 1) else: k, v = part...
tag=python&tag=data&tag=csv&user=jdoe&active=true&limit=10&note=hello%20world
{ "tag": [ "python", "data", "csv" ], "user": "jdoe", "active": true, "limit": 10, "note": "hello world" }
Parse this URL query string. Percent-decode keys and values (leave literal '+' characters as-is, do not treat them as spaces). If a key appears more than once, collect all its values into a JSON array in order of appearance; otherwise store it as a scalar. Coerce 'true'/'false' to booleans and numeric-looking values to...