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 |
|---|---|---|---|---|---|---|---|
cmsshvp8r00aljmp2chbjfmfq | contributor_item | Submission BJFMFQ | false | import json
def transform(text):
lines = text.strip().split('\n')
headers = lines[0].split('|')
result = []
for line in lines[1:]:
values = line.split('|')
row = dict(zip(headers, values))
row['missing_contact'] = row.get('email', '') == '' or row.get('phone', '') == ''
... | first_name|last_name|email|phone
John|Doe|john.doe@example.com|555-1234
Jane|Smith|jane.smith@example.com|555-5678
Bob|Jones||555-9012
Alice|Brown|alice@example.com| | [
{
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"phone": "555-1234",
"missing_contact": false
},
{
"first_name": "Jane",
"last_name": "Smith",
"email": "jane.smith@example.com",
"phone": "555-5678",
"missing_contact": false
},
{
"first... | Parse the pipe-delimited file. For each row, if either email or phone is missing (empty), mark the row with a 'missing_contact' flag set to true, otherwise false. Return a JSON array of all records with all original fields plus the 'missing_contact' boolean. |
cmsshvp8r00asjmp2iiz3vif3 | contributor_item | Submission Z3VIF3 | false | import json
def grade(avg):
if avg >= 90: return 'A'
if avg >= 80: return 'B'
if avg >= 70: return 'C'
if avg >= 60: return 'D'
return 'F'
def transform(text):
data = json.loads(text.strip())
result = []
for student in data['students']:
scores = list(student['scores'].values())... | {
"students": [
{"name": "Alice", "scores": {"math": 88, "english": 92, "science": 79}},
{"name": "Bob", "scores": {"math": 74, "english": 65, "science": 81}},
{"name": "Carol", "scores": {"math": 95, "english": 90, "science": 93}}
]
} | [
{
"name": "Alice",
"average": 86.3,
"grade": "B"
},
{
"name": "Bob",
"average": 73.3,
"grade": "C"
},
{
"name": "Carol",
"average": 92.7,
"grade": "A"
}
] | For each student, compute their average score (rounded to 1 decimal place) and assign a letter grade: A (>=90), B (>=80), C (>=70), D (>=60), F (<60). Return a JSON array of objects with fields: name, average, grade. |
cmsshvp8r00aajmp27wacace2 | contributor_item | Submission ACACE2 | false | import json
from collections import defaultdict
def transform(text):
data = json.loads(text.strip())
dept_salaries = defaultdict(list)
for emp in data['employees']:
dept_salaries[emp['dept']].append(emp['salary'])
result = {dept: round(sum(salaries) / len(salaries), 2)
for dept, s... | {"employees": [{"name": "Alice", "dept": "Engineering", "salary": 95000}, {"name": "Bob", "dept": "Marketing", "salary": 72000}, {"name": "Carol", "dept": "Engineering", "salary": 105000}, {"name": "Dave", "dept": "Marketing", "salary": 68000}, {"name": "Eve", "dept": "Engineering", "salary": 88000}]} | {
"Engineering": 96000,
"Marketing": 70000
} | Group employees by department, compute the average salary per department (rounded to 2 decimal places), and return a JSON object mapping department name to average salary. |
cmsshvp8r00a9jmp2rk5838co | contributor_item | Submission 5838CO | false | import csv, io, json
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
result = []
for row in reader:
qty = int(row['quantity'])
if qty == 0:
continue
price = float(row['price'])
result.append({
'product_id': int(row['product_id'... | product_id,name,price,quantity
101,Widget A,9.99,5
102,Gadget B,24.50,0
103,Doohickey C,4.75,12
104,Thingamajig D,99.00,0
105,Whatsit E,14.25,3 | [
{
"product_id": 101,
"name": "Widget A",
"price": 9.99,
"quantity": 5,
"total_value": 49.95
},
{
"product_id": 103,
"name": "Doohickey C",
"price": 4.75,
"quantity": 12,
"total_value": 57
},
{
"product_id": 105,
"name": "Whatsit E",
"price": 14.25,
"qu... | Filter out rows where quantity is 0, then compute a 'total_value' column (price * quantity) for remaining rows, and return the result as JSON array of objects with keys: product_id, name, price, quantity, total_value. |
cmsshvp8r00abjmp2rr5t90l5 | contributor_item | Submission 5T90L5 | false | import csv, io
def transform(text):
lines = [l.strip() for l in text.strip().split('\n') if l.strip()]
out = io.StringIO()
writer = csv.writer(out)
writer.writerow(['date', 'amount', 'type', 'running_balance'])
balance = 0.0
for line in lines:
date, amount, txtype = line.split(',')
... | 2024-01-15,150.00,credit
2024-01-17,45.50,debit
2024-01-20,200.00,credit
2024-01-22,30.00,debit
2024-01-25,75.25,debit | "date,amount,type,running_balance\r\n2024-01-15,150.00,credit,150.00\r\n2024-01-17,45.50,debit,104.50\r\n2024-01-20,200.00,credit,304.50\r\n2024-01-22,30.00,debit,274.50\r\n2024-01-25,75.25,debit,199.25" | Parse the ledger entries (date, amount, type). Compute the running balance starting from 0: add credits, subtract debits. Return a CSV with columns: date, amount, type, running_balance. |
cmsshvp8r00aejmp2kny9fzzc | contributor_item | Submission Y9FZZC | false | import csv, io, json
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
result = []
for row in reader:
hs = int(row['home_score'])
as_ = int(row['away_score'])
if hs > as_:
winner = row['home_team']
elif as_ > hs:
winner = row['aw... | home_team,away_team,home_score,away_score
Lakers,Bulls,108,95
Warriors,Celtics,112,110
Heat,Nets,99,102
Suns,Knicks,115,100
Clippers,Bucks,88,97 | [
{
"home_team": "Lakers",
"away_team": "Bulls",
"winner": "Lakers"
},
{
"home_team": "Warriors",
"away_team": "Celtics",
"winner": "Warriors"
},
{
"home_team": "Heat",
"away_team": "Nets",
"winner": "Nets"
},
{
"home_team": "Suns",
"away_team": "Knicks",
"w... | Determine the winner of each game (or 'draw' if scores are equal). Return a JSON array of objects with fields: home_team, away_team, winner. |
cmsshvp8r00acjmp2hfy7r0za | contributor_item | Submission Y7R0ZA | false | import json
def transform(text):
data = json.loads(text.strip())
errors = [{'msg': entry['msg'], 'ts': entry['ts']}
for entry in data['log']
if entry['level'] == 'ERROR']
return json.dumps(errors)
| {
"log": [
{"level": "INFO", "msg": "Server started", "ts": "2024-03-10T09:00:00Z"},
{"level": "WARN", "msg": "High memory", "ts": "2024-03-10T09:05:00Z"},
{"level": "ERROR", "msg": "DB connection failed", "ts": "2024-03-10T09:06:00Z"},
{"level": "INFO", "msg": "Retry succeeded", "ts": "2024-03-10T09:... | [
{
"msg": "DB connection failed",
"ts": "2024-03-10T09:06:00Z"
},
{
"msg": "Timeout on request",
"ts": "2024-03-10T09:10:00Z"
}
] | Extract only ERROR-level log entries and return them as a JSON array, keeping only the 'msg' and 'ts' fields. |
cmsshvp8r00adjmp2zd9waqkx | contributor_item | Submission 9WAQKX | false | import csv, io
def transform(text):
reader = csv.reader(io.StringIO(text.strip()))
rows = list(reader)
headers = rows[0]
data_rows = rows[1:]
out = io.StringIO()
writer = csv.writer(out)
for i, header in enumerate(headers):
writer.writerow([header] + [row[i] for row in data_rows])
... | Alice,Bob,Carol
10,20,30
40,50,60
70,80,90 | "Alice,10,40,70\r\nBob,20,50,80\r\nCarol,30,60,90" | Parse the CSV where the first row is column headers. Transpose the data so rows become columns and columns become rows, preserving the headers as the first column label. Return the transposed data as CSV. |
cmsshvp8r00afjmp2xk6buoh6 | contributor_item | Submission 6BUOH6 | false | import json
from collections import Counter
def transform(text):
words = text.strip().lower().split()
counts = Counter(words)
filtered = {w: c for w, c in counts.items() if c >= 2}
sorted_items = sorted(filtered.items(), key=lambda x: (-x[1], x[0]))
return json.dumps(dict(sorted_items))
| the quick brown fox jumps over the lazy dog the fox was very quick indeed | {
"the": 3,
"fox": 2,
"quick": 2
} | Count word frequencies in the input text (case-insensitive). Return a JSON object sorted by frequency descending, then alphabetically for ties. Only include words with frequency >= 2. |
cmsshvp8r00aijmp2dfnus9if | contributor_item | Submission NUS9IF | false | import re
def transform(text):
lines = [l.strip() for l in text.strip().split('\n') if l.strip()]
result = []
for line in lines:
value = line.split('raw_text: ', 1)[1].strip().strip('"')
cleaned = re.sub(r' +', ' ', value).strip()
result.append(cleaned)
return '\n'.join(result)
| raw_text: " Hello, World! "
raw_text: "python programming "
raw_text: " data science and AI "
raw_text: " strip and normalize " | "Hello, World!\npython programming\ndata science and AI\nstrip and normalize" | For each line, extract the value after 'raw_text: ' (removing surrounding quotes), strip leading/trailing whitespace, collapse internal multiple spaces to a single space, and return one cleaned string per line as plain text. |
cmsshvp8r00ahjmp2x50cngv0 | contributor_item | Submission 0CNGV0 | false | import csv, io, json
from collections import defaultdict
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
city_oldest = {}
for row in reader:
city = row['city']
year = int(row['birth_year'])
name = row['name']
if city not in city_oldest or year < city_... | name,birth_year,city
Alice,1990,Seattle
Bob,1985,Portland
Carol,1992,Seattle
Dave,1988,Portland
Eve,1995,Seattle | {
"Seattle": "Alice",
"Portland": "Bob"
} | For each city, find the oldest person (minimum birth_year) and return a JSON object mapping city to the name of the oldest resident. If there is a tie, return the name that comes first alphabetically. |
cmsshvp8r00agjmp208jyqo9b | contributor_item | Submission JYQO9B | false | import json
from collections import defaultdict
def transform(text):
data = json.loads(text.strip())
groups = defaultdict(int)
for entry in data:
prefix = '.'.join(entry['ip'].split('.')[:2])
groups[prefix] += entry['hits']
sorted_groups = dict(sorted(groups.items(), key=lambda x: -x[1]... | [
{"ip": "192.168.1.1", "hits": 245},
{"ip": "10.0.0.5", "hits": 1},
{"ip": "192.168.1.2", "hits": 89},
{"ip": "172.16.0.1", "hits": 430},
{"ip": "10.0.0.8", "hits": 5},
{"ip": "192.168.1.3", "hits": 12}
] | {
"172.16": 430,
"192.168": 346,
"10.0": 6
} | Group IP addresses by their first two octets (subnet prefix), sum the hits per group, and return a JSON object mapping prefix to total hits, sorted by total hits descending. |
cmsshvp8r00akjmp20825hpci | contributor_item | Submission 25HPCI | false | import csv, io, json
from collections import defaultdict
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
sensor_temps = defaultdict(list)
for row in reader:
sensor_temps[row['sensor_id']].append(float(row['temperature_c']))
result = {}
for sid, temps in sensor_temps.... | sensor_id,timestamp,temperature_c
S1,2024-06-01 08:00,22.5
S1,2024-06-01 09:00,23.1
S1,2024-06-01 10:00,24.8
S2,2024-06-01 08:00,18.0
S2,2024-06-01 09:00,17.5
S2,2024-06-01 10:00,19.2 | {
"S1": {
"min": 22.5,
"max": 24.8,
"avg": 23.47
},
"S2": {
"min": 17.5,
"max": 19.2,
"avg": 18.23
}
} | For each sensor, compute the min, max, and average temperature (rounded to 2 decimal places). Return a JSON object mapping sensor_id to an object with keys: min, max, avg. |
cmsshvp8r00ajjmp28sc1r7t7 | contributor_item | Submission C1R7T7 | false | import json
def transform(text):
data = json.loads(text.strip())
items = set()
for order in data['orders']:
if order['status'] == 'shipped':
items.update(order['items'])
return json.dumps(sorted(items))
| {
"orders": [
{"id": "A1", "items": ["apple", "banana"], "status": "shipped"},
{"id": "A2", "items": ["cherry"], "status": "pending"},
{"id": "A3", "items": ["apple", "cherry", "date"], "status": "shipped"},
{"id": "A4", "items": ["banana", "date"], "status": "cancelled"}
]
} | [
"apple",
"banana",
"cherry",
"date"
] | From shipped orders only, collect all unique items across all such orders, sort them alphabetically, and return a JSON array of those item names. |
cmsshvp8r00amjmp2uhnhozgk | contributor_item | Submission NHOZGK | false | import json
from datetime import date, timedelta
def transform(text):
lines = [l.strip() for l in text.strip().split('\n') if l.strip()]
dates = sorted(date.fromisoformat(d) for d in lines)
ranges = []
start = end = dates[0]
for d in dates[1:]:
if d == end + timedelta(days=1):
e... | 2024-01-03
2024-01-07
2024-01-08
2024-01-09
2024-01-15
2024-01-16
2024-01-17
2024-01-18 | [
{
"start": "2024-01-03",
"end": "2024-01-03"
},
{
"start": "2024-01-07",
"end": "2024-01-09"
},
{
"start": "2024-01-15",
"end": "2024-01-18"
}
] | Given a list of dates (one per line, ISO format), group them into consecutive date ranges. Return a JSON array of objects with 'start' and 'end' keys. Single-day ranges have the same start and end. |
cmsshvp8r00aqjmp2khnqofr0 | contributor_item | Submission NQOFR0 | false | import json
from collections import defaultdict
def transform(text):
data = json.loads(text.strip())
tag_map = defaultdict(list)
for item in data:
for tag in item['tags']:
tag_map[tag].append(item['sku'])
result = {tag: sorted(skus) for tag, skus in sorted(tag_map.items())}
retu... | [
{"sku": "X100", "tags": ["sale", "electronics", "featured"]},
{"sku": "X200", "tags": ["electronics", "new"]},
{"sku": "X300", "tags": ["sale", "clothing"]},
{"sku": "X400", "tags": ["new", "clothing", "featured"]}
] | {
"clothing": [
"X300",
"X400"
],
"electronics": [
"X100",
"X200"
],
"featured": [
"X100",
"X400"
],
"new": [
"X200",
"X400"
],
"sale": [
"X100",
"X300"
]
} | Invert the tag-to-product mapping: return a JSON object where each tag maps to a sorted list of SKUs that have that tag. |
cmsshvp8r00anjmp2ibzzoo6w | contributor_item | Submission ZZOO6W | false | import json
def flatten(obj, prefix=''):
result = {}
for key, val in obj.items():
full_key = f'{prefix}.{key}' if prefix else key
if isinstance(val, dict):
result.update(flatten(val, full_key))
else:
result[full_key] = val
return result
def transform(text):
... | {
"config": {
"database": {"host": "localhost", "port": 5432, "name": "mydb"},
"cache": {"host": "redis", "port": 6379, "ttl": 300},
"app": {"debug": true, "workers": 4}
}
} | {
"database.host": "localhost",
"database.port": 5432,
"database.name": "mydb",
"cache.host": "redis",
"cache.port": 6379,
"cache.ttl": 300,
"app.debug": true,
"app.workers": 4
} | Flatten the nested JSON config into a flat dictionary using dot notation for keys. Return as a JSON object. For example, 'database.host' should map to 'localhost'. |
cmsshvp8r00aojmp2yxobbv4m | contributor_item | Submission OBBV4M | false | import csv, io, json
from collections import defaultdict, OrderedDict
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
user_data = defaultdict(lambda: {'total_duration': 0, 'actions': []})
for row in reader:
uid = int(row['user_id'])
action = row['action']
dur... | user_id,action,duration_seconds
1,login,2
1,view_page,45
1,purchase,120
2,login,3
2,view_page,30
3,login,1
3,view_page,60
3,view_page,90
3,logout,5 | [
{
"user_id": 1,
"total_duration": 167,
"actions": [
"login",
"view_page",
"purchase"
]
},
{
"user_id": 2,
"total_duration": 33,
"actions": [
"login",
"view_page"
]
},
{
"user_id": 3,
"total_duration": 156,
"actions": [
"login",
... | For each user_id, compute the total session duration (sum of all duration_seconds) and list their unique actions in the order they first appear. Return a JSON array of objects with fields: user_id, total_duration, actions. |
cmsshvp8r00apjmp2e4eid7ly | contributor_item | Submission EID7LY | false | import csv, io
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
rows = list(reader)
cols = list(rows[0].keys())
col_vals = {c: [float(r[c]) for r in rows] for c in cols}
col_min = {c: min(col_vals[c]) for c in cols}
col_max = {c: max(col_vals[c]) for c in cols}
out = ... | col_a,col_b,col_c
1,5,9
2,6,10
3,7,11
4,8,12 | "col_a,col_b,col_c\r\n0.0,0.0,0.0\r\n0.3333,0.3333,0.3333\r\n0.6667,0.6667,0.6667\r\n1.0,1.0,1.0" | Normalize each numeric column to the 0-1 range using min-max normalization: (value - min) / (max - min). Round each value to 4 decimal places. Return the result as CSV with the same headers. |
cmsshvp8r00atjmp2nwdbavc4 | contributor_item | Submission DBAVC4 | false | import json
def transform(text):
lines = [l.strip() for l in text.strip().split('\n') if l.strip()]
result = {}
for line in lines:
parts = dict(pair.split('=', 1) for pair in line.split(';'))
raw = parts['value']
val = float(raw)
result[parts['key']] = int(val) if val == int... | key=timeout;value=30;unit=seconds
key=retries;value=3;unit=count
key=threshold;value=0.75;unit=ratio
key=batch_size;value=100;unit=count | {
"timeout": 30,
"retries": 3,
"threshold": 0.75,
"batch_size": 100
} | Parse each semicolon-separated key-value line. Extract the key and value fields and return a single JSON object mapping each key to its numeric value (as int if whole number, float otherwise). |
cmsshvp8r00aujmp2jcs1x7qz | contributor_item | Submission S1X7QZ | false | import json
def transform(text):
nums = [int(x.strip()) for x in text.strip().split(',')]
evens = [n for n in nums if n % 2 == 0]
odds = [n for n in nums if n % 2 != 0]
return json.dumps({
'sum_evens': sum(evens),
'sum_odds': sum(odds),
'count_evens': len(evens),
'count_... | 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 | {
"sum_evens": 110,
"sum_odds": 100,
"count_evens": 10,
"count_odds": 10
} | Parse the comma-separated integers and compute: sum of evens, sum of odds, count of evens, count of odds. Return a JSON object with keys: sum_evens, sum_odds, count_evens, count_odds. |
cmsshvp8r00arjmp29jy7p97b | contributor_item | Submission Y7P97B | false | import json
def transform(text):
lines = [l for l in text.strip().split('\n') if l.strip()]
result = []
for line in lines:
parts = [p.strip() for p in line.split(';')]
result.append({
'name': parts[0],
'email': parts[1],
'department': parts[2].title()
... | Maria Garcia; maria.garcia@corp.com; Engineering
John Lee ; johnlee@corp.com ; Sales
Sam Patel; sam.patel@corp.com; HR
Ana Souza;ana.souza@corp.com;Engineering | [
{
"name": "Maria Garcia",
"email": "maria.garcia@corp.com",
"department": "Engineering"
},
{
"name": "John Lee",
"email": "johnlee@corp.com",
"department": "Sales"
},
{
"name": "Sam Patel",
"email": "sam.patel@corp.com",
"department": "Hr"
},
{
"name": "Ana Souza"... | Parse the semicolon-delimited contact list. Trim whitespace from all fields. Standardize the department field to title case. Return a JSON array of objects with keys: name, email, department. |
cmsshvp8r00avjmp2n7fwuk5h | contributor_item | Submission FWUK5H | false | import json
from datetime import datetime
def transform(text):
data = json.loads(text.strip())
steps = []
for s in data['pipeline']:
start = datetime.fromisoformat(s['start'])
end = datetime.fromisoformat(s['end'])
dur = int((end - start).total_seconds())
steps.append({'step... | {
"pipeline": [
{"step": "ingest", "start": "2024-05-01T08:00:00", "end": "2024-05-01T08:15:30"},
{"step": "validate", "start": "2024-05-01T08:15:30", "end": "2024-05-01T08:18:45"},
{"step": "transform", "start": "2024-05-01T08:18:45", "end": "2024-05-01T09:02:10"},
{"step": "load", "start": "2024-05-... | {
"steps": [
{
"step": "ingest",
"duration_seconds": 930
},
{
"step": "validate",
"duration_seconds": 195
},
{
"step": "transform",
"duration_seconds": 2605
},
{
"step": "load",
"duration_seconds": 470
}
],
"longest_step": "transform"... | For each pipeline step, calculate the duration in whole seconds. Also identify the step with the longest duration. Return a JSON object with 'steps' (array with step name and duration_seconds) and 'longest_step' (the step name). |
cmsshvp8r00axjmp2rigizgj1 | contributor_item | Submission GIZGJ1 | false | import csv, io, json
from collections import defaultdict
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
region_data = defaultdict(list)
for row in reader:
revenue = int(row['revenue'])
expenses = int(row['expenses'])
profit = revenue - expenses
margi... | report_date,region,revenue,expenses
2024-Q1,North,450000,310000
2024-Q1,South,320000,240000
2024-Q2,North,510000,360000
2024-Q2,South,410000,290000
2024-Q3,North,480000,325000
2024-Q3,South,395000,275000 | {
"North": [
{
"quarter": "2024-Q1",
"profit": 140000,
"profit_margin_pct": 31.1
},
{
"quarter": "2024-Q2",
"profit": 150000,
"profit_margin_pct": 29.4
},
{
"quarter": "2024-Q3",
"profit": 155000,
"profit_margin_pct": 32.3
}
],
"South":... | For each region, compute the profit (revenue - expenses) and profit margin percentage (profit / revenue * 100, rounded to 1 decimal) for each quarter. Return a JSON object where each region maps to a list of objects with quarter, profit, and profit_margin_pct. |
cmsshvp8r00awjmp2vvizwr49 | contributor_item | Submission IZWR49 | false | import json
from collections import defaultdict
def transform(text):
fruits = [l.strip() for l in text.strip().split('\n') if l.strip()]
groups = defaultdict(list)
for fruit in fruits:
groups[fruit[0]].append(fruit)
result = {letter: sorted(names) for letter, names in sorted(groups.items())}
... | apple
banana
apricot
avocado
blueberry
cherry
blackberry
cantaloupe | {
"a": [
"apple",
"apricot",
"avocado"
],
"b": [
"banana",
"blackberry",
"blueberry"
],
"c": [
"cantaloupe",
"cherry"
]
} | Group the fruit names by their first letter. Return a JSON object mapping each starting letter to a sorted list of fruit names. Preserve the case as-is. |
cmssi2byc00czjmp2ytmkd90c | contributor_item | Submission MKD90C | false | def transform(text):
text = text.strip()
trailing_dot = text.endswith('.')
if trailing_dot:
text = text[:-1]
sentences = text.split('. ')
reversed_sentences = [' '.join(s.split()[::-1]) for s in sentences]
result = '. '.join(reversed_sentences)
return result + '.' if trailing_dot els... | The quick fox jumps. A lazy dog sleeps. | "jumps fox quick The. sleeps dog lazy A." | Given a block of text with sentences separated by '. ', reverse the order of the words within each sentence but keep sentence order unchanged. Rejoin with '. '. |
cmssi2byc00cxjmp2h6sen9o3 | contributor_item | Submission SEN9O3 | false | def transform(text):
rows = []
for line in text.strip().split('\n'):
parts = line.split('\t')
name = parts[0]
scores = [float(x) for x in parts[1:]]
avg = round(sum(scores) / len(scores), 1)
rows.append((name, avg))
rows.sort(key=lambda r: -r[1])
return '\n'.join(... | Amy 90 85 88
Ben 70 75 80
Cleo 95 92 98 | "Cleo: 95.0\nAmy: 87.7\nBen: 75.0" | Given tab-separated rows (no header) of student_name and 3 test scores, compute each student's average score rounded to 1 decimal, output as 'name: avg' lines sorted by average descending. |
cmssi2byc00d0jmp29y6lhbpk | contributor_item | Submission 6LHBPK | false | import csv, io, json
from collections import Counter
def transform(text):
reader = csv.reader(io.StringIO(text.strip()))
counts = Counter(row[1] for row in reader)
return json.dumps(dict(counts))
| 2026-01-01T10:00,alice,login
2026-01-01T10:05,bob,login
2026-01-01T10:10,alice,click
2026-01-01T10:15,alice,logout | {
"alice": 3,
"bob": 1
} | Parse a simple log of 'timestamp,user,action' CSV rows (no header) and return, as JSON, a mapping of each user to the count of their actions. |
cmssi2byc00d1jmp25w8n1cs2 | contributor_item | Submission 8N1CS2 | false | def transform(text):
nums = sorted(set(int(x.strip()) for x in text.strip().split(',')))
return ','.join(str(n) for n in nums)
| 5, 3, 9, 3, 1, 5, 7, 1 | "1,3,5,7,9" | Given a comma-separated list of numbers, return the numbers sorted in ascending order with duplicates removed, as a comma-separated string. |
cmssi2byc00d2jmp2ac9qljef | contributor_item | Submission 9QLJEF | false | import json
def transform(text):
lines = [l.strip() for l in text.strip().split('\n') if l.strip()]
header = [c.strip() for c in lines[0].strip('|').split('|')]
rows = []
for line in lines[2:]:
cells = [c.strip() for c in line.strip('|').split('|')]
rows.append(dict(zip(header, cells)))... | | Name | Age |
|------|-----|
| Zoe | 22 |
| Max | 31 | | [
{
"Name": "Zoe",
"Age": "22"
},
{
"Name": "Max",
"Age": "31"
}
] | Convert a plain-text table of pipe-delimited rows (first row is header, second row is a separator of dashes) into a JSON array of objects keyed by header. |
cmssi2byc00d3jmp2ro3pzvdv | contributor_item | Submission 3PZVDV | false | import json
from collections import Counter
def transform(text):
counts = Counter()
for line in text.strip().split('\n'):
name = line.strip().rsplit('/', 1)[-1]
if '.' in name:
ext = name.rsplit('.', 1)[-1]
else:
ext = 'none'
counts[ext] += 1
return j... | src/app.py
src/utils.py
README
docs/guide.md
bin/run
src/test.py | {
"py": 3,
"none": 2,
"md": 1
} | Given a list of file paths (one per line), return a JSON object mapping each unique file extension (without dot) to the count of files with that extension. Files with no extension are grouped under 'none'. |
cmssi2byc00d4jmp2e7spc1hy | contributor_item | Submission SPC1HY | false | import json
def transform(text):
result = {}
for part in text.strip().split(';'):
if '=' not in part:
continue
k, v = part.split('=', 1)
result[k.strip()] = v.strip()
return json.dumps(result)
| session_id=abc123; theme = dark ; lang=en | {
"session_id": "abc123",
"theme": "dark",
"lang": "en"
} | Parse a semicolon-separated list of 'name=value' pairs (like a cookie header) into a JSON object, trimming whitespace around names and values. |
cmssi2byc00csjmp2661ifg1c | contributor_item | Submission 1IFG1C | false | import re
def transform(text):
text = text.strip()
match = re.match(r'^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$', text)
h, m, s = (int(g) if g else 0 for g in match.groups())
return str(h * 3600 + m * 60 + s)
| 2h30m15s | 9015 | Convert a duration string like '2h30m15s' (any subset of hours/minutes/seconds) into total seconds as an integer string. |
cmssi2byc00cpjmp259uri4l5 | contributor_item | Submission URI4L5 | false | import json
def transform(text):
result = {}
for line in text.strip().split('\n'):
if ':' not in line:
continue
k, v = line.split(':', 1)
k, v = k.strip(), v.strip()
try:
if '.' in v:
v = float(v)
else:
v = int(... | name: Priya
age: 29
height: 5.6
city: Pune | {
"name": "Priya",
"age": 29,
"height": 5.6,
"city": "Pune"
} | Convert a list of 'key: value' lines (one per line) into a JSON object, casting numeric-looking values to int or float. |
cmssi2byc00cyjmp2m29vxekz | contributor_item | Submission 9VXEKZ | false | import json
def transform(text):
result = []
for line in text.strip().split('\n'):
line = line.strip().lstrip('#')
r, g, b = int(line[0:2], 16), int(line[2:4], 16), int(line[4:6], 16)
result.append([r, g, b])
return json.dumps(result)
| #FF0000
#00FF00
#1A2B3C | [
[
255,
0,
0
],
[
0,
255,
0
],
[
26,
43,
60
]
] | Convert a list of hex color codes (one per line, like #RRGGBB) into their RGB decimal tuples, output as a JSON array of [r,g,b] arrays. |
cmssi2byc00d6jmp2abgo826h | contributor_item | Submission GO826H | false | import math
def transform(text):
tokens = text.strip().split()
stack = []
for tok in tokens:
if tok in ('+', '-', '*', '/'):
b = stack.pop()
a = stack.pop()
if tok == '+':
stack.append(a + b)
elif tok == '-':
stack.appe... | 5 1 2 + 4 * + 3 - | 14 | Given a block of whitespace-separated tokens representing a simple postfix (RPN) arithmetic expression using +, -, *, / on integers, evaluate it and return the integer result as a string (use integer division truncated toward zero). |
cmssi2byc00d7jmp2mohskmfz | contributor_item | Submission HSKMFZ | false | import csv, io, json
from collections import defaultdict
def transform(text):
reader = csv.reader(io.StringIO(text.strip()))
totals = defaultdict(float)
for row in reader:
product, qty, price = row[0], float(row[1]), float(row[2])
totals[product] += qty * price
return json.dumps({k: rou... | Widget,3,9.99
Gadget,1,19.99
Widget,2,9.99 | {
"Widget": 49.95,
"Gadget": 19.99
} | Given rows of 'product,quantity,price' CSV (no header), compute the total revenue (quantity*price) per product, output as JSON object mapping product to total revenue rounded to 2 decimals. |
cmssi2byc00d5jmp2o1z25ymx | contributor_item | Submission Z25YMX | false | def transform(text):
nums = [int(l.strip()) for l in text.strip().split('\n')]
result = []
current_max = None
for n in nums:
current_max = n if current_max is None else max(current_max, n)
result.append(current_max)
return ','.join(str(x) for x in result)
| 3
1
4
1
5
9
2
6 | "3,3,4,4,5,9,9,9" | Given a list of integers one per line, compute the running maximum after each element and output as a comma-separated string. |
cmssi2byc00cvjmp2nm9ryced | contributor_item | Submission 9RYCED | false | def transform(text):
nums = [int(x.strip()) for x in text.strip().split(',')]
if not nums:
return ''
groups = []
current, count = nums[0], 1
for n in nums[1:]:
if n == current:
count += 1
else:
groups.append((current, count))
current, count... | 1,1,1,2,2,3,3,3,3,1 | "3x1 2x2 4x3 1x1" | Given a list of integers separated by commas, return them run-length encoded as pairs like '3xN' joined by spaces (e.g. consecutive equal values are grouped). |
cmssi2byc00cujmp2r3omraky | contributor_item | Submission OMRAKY | false | import json
def transform(text):
data = json.loads(text)
result = {}
def flatten(obj, prefix=''):
if isinstance(obj, dict):
for k, v in obj.items():
flatten(v, f'{prefix}.{k}' if prefix else k)
else:
result[prefix] = obj
flatten(data)
return j... | {"user": {"name": "Sam", "address": {"city": "Delhi", "zip": "110001"}}, "active": true} | {
"user.name": "Sam",
"user.address.city": "Delhi",
"user.address.zip": "110001",
"active": true
} | Convert a nested JSON object into a flattened single-level JSON object using dot notation for nested keys. |
cmssi2byc00cwjmp2bjmjbl3z | contributor_item | Submission MJBL3Z | false | import json
def transform(text):
items = []
for line in text.strip().split('\n'):
line = line.strip()
if line.startswith('- '):
items.append(line[2:].strip())
return json.dumps(items)
| Shopping list:
- Milk
- Eggs
- Bread
Don't forget!
- Butter | [
"Milk",
"Eggs",
"Bread",
"Butter"
] | Parse a simple Markdown unordered list (lines starting with '- ') and return a JSON array of the item strings, ignoring non-list lines. |
cmssi2byc00ctjmp2gw597xo9 | contributor_item | Submission 597XO9 | false | def transform(text):
best_name, best_score = None, None
for line in text.strip().split('\n'):
name, score = line.split(',')
name, score = name.strip(), int(score.strip())
if best_score is None or score > best_score or (score == best_score and name < best_name):
best_name, bes... | Alice,88
Bob,92
Carol,92
Dave,75 | "Bob" | Given a list of (name, score) pairs one per line separated by a comma, return the name with the highest score. On a tie, return the alphabetically first name. |
cmssi2byc00cqjmp278w85sdm | contributor_item | Submission W85SDM | false | import csv, io, json
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"
}
] | Convert a CSV string with a header row into a JSON array of objects, one per data row. |
cmssi2byc00crjmp2sm4lzkba | contributor_item | Submission 4LZKBA | false | import re
from collections import Counter
def transform(text):
words = re.findall(r"[a-zA-Z']+", text.lower())
counts = Counter(words)
top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
return ','.join(f'{w}:{c}' for w, c in top)
| The cat sat on the mat. The cat ran. A dog watched the cat run. | "the:4,cat:3,a:1" | Given a block of text, return the top 3 most frequent words (lowercased, punctuation stripped) as a comma-separated 'word:count' list, ordered by count desc then alphabetically. |
cmssik3t000i8jmp28z7ynfvt | contributor_item | Submission 7YNFVT | false | import re
from datetime import datetime, timezone
def transform(input):
def repl(m):
ts = int(m.group(0))
return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
return re.sub(r"\b1\d{9}\b", repl, input)
| Event started at 1704067200 and ended at 1704070800.
Next checkpoint scheduled for 1704074400.
| "Event started at 2024-01-01T00:00:00Z and ended at 2024-01-01T01:00:00Z.\nNext checkpoint scheduled for 2024-01-01T02:00:00Z.\n" | Find all 10-digit Unix timestamps embedded in free text and replace them in-place with their UTC ISO 8601 representation ('YYYY-MM-DDTHH:MM:SSZ'). |
cmssik3t000iejmp22sksc5xx | contributor_item | Submission KSC5XX | false | import re
def transform(input):
def repl(m):
digits = m.group(0)
return "*" * (len(digits) - 4) + digits[-4:]
return re.sub(r"\d{10,}", repl, input)
| Card number 4111222233334444 was charged. Reference ID 998877665544 issued. Short code 12345 unaffected.
| "Card number ************4444 was charged. Reference ID ********5544 issued. Short code 12345 unaffected.\n" | Redact digit runs of length 10 or more in text, masking all but the last 4 digits with asterisks, leaving everything else (including shorter digit runs) unchanged. |
cmssik3t000icjmp2ttz67m66 | contributor_item | Submission Z67M66 | false | def transform(input):
lines = [l for l in input.strip().split("\n") if l.strip()]
out_lines = []
for line in lines:
cols = [c.strip() for c in line.split("|")]
out_lines.append("\t".join(cols))
return "\n".join(out_lines)
| Name|Role|Salary
Alice|Engineer|90000
Bob|Designer|80000
| "Name\tRole\tSalary\nAlice\tEngineer\t90000\nBob\tDesigner\t80000" | Convert a pipe ('|') delimited text block (header + rows) into a tab-separated (TSV) text block. |
cmssik3t000idjmp2xdmcfwxn | contributor_item | Submission MCFWXN | false | import json, re
from collections import Counter
def transform(input):
words = re.findall(r"[a-zA-Z']+", input.lower())
counts = Counter(words)
sorted_counts = dict(sorted(counts.items(), key=lambda x: (-x[1], x[0])))
return json.dumps(sorted_counts)
| The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs away quickly. | {
"the": 4,
"dog": 2,
"fox": 2,
"and": 1,
"away": 1,
"barks": 1,
"brown": 1,
"jumps": 1,
"lazy": 1,
"over": 1,
"quick": 1,
"quickly": 1,
"runs": 1
} | Compute a word-frequency histogram of a text block (case-insensitive, alphabetic words only) and return it as a JSON object sorted by descending frequency then alphabetically. |
cmssik3t000i9jmp2rrvlud4p | contributor_item | Submission VLUD4P | false | import json
def transform(input):
out = []
for line in input.strip().split("\n"):
line = line.strip()
if line.startswith("- [ ]") or line.startswith("- [x]") or line.startswith("- [X]"):
done = line[3] in ("x", "X")
task = line[6:].strip()
out.append({"task":... | - [x] Write project proposal
- [ ] Review budget estimates
- [x] Send invites
- [ ] Finalize venue
| [
{
"task": "Write project proposal",
"done": true
},
{
"task": "Review budget estimates",
"done": false
},
{
"task": "Send invites",
"done": true
},
{
"task": "Finalize venue",
"done": false
}
] | Parse a Markdown checkbox task list ('- [ ] task' / '- [x] done') into a JSON array of objects with 'task' and 'done' (boolean) fields. |
cmssik3t000ibjmp2a8pe4pk4 | contributor_item | Submission PE4PK4 | false | import json, re
def transform(input):
matches = re.findall(r'"([^"]*)"', input)
return json.dumps(matches)
| She said "hello there" and then asked "how are you doing?" before leaving with a quick "goodbye". | [
"hello there",
"how are you doing?",
"goodbye"
] | Extract all double-quoted substrings from a block of free text into a JSON array of strings, in order of appearance. |
cmssik3t000iajmp2cvofv4v2 | contributor_item | Submission OFV4V2 | false | import json
def to_camel(key):
parts = key.split("_")
return parts[0] + "".join(p.capitalize() for p in parts[1:])
def convert(obj):
if isinstance(obj, dict):
return {to_camel(k): convert(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [convert(v) for v in obj]
else:... | {"user_id": 1, "first_name": "Alice", "contact_info": {"email_address": "a@x.com", "phone_number": "555-1000"}, "order_items": [{"item_id": 5, "unit_price": 9.99}]} | {
"userId": 1,
"firstName": "Alice",
"contactInfo": {
"emailAddress": "a@x.com",
"phoneNumber": "555-1000"
},
"orderItems": [
{
"itemId": 5,
"unitPrice": 9.99
}
]
} | Recursively convert all snake_case keys in a nested JSON object (including within lists) into camelCase keys, preserving values and structure. |
cmssik3t000i0jmp2ugzv62kr | contributor_item | Submission ZV62KR | false | import json, re
def transform(input):
lines = [l.strip() for l in input.strip().split("\n") if l.strip()]
results = []
for line in lines:
digits = re.sub(r"\D", "", line)
if len(digits) == 10:
digits = "1" + digits
results.append("+" + digits)
return json.dumps(resul... | (415) 555-0132
415.555.0198
+1 415-555-0173
1-415-555-0111
| [
"+14155550132",
"+14155550198",
"+14155550173",
"+14155550111"
] | Normalize varied US phone number formats (parentheses, dots, dashes, with or without country code) into a JSON array of E.164-like strings ('+1' followed by 10 digits). |
cmssik3t000i5jmp2ose1fpc8 | contributor_item | Submission E1FPC8 | false | import json
def transform(input):
result = {}
for line in input.strip().split("\n"):
if ":" in line:
k, v = line.split(":", 1)
result[k.strip()] = v.strip()
return json.dumps(result)
| From: alice@example.com
To: bob@example.com
Subject: Quarterly Report
Date: Mon, 10 Aug 2026 09:00:00 -0000
X-Priority: 1
| {
"From": "alice@example.com",
"To": "bob@example.com",
"Subject": "Quarterly Report",
"Date": "Mon, 10 Aug 2026 09:00:00 -0000",
"X-Priority": "1"
} | Extract 'Key: Value' pairs from an email-header-style text block into a flat JSON object. |
cmssik3t000hzjmp2je9by3qh | contributor_item | Submission 9BY3QH | false | import re
def transform(input):
total = 0.0
for line in input.splitlines():
m = re.search(r"\$([0-9,]+\.\d{2})", line)
if m:
total += float(m.group(1).replace(",", ""))
return f"{total:.2f}"
| Item: Widget A x2 ......... $19.99
Item: Widget B x1 ......... $1,250.00
Shipping fee .............. $15.50
Item: Widget C x5 ......... $99.95
| 1385.44 | Extract all dollar amounts (formatted like $1,234.56) from semi-structured invoice line text and return their sum formatted to 2 decimal places as a string. |
cmssik3sz00hvjmp2zfuf6f0w | contributor_item | Submission UF6F0W | false | import json
def transform(input):
data = json.loads(input)
out = {}
def flat(obj, prefix=""):
if isinstance(obj, dict):
for k, v in obj.items():
flat(v, f"{prefix}{k}.")
elif isinstance(obj, list):
for i, v in enumerate(obj):
flat(v, f... | {"user": {"name": "Alice", "address": {"city": "Boston", "zip": "02110"}}, "tags": ["admin", "beta"], "active": true} | {
"user.name": "Alice",
"user.address.city": "Boston",
"user.address.zip": "02110",
"tags.0": "admin",
"tags.1": "beta",
"active": true
} | Flatten a nested JSON object into a single-level dict with dotted-path keys (e.g. 'user.address.city'), including array indices as path segments (e.g. 'tags.0'). |
cmssik3t000hxjmp2z71t7wer | contributor_item | Submission 1T7WER | false | import csv, io
def transform(input):
reader = csv.DictReader(io.StringIO(input.strip()))
fieldnames = reader.fieldnames
rows = list(reader)
dedup = {}
for row in rows:
dedup[row["id"]] = row
out = io.StringIO()
writer = csv.DictWriter(out, fieldnames=fieldnames, lineterminator="\n")... | id,name,score
1,Alice,10
2,Bob,20
1,Alice,15
3,Carol,30
2,Bob,25
| "id,name,score\n1,Alice,15\n2,Bob,25\n3,Carol,30" | Deduplicate CSV rows by the 'id' column, keeping only the last occurrence of each id, and return the deduplicated CSV (header + rows) as a string. |
cmssik3t000i1jmp2a99dr0tq | contributor_item | Submission 9DR0TQ | false | import json
def transform(input):
lines = [l for l in input.split("\n") if l.strip()]
header = lines[0]
import re
cols = re.findall(r"\S+(?:\s\S+)*", header)
bounds = []
idx = 0
for c in cols:
start = header.index(c, idx)
bounds.append(start)
idx = start + len(c)
... | NAME AGE CITY
Alice 30 Boston
Bob 25 Denver
Carol 41 Reno
| [
{
"NAME": "Alice",
"AGE": "30",
"CITY": "Boston"
},
{
"NAME": "Bob",
"AGE": "25",
"CITY": "Denver"
},
{
"NAME": "Carol",
"AGE": "41",
"CITY": "Reno"
}
] | Convert a fixed-width text table (columns aligned by whitespace, header row defines column names and positions) into a JSON array of record objects. |
cmssik3t000i3jmp2nk5t0i75 | contributor_item | Submission 5T0I75 | false | import json, re
def transform(input):
records = []
for line in input.strip().split("\n"):
if not line.strip():
continue
pairs = re.findall(r'(\w+)=("[^"]*"|\S+)', line)
rec = {}
for k, v in pairs:
if v.startswith('"') and v.endswith('"'):
... | level=INFO msg="User logged in" user=alice ip=10.0.0.5
level=ERROR msg="Connection failed" user=bob ip=10.0.0.9
level=WARN msg="Low disk space" user=system ip=10.0.0.1
| [
{
"level": "INFO",
"msg": "User logged in",
"user": "alice",
"ip": "10.0.0.5"
},
{
"level": "ERROR",
"msg": "Connection failed",
"user": "bob",
"ip": "10.0.0.9"
},
{
"level": "WARN",
"msg": "Low disk space",
"user": "system",
"ip": "10.0.0.1"
}
] | Parse log lines containing space-separated key=value pairs (values may be double-quoted with embedded spaces) into a JSON array of objects. |
cmssik3sz00hwjmp2oexlgscc | contributor_item | Submission XLGSCC | false | import json
def transform(input):
records = json.loads(input)
out = {}
for rec in records:
out[rec["key"]] = rec["value"]
return json.dumps(out)
| [{"key": "width", "value": 100}, {"key": "height", "value": 200}, {"key": "color", "value": "red"}] | {
"width": 100,
"height": 200,
"color": "red"
} | Pivot a JSON array of {"key":..., "value":...} records into a single flat JSON object mapping each key to its value. |
cmssik3t000hyjmp2g6vnssvx | contributor_item | Submission VNSSVX | false | import json
def transform(input):
result = {}
current = None
for line in input.splitlines():
line = line.strip()
if not line or line.startswith(";") or line.startswith("#"):
continue
if line.startswith("[") and line.endswith("]"):
current = line[1:-1]
... | [server]
host = 0.0.0.0
port = 8080
[database]
name = prod_db
user = admin
; comment line
timeout = 30
| {
"server": {
"host": "0.0.0.0",
"port": "8080"
},
"database": {
"name": "prod_db",
"user": "admin",
"timeout": "30"
}
} | Parse INI-style config text (sections in [brackets], key = value lines, ';' or '#' comments) into nested JSON keyed by section name. |
cmssik3t000i2jmp2h6u2h7wv | contributor_item | Submission U2H7WV | false | import json
from urllib.parse import parse_qs
def transform(input):
parsed = parse_qs(input.strip())
return json.dumps(parsed)
| color=red&color=blue&size=M&tag=a&tag=b&tag=c | {
"color": [
"red",
"blue"
],
"size": [
"M"
],
"tag": [
"a",
"b",
"c"
]
} | Parse a URL query string, merging duplicate keys into arrays of their values, and return as a JSON object (using urllib.parse.parse_qs semantics). |
cmssik3t000i4jmp2pbxfjdvw | contributor_item | Submission XFJDVW | false | import json
def transform(input):
lines = [l for l in input.split("\n") if l.strip()]
root = {}
stack = [(-1, root)]
for line in lines:
stripped = line.lstrip(" ")
indent = len(line) - len(stripped)
key, _, val = stripped.partition(":")
key = key.strip()
val = va... | server:
host: localhost
port: 8080
database:
name: mydb
credentials:
user: admin
password: secret
logging:
level: debug
| {
"server": {
"host": "localhost",
"port": "8080"
},
"database": {
"name": "mydb",
"credentials": {
"user": "admin",
"password": "secret"
}
},
"logging": {
"level": "debug"
}
} | Parse a simple YAML-like indented text block (2-space indentation, 'key:' for nested mappings, 'key: value' for scalars) into nested JSON. |
cmssik3t000i6jmp2pkft21yg | contributor_item | Submission FT21YG | false | import csv, io, json
def transform(input):
reader = csv.DictReader(io.StringIO(input.strip()))
out = []
for row in reader:
tags = [t.strip() for t in row["tags"].split(";") if t.strip()]
for tag in tags:
new_row = dict(row)
new_row["tags"] = tag
out.appen... | id,name,tags
1,Alice,admin;beta;tester
2,Bob,viewer
3,Carol,admin;viewer
| [
{
"id": "1",
"name": "Alice",
"tags": "admin"
},
{
"id": "1",
"name": "Alice",
"tags": "beta"
},
{
"id": "1",
"name": "Alice",
"tags": "tester"
},
{
"id": "2",
"name": "Bob",
"tags": "viewer"
},
{
"id": "3",
"name": "Carol",
"tags": "admin"... | Given CSV rows with a semicolon-separated 'tags' column, explode each row into one row per tag, duplicating the other column values, and return as a JSON array of objects. |
cmssik3t000i7jmp2vl7qeg92 | contributor_item | Submission 7QEG92 | false | def transform(input):
lines = [l for l in input.strip().split("\n") if l.strip()]
total = 0.0
out_lines = []
for line in lines:
parts = line.split(",")
amount = float(parts[-1])
total += amount
out_lines.append(line + "," + f"{total:.2f}")
return "\n".join(out_lines)
| 2026-01-01,Deposit,100.00
2026-01-02,Deposit,50.00
2026-01-03,Withdrawal,-30.00
2026-01-04,Deposit,20.00
| "2026-01-01,Deposit,100.00,100.00\n2026-01-02,Deposit,50.00,150.00\n2026-01-03,Withdrawal,-30.00,120.00\n2026-01-04,Deposit,20.00,140.00" | Given CSV-like lines of 'date,description,amount', append a running cumulative total column to each line based on the amount field, returning the updated lines joined by newlines. |
cmssila2x00jyjmp2cxk195uv | contributor_item | Submission K195UV | false | import json
def transform(text):
data = json.loads(text)
out = {}
def rec(prefix, obj):
if isinstance(obj, dict):
for k, v in obj.items():
rec(f"{prefix}.{k}" if prefix else k, v)
else:
out[prefix] = obj
rec("", data)
return json.dumps(out, so... | {"user": {"name": "Maria", "address": {"city": "Lima", "zip": "15001"}}, "active": true} | {
"active": true,
"user.address.city": "Lima",
"user.address.zip": "15001",
"user.name": "Maria"
} | Flatten a nested JSON object into a single-level JSON object whose keys are dot-separated paths to each leaf value (e.g. 'user.address.city'). Keys in the output must be sorted alphabetically. |
cmssila2x00jzjmp2tl4ua1q5 | contributor_item | Submission 4UA1Q5 | false | import csv, io, json
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
rows = []
for r in reader:
rows.append({
"id": int(r["id"]),
"name": r["name"],
"price": float(r["price"]),
"in_stock": r["in_stock"].strip().lower() == "true... | id,name,price,in_stock
1,Widget,9.99,true
2,Gadget,19.5,false
| [
{
"id": 1,
"name": "Widget",
"price": 9.99,
"in_stock": true
},
{
"id": 2,
"name": "Gadget",
"price": 19.5,
"in_stock": false
}
] | Parse a CSV table with header row into a JSON array of objects, coercing 'id' to an integer, 'price' to a float, and 'in_stock' to a boolean (case-insensitive 'true'/'false'), leaving 'name' as a string. |
cmssila2x00k1jmp2o5zz92v5 | contributor_item | Submission ZZ92V5 | false | import json
def transform(text):
data = json.loads(text)
totals = {}
for rec in data:
totals[rec["category"]] = totals.get(rec["category"], 0) + rec["amount"]
totals = {k: round(v, 2) for k, v in sorted(totals.items())}
return json.dumps(totals)
| [{"category": "Books", "amount": 12.5}, {"category": "Electronics", "amount": 99.99}, {"category": "Books", "amount": 7.25}, {"category": "Electronics", "amount": 20.0}, {"category": "Toys", "amount": 15.0}] | {
"Books": 19.75,
"Electronics": 119.99,
"Toys": 15
} | Given a JSON array of sale records each with 'category' and 'amount', sum the amounts per category (rounded to 2 decimal places), and return a single JSON object mapping category name to total, with keys sorted alphabetically. |
cmssila2x00k0jmp2ni39aq9m | contributor_item | Submission 39AQ9M | false | import re, json
def transform(text):
lines = text.strip().split("\n")[1:]
seen = []
for line in lines:
digits = re.sub(r"\D", "", line)
if digits.startswith("1") and len(digits) == 11:
digits = digits[1:]
if len(digits) != 10:
continue
norm = "+1" + d... | Contacts:
(415) 555-0132
415-555-0198
+1 415 555 0132
555.0177
| [
"+14155550132",
"+14155550198"
] | From a text listing of US phone numbers (first line is a 'Contacts:' header to skip), extract only valid 10-digit US numbers (with or without a leading '1' country code), normalize each to '+1XXXXXXXXXX' format, drop any line that doesn't yield exactly 10 digits, remove duplicates while preserving first-seen order, and... |
cmssis6l200nxjmp2aqr19140 | contributor_item | Submission R19140 | false | def transform(input):
emails = [e.strip() for e in input.strip().split('\n') if e.strip()]
domains = sorted(set(e.split('@')[1] for e in emails))
return '\n'.join(domains)
| alice@example.com
bob@gmail.com
carol@example.com
dave@yahoo.com | "example.com\ngmail.com\nyahoo.com" | Extract unique email domains, sort them alphabetically, and return them one per line. |
cmssis6l200nyjmp24qxkirq5 | contributor_item | Submission XKIRQ5 | false | def transform(input):
total = sum(int(line.split(':')[1]) for line in input.strip().split('\n'))
return str(total)
| product_a:150
product_b:200
product_c:75
product_d:125 | 550 | Sum the numeric values from colon-separated key:value pairs and return the total as a string. |
cmssis6l200nvjmp2djusjh4r | contributor_item | Submission USJH4R | false | import json, urllib.parse
def transform(input):
parsed = urllib.parse.parse_qs(input.strip())
result = {k: v[0] if len(v) == 1 else v for k, v in parsed.items()}
return json.dumps(result)
| name=Alice&age=30&city=New+York&role=Developer | {
"name": "Alice",
"age": "30",
"city": "New York",
"role": "Developer"
} | Parse a URL query string into a JSON object, decoding URL-encoded characters. |
cmssis6l200nwjmp25dbpmual | contributor_item | Submission BPMUAL | false | def transform(input):
return ','.join(w.strip().title() for w in input.split(','))
| apple,banana,cherry,date | "Apple,Banana,Cherry,Date" | Title-case each word in a comma-separated list and return the result as a comma-separated string. |
cmssis6l200nzjmp2xb3elovz | contributor_item | Submission 3ELOVZ | false | import csv, json, io
def transform(input):
reader = csv.DictReader(io.StringIO(input.strip()))
return json.dumps(list(reader))
| name,age,city
Alice,30,Paris
Bob,25,London
| [
{
"name": "Alice",
"age": "30",
"city": "Paris"
},
{
"name": "Bob",
"age": "25",
"city": "London"
}
] | Convert CSV input into a JSON array of objects using the first row as headers. |
cmssitudq00orjmp2u55coz38 | contributor_item | Submission 5COZ38 | false | def transform(text):
s = text.strip()
if not s:
return ""
parts = []
count = 1
prev = s[0]
for ch in s[1:]:
if ch == prev:
count += 1
else:
parts.append(f"{prev}{count}")
prev = ch
count = 1
parts.append(f"{prev}{count}"... | aaabbbccccd | "a3b3c4d1" | Run-length encode a string of repeated characters into '<char><count>' pairs concatenated together. |
cmssitudq00osjmp2rjgxci81 | contributor_item | Submission GXCI81 | false | import json, csv, io
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()), delimiter="\t")
rows = []
for row in reader:
converted = {}
for k, v in row.items():
try:
converted[k] = int(v)
except ValueError:
try:
... | name score note
Alice 95 Top, great
Bob 88.5 Good | [
{
"name": "Alice",
"score": 95,
"note": "Top, great"
},
{
"name": "Bob",
"score": 88.5,
"note": "Good"
}
] | Parse tab-separated values with a header row into a JSON array of objects, coercing numeric-looking fields to int or float. |
cmssitudq00otjmp230ti933g | contributor_item | Submission TI933G | false | import json
def transform(text):
ranges = []
for part in text.strip().split(","):
a, b = part.strip().split("-")
ranges.append((int(a), int(b)))
ranges.sort()
merged = [ranges[0]]
for start, end in ranges[1:]:
last_start, last_end = merged[-1]
if start <= last_end + ... | 1-3, 5-7, 2-4, 10-10, 8-9 | [
"1-10"
] | Parse a comma-separated list of 'start-end' integer ranges, merge overlapping or adjacent ranges, and return the merged ranges as a JSON array of 'start-end' strings. |
cmssjmldn00sqjmp2txyulq2t | contributor_item | Submission YULQ2T | false | import csv,io,json
def transform(text):
groups={}
for r in csv.DictReader(io.StringIO(text)): groups.setdefault(r["sensor"],[]).append(float(r["value"]))
out={k:{"min":min(v),"max":max(v),"mean":round(sum(v)/len(v),2)} for k,v in sorted(groups.items())}
return json.dumps(out) | sensor,value
s2,9
s1,3
s2,15
s1,7
s1,8 | {
"s1": {
"min": 3,
"max": 8,
"mean": 6
},
"s2": {
"min": 9,
"max": 15,
"mean": 12
}
} | Convert CSV sensor readings into JSON containing each sensor's minimum, maximum, and rounded mean, sorted by sensor id. |
cmssjmldn00spjmp23ft6fco9 | contributor_item | Submission T6FCO9 | false | import json
def transform(text):
totals={}
for line in text.splitlines():
r=json.loads(line); totals[r["account"]]=totals.get(r["account"],0)+r["amount"]
return json.dumps(dict(sorted(totals.items()))) | {"account":"a","amount":12.5}
{"account":"b","amount":4}
{"account":"a","amount":-2.25} | {
"a": 10.25,
"b": 4
} | Parse newline-delimited JSON events, sum numeric 'amount' values by 'account', and return a key-sorted JSON object. |
cmssjmldn00ssjmp26f70515i | contributor_item | Submission 70515I | false | import csv,io,json
def transform(text):
rows=[]
for r in csv.DictReader(io.StringIO(text),delimiter=';'):
q=int(r['quantity'])
if q: rows.append({'sku':r['sku'],'quantity':q,'price':float(r['price'])})
return json.dumps(rows) | sku;quantity;price
A1;3;4.50
B2;0;9.99
C3;7;1.25 | [
{
"sku": "A1",
"quantity": 3,
"price": 4.5
},
{
"sku": "C3",
"quantity": 7,
"price": 1.25
}
] | Convert a semicolon-delimited inventory table to JSON, coercing quantity to int and price to float, while dropping rows with zero quantity. |
cmssjmldo00sujmp2vgmn6pph | contributor_item | Submission MN6PPH | false | def transform(text):
ranges=sorted(tuple(map(int,l.split('-'))) for l in text.splitlines() if l.strip())
out=[]
for a,b in ranges:
if out and a<=out[-1][1]+1: out[-1]=(out[-1][0],max(out[-1][1],b))
else: out.append((a,b))
return '\n'.join(f'{a}-{b}' for a,b in out) | 8-10
1-3
4-6
12-15
10-12 | "1-6\n8-15" | Parse integer ranges, merge overlapping or adjacent ranges, and output one normalized 'start-end' range per line. |
cmssjmldn00stjmp272246a7u | contributor_item | Submission 246A7U | false | import re
def transform(text):
out=[]
for line in text.splitlines():
tag=re.sub(r'\s+','-',line.strip().lower())
if tag and tag not in out: out.append(tag)
return ','.join(out) | Data Science
API
data science
Release Candidate
api | "data-science,api,release-candidate" | Normalize mixed newline-separated tags by trimming, lowercasing, replacing internal whitespace with hyphens, and returning unique tags in first-seen order. |
cmssjmldo00svjmp2i0a5jn5w | contributor_item | Submission A5JN5W | false | import json
def transform(text):
graph=json.loads(text); edges={f'{a}->{b}' for a,targets in graph.items() for b in targets}
return json.dumps(sorted(edges)) | {"a":["c","b","c"],"b":["c"],"c":[]} | [
"a->b",
"a->c",
"b->c"
] | Convert a JSON adjacency map into a sorted edge list of 'source->target' strings, removing duplicate edges. |
cmssjmldo00swjmp2txnuklud | contributor_item | Submission NUKLUD | false | import re,json
def transform(text):
out=[]
for line in text.splitlines():
pairs=re.findall(r'(\w+)=("[^"]*"|\S+)',line); r={k:v.strip('"') for k,v in pairs}
if r.get('level')=='ERROR': r['code']=int(r['code']); out.append(r)
return json.dumps(out) | level=INFO msg="ready now" code=0
level=ERROR msg="disk full" code=28
level=ERROR msg="bad token" code=41 | [
{
"level": "ERROR",
"msg": "disk full",
"code": 28
},
{
"level": "ERROR",
"msg": "bad token",
"code": 41
}
] | Parse key=value log lines with quoted values and return a JSON array containing only ERROR records. |
cmssjmldo00syjmp2mjj1yysa | contributor_item | Submission J1YYSA | false | import re
from datetime import datetime,timezone
def transform(text):
return re.sub(r'(?<!\w)\d{10}(?!\w)',lambda m:datetime.fromtimestamp(int(m.group()),timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),text) | started=1704067200; retry at 1704070800; id1704074400 stays | "started=2024-01-01T00:00:00Z; retry at 2024-01-01T01:00:00Z; id1704074400 stays" | Replace every standalone 10-digit Unix timestamp in free text with a UTC ISO-8601 timestamp. |
cmssjmldo00szjmp2yr64jmn6 | contributor_item | Submission 64JMN6 | false | import json,re
def transform(text):
done=[]; todo=[]
for l in text.splitlines():
m=re.match(r'- \[([ xX])\] (.+)',l)
if m: (done if m.group(1).lower()=='x' else todo).append(m.group(2))
return json.dumps({'complete':len(done),'incomplete':len(todo),'remaining':todo}) | - [x] compile report
- [ ] send review
- [X] archive data
- [ ] close ticket | {
"complete": 2,
"incomplete": 2,
"remaining": [
"send review",
"close ticket"
]
} | Parse a Markdown checklist and return JSON totals for complete and incomplete tasks plus incomplete task text. |
cmssjmldo00t0jmp27rrv8seh | contributor_item | Submission RV8SEH | false | import json,re
def transform(text):
lines=text.splitlines(); starts=[m.start() for m in re.finditer(r'\S+',lines[0])]; names=[lines[0][s:(starts[i+1] if i+1<len(starts) else None)].strip() for i,s in enumerate(starts)]
out=[]
for l in lines[1:]:
vals=[l[s:(starts[i+1] if i+1<len(starts) else None)].... | NAME AGE SCORE
Ana 31 88.5
Benjamin 27 91.0 | [
{
"NAME": "Ana",
"AGE": 31,
"SCORE": 88.5
},
{
"NAME": "Benjamin",
"AGE": 27,
"SCORE": 91
}
] | Convert a fixed-width employee table to JSON using the header's column start positions and coerce age and score to numbers. |
cmssjmldo00sxjmp2vb4ri31c | contributor_item | Submission 4RI31C | false | import csv,io,json
def transform(text):
out={}
for r in csv.DictReader(io.StringIO(text)):
q=out.setdefault(r['region'],{}); q[r['quarter']]=q.get(r['quarter'],0)+int(r['revenue'])
return json.dumps({k:dict(sorted(v.items())) for k,v in sorted(out.items())}) | region,quarter,revenue
west,Q1,10
east,Q1,8
west,Q2,12
west,Q1,3 | {
"east": {
"Q1": 8
},
"west": {
"Q1": 13,
"Q2": 12
}
} | Pivot CSV rows of region,quarter,revenue into a nested JSON object keyed by region then quarter, summing duplicates. |
cmssjmldo00t4jmp24rvzdpah | contributor_item | Submission VZDPAH | false | import re,json
def transform(text):
out=[]
for raw in re.findall(r'(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d)',text):
if all(int(x)<=255 for x in raw.split('.')) and raw not in out: out.append(raw)
return json.dumps(out) | seen 10.0.0.1 then 999.1.1.1; repeat 10.0.0.1 and 172.16.4.8. | [
"10.0.0.1",
"172.16.4.8"
] | Extract valid IPv4 addresses from text, reject octets above 255, and return unique addresses in first-seen order. |
cmssjmldo00t2jmp2s422vdg5 | contributor_item | Submission 22VDG5 | false | import json
def transform(text):
root={}
for line in text.splitlines():
path,raw=line.split('=',1); value=True if raw=='true' else False if raw=='false' else int(raw) if raw.lstrip('-').isdigit() else raw
cur=root
parts=path.split('.')
for p in parts[:-1]: cur=cur.setdefault(p,{}... | server.port=8080
server.debug=true
database.pool.size=12
name=demo | {
"server": {
"port": 8080,
"debug": true
},
"database": {
"pool": {
"size": 12
}
},
"name": "demo"
} | Convert path=value lines into nested JSON dictionaries using dot-separated path segments, coercing true/false and integers. |
cmssjmldo00t3jmp26l5qxsn0 | contributor_item | Submission 5QXSN0 | false | import csv,io,json
def transform(text):
balances={}; out=[]
for r in csv.DictReader(io.StringIO(text)):
a=r['account']; balances[a]=balances.get(a,0)+int(r['delta']); out.append({'account':a,'delta':int(r['delta']),'balance':balances[a]})
return json.dumps(out) | account,delta
a,10
b,5
a,-3
b,8
a,2 | [
{
"account": "a",
"delta": 10,
"balance": 10
},
{
"account": "b",
"delta": 5,
"balance": 5
},
{
"account": "a",
"delta": -3,
"balance": 7
},
{
"account": "b",
"delta": 8,
"balance": 13
},
{
"account": "a",
"delta": 2,
"balance": 9
}
] | Read CSV transactions and append a running balance per account while preserving input order, returning JSON. |
cmssjmldo00t5jmp28d025wlj | contributor_item | Submission 025WLJ | false | import csv,io,json
def transform(text):
rows=list(csv.DictReader(io.StringIO(text),delimiter='|')); failed=[r['id'] for r in rows if r['status']!='PASS']
return json.dumps({'pass_rate':round((len(rows)-len(failed))/len(rows),2),'failed':failed}) | id|status
b1|PASS
b2|FAIL
b3|PASS
b4|FAIL
b5|PASS | {
"pass_rate": 0.6000000000000001,
"failed": [
"b2",
"b4"
]
} | Parse pipe-delimited build results and return a JSON object giving pass rate and failed build ids. |
cmssjmldo00t7jmp2ti6wx8mm | contributor_item | Submission 6WX8MM | false | def transform(text):
out=[]
for line in text.splitlines():
n=int(line); value=float(abs(n)); unit='B'
for u in ['B','KiB','MiB','GiB']:
unit=u
if value<1024 or u=='GiB': break
value/=1024
if n<0:value=-value
out.append(f'{value:.1f} {unit}')
... | 0
1024
1536
-1048576
1073741824 | "0.0 B\n1.0 KiB\n1.5 KiB\n-1.0 MiB\n1.0 GiB" | Convert newline-separated signed byte counts into human-readable IEC units with one decimal place. |
cmssjmldo00t6jmp2pb0rwg0s | contributor_item | Submission 0RWG0S | false | import json
def transform(text):
root={}; stack=[(-1,root)]
for line in text.splitlines():
depth=(len(line)-len(line.lstrip()))//2; name=line.strip(); node={}
while stack[-1][0]>=depth: stack.pop()
stack[-1][1][name]=node; stack.append((depth,node))
return json.dumps(root) | hardware
cpu
storage
ssd
software
os | {
"hardware": {
"cpu": {},
"storage": {
"ssd": {}
}
},
"software": {
"os": {}
}
} | Convert an indented category list into nested JSON where two-space indentation establishes parent-child relationships. |
cmssjmldo00t8jmp2gnuz9u90 | contributor_item | Submission UZ9U90 | false | import json
def transform(text):
out={}
for r in json.loads(text):
d=r['ts'][:10]; x=out.setdefault(d,{'count':0,'total':0}); x['count']+=1; x['total']+=r['value']
return json.dumps(dict(sorted(out.items()))) | [{"ts":"2026-08-01T10:00:00Z","value":3},{"ts":"2026-08-01T11:00:00Z","value":5},{"ts":"2026-08-02T09:00:00Z","value":7}] | {
"2026-08-01": {
"count": 2,
"total": 8
},
"2026-08-02": {
"count": 1,
"total": 7
}
} | Group JSON records by date (the YYYY-MM-DD prefix of ts) and return daily count and total value. |
cmssjmldo00tajmp20vanl488 | contributor_item | Submission ANL488 | false | import re,json
def transform(text):
out=[]
for l in text.splitlines():
parts={u:int(v) for v,u in re.findall(r'(\d+)([hms])',l)}; out.append(parts.get('h',0)*3600+parts.get('m',0)*60+parts.get('s',0))
return json.dumps(out) | 1h 20m 5s
45m
2h 3s
0s | [
4805,
2700,
7203,
0
] | Parse duration tokens such as '1h 20m 5s' on each line and return total seconds as a JSON array. |
cmssjmldo00t9jmp24n1eoqw1 | contributor_item | Submission 1EOQW1 | false | import json
def transform(text):
rows=[list(map(int,l.split(','))) for l in text.splitlines()]
return json.dumps([list(r) for r in zip(*rows[::-1])]) | 1,2,3,4
5,6,7,8
9,10,11,12 | [
[
9,
5,
1
],
[
10,
6,
2
],
[
11,
7,
3
],
[
12,
8,
4
]
] | Convert a matrix of comma-separated integers into its clockwise 90-degree rotation as JSON. |
cmssjmldo00tbjmp2mmco8qud | contributor_item | Submission CO8QUD | false | import json
def transform(text):
def clean(x):
if isinstance(x,dict):return {k:clean(v) for k,v in x.items() if v is not None}
if isinstance(x,list):return [clean(v) for v in x]
return x
return json.dumps(clean(json.loads(text))) | [{"id":1,"meta":{"x":null,"y":2},"tags":[null,"a"]},{"id":2,"note":null}] | [
{
"id": 1,
"meta": {
"y": 2
},
"tags": [
null,
"a"
]
},
{
"id": 2
}
] | Read JSON records, recursively remove keys whose value is null, and preserve null entries inside arrays. |
cmssjmldo00tdjmp2g1x6dt8h | contributor_item | Submission X6DT8H | false | import re,json
def transform(text):
out=[]
for l in text.splitlines():
m=re.match(r'^(#{1,6})\s+(.+)$',l)
if m:
title=m.group(2); slug=re.sub(r'[^a-z0-9]+','-',title.lower()).strip('-'); out.append({'level':len(m.group(1)),'text':title,'slug':slug})
return json.dumps(out) | # Main Title
text
## API Reference
### Error Codes! | [
{
"level": 1,
"text": "Main Title",
"slug": "main-title"
},
{
"level": 2,
"text": "API Reference",
"slug": "api-reference"
},
{
"level": 3,
"text": "Error Codes!",
"slug": "error-codes"
}
] | Extract Markdown headings, returning JSON objects with level, text, and a lowercase hyphenated slug. |
cmssjmldo00tejmp2fjbdxg3i | contributor_item | Submission BDXG3I | false | import json,itertools
def transform(text):
data=json.loads(text); keys=list(data); rows=[dict(zip(keys,v)) for v in itertools.product(*(data[k] for k in keys))]
return json.dumps(rows) | {"color":["red","blue"],"size":["S","M"],"stock":[1]} | [
{
"color": "red",
"size": "S",
"stock": 1
},
{
"color": "red",
"size": "M",
"stock": 1
},
{
"color": "blue",
"size": "S",
"stock": 1
},
{
"color": "blue",
"size": "M",
"stock": 1
}
] | Convert a JSON object with array values into its Cartesian product as a JSON array of objects, preserving key order. |
cmssjmldo00tfjmp25mpfkram | contributor_item | Submission PFKRAM | false | import json
def transform(text):
c={'added':0,'removed':0,'context':0}
for l in text.splitlines():
if l.startswith(('+++','---')):continue
if l.startswith('+'):c['added']+=1
elif l.startswith('-'):c['removed']+=1
elif l.startswith(' '):c['context']+=1
return json.dumps(c) | --- a/file
+++ b/file
line one
-old
+new
+extra
unchanged | {
"added": 2,
"removed": 1,
"context": 2
} | Parse a unified-diff-like block and return JSON counts of added, removed, and context lines, excluding file headers. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.