Submission J8OU2A

def transform(input):
    out = []
    for line in input:
        if not line:
            continue
        parsed = {}
        for pair in line.split(";"):
            key, value = pair.split("=", 1)
            if value.isdigit():
                parsed[key] = int(value)
            elif value in ("true", "false"):
                parsed[key] = value == "true"
            else:
                parsed[key] = value
        out.append(parsed)
    return out

Define transform(input) to parse each non-empty 'key=value;key=value' string into a dict, converting digit strings to int and true/false to booleans, returning the list of dicts.


Submission 7FQUFE

def transform(input):
    latest = {}
    for row in input:
        current = latest.get(row["user"])
        if current is None or row["version"] > current["version"]:
            latest[row["user"]] = row
    return [latest[u] for u in sorted(latest)]

Define transform(input) to keep only the record with the highest version per user, returned as a list sorted by user ascending.


Submission FSM0CE

def transform(input):
    totals = {}
    for row in input:
        totals[row["dept"]] = totals.get(row["dept"], 0) + row["amount_cents"]
    return [{"dept": d, "total_cents": t} for d, t in sorted(totals.items(), key=lambda kv: (-kv[1], kv[0]))]

Define transform(input) to total amount_cents per dept and return a list of {dept, total_cents} sorted by total_cents descending, then dept ascending for ties.


Submission 5JNYXP

def transform(input):
    rows = []
    for order in input:
        for item in order["items"]:
            rows.append({"order_id": order["order_id"], "sku": item["sku"], "line_total_cents": item["qty"] * item["unit_cents"]})
    return rows

Define transform(input) to flatten orders into one row per line item with order_id, sku, and line_total_cents (qty times unit_cents), preserving input order.


Submission CRT8P2

def transform(input):
    distinct = sorted({r["score"] for r in input}, reverse=True)
    rank_of = {score: i + 1 for i, score in enumerate(distinct)}
    return [{**r, "rank": rank_of[r["score"]]} for r in input]

Define transform(input) to add a dense rank field where the highest score is rank 1 and equal scores share a rank, keeping the original record order.


Submission Y434SP

def transform(input):
    return [{"first": r["first"].capitalize(), "age": r["age"]} for r in input]

Define transform(input) to capitalize the first name and keep age unchanged.


Submission KB606E

def transform(input):
    return [{**r, "temp_f": int(r["temp_c"] * 9 / 5 + 32)} for r in input]

Define transform(input) to add temp_f, the Fahrenheit equivalent of temp_c, as an integer.


Submission GCLM0S

def transform(input):
    return [{**r, "price": r["cost"] * (1 + r["margin"])} for r in input]

Define transform(input) to add price, computed as cost times one plus margin.


Submission 8M9FX7

def transform(input):
    return [r["sku"] for r in input if r["in_stock"]]

Define transform(input) to return the list of skus that are in stock.


Submission X3PUBV

def transform(input):
    return [{**r, "full_name": r["first"] + " " + r["last"]} for r in input]

Define transform(input) to add full_name as first and last joined by a space.


Submission 9DCM98

def transform(input):
    return [r for r in input if r["tags"]]

Define transform(input) to keep only records that have at least one tag.


Submission 38BN9B

def transform(input):
    return [{"email": r["email"].lower()} for r in input]

Define transform(input) to lowercase every email value in place.


Submission FI2FK3

def transform(input):
    return [{"word": w, "length": len(w)} for w in input]

Define transform(input) to return a list of {word, length} objects for each string.


Submission XOVAA9

def transform(input):
    return [{**r, "ctr": round(r["clicks"] / r["views"], 2)} for r in input]

Define transform(input) to add ctr, the clicks divided by views rounded to two decimals.


Submission IBN27V

def transform(input):
    return [{"name": r["name"], "total": sum(r["vals"])} for r in input]

Define transform(input) to return name and the sum of its vals as total.


Submission RZRP85

def transform(input):
    total = 0
    out = []
    for r in input:
        total += r["sales"]
        out.append({**r, "cumulative": total})
    return out

Define transform(input) to add a cumulative running total field named cumulative.


Submission 67KH4T

def transform(input):
    counts = {}
    for s in input:
        counts[s] = counts.get(s, 0) + 1
    return counts

Define transform(input) to return a frequency count of each distinct string.


Submission 8F8ALE

def transform(input):
    return [s.strip().lower() for s in input]

Define transform(input) to return each string trimmed of whitespace and lowercased.


Submission 6VVQ7K

def transform(input):
    def letter(g):
        if g >= 90:
            return "A"
        if g >= 70:
            return "B"
        return "F"
    return [{**r, "letter": letter(r["grade"])} for r in input]

Define transform(input) to add a letter field: A for 90+, B for 70-89, otherwise F.


Submission GTCRNO

def transform(input):
    return [{"n": r["n"], "avg_rating": round(sum(r["reviews"]) / len(r["reviews"]), 1)} for r in input]

Define transform(input) to add avg_rating, the mean of reviews rounded to one decimal.


Submission K1X64D

def transform(input):
    return sorted(input, key=lambda r: r["value"])

Define transform(input) to sort the records by value ascending.


Submission RBZ6NU

def transform(input):
    return [n for n in input if n % 5 == 0 and n > 20]

Define transform(input) to return only values that are multiples of 5 and greater than 20.


Submission 2VINIX

def transform(input):
    return {"total": len(input), "active_count": sum(1 for r in input if r["active"])}

Define transform(input) to return a summary object with total and active_count.


Submission 578WZY

def transform(input):
    return {r["k"]: r["v"] for r in sorted(input, key=lambda x: x["k"])}

Define transform(input) to build a single dict mapping k to v, sorted by key.


Submission I377NF

def transform(input):
    return [{"item": r["item"], "subtotal": r["qty"] * r["price"]} for r in input]

Define transform(input) to return item and subtotal, where subtotal is qty times price.


Submission 907KVP

def transform(input):
    return [n * 2 for n in input if n % 2 == 0]

Define transform(input) to return only the even numbers, each doubled.


Submission GLEKKS

def transform(input):
    totals = {}
    for r in input:
        totals[r["user"]] = totals.get(r["user"], 0) + r["amount"]
    return totals

Define transform(input) to return a mapping of user to their total amount.


Submission S3SS5F

def transform(input):
    return [{**r, "passed": r["score"] >= 80} for r in input]

Define transform(input) to return each record with a passed flag set to True when score >= 80.


Submission 40UWY5

def transform(input):
    return sorted(input, reverse=True)

Define transform(input) to return the numbers sorted in descending order.


Submission JWIJMA

import json,itertools
def transform(s): return json.dumps(list(itertools.accumulate(json.loads(s))))

Parse a JSON integer array and return its cumulative sums as JSON.


Submission Q0SVHG

import json
from collections import Counter
def transform(s): return json.dumps(dict(sorted(Counter(s.split()).items())))

Count whitespace-separated words and return a JSON object sorted by word.


Submission 7ND2XC

import json
def transform(s):
 d={}
 for p in s.split(';'):
  k,v=p.split(':'); d[k]=d.get(k,0)+int(v)
 return json.dumps(dict(sorted(d.items())))

Sum repeated key values from semicolon-separated pairs and return sorted JSON.


Submission XGYPU0

def transform(text):
    totals = {}
    for line in text.strip().splitlines():
        k, v = line.split(",")
        totals[k] = totals.get(k, 0) + int(v)
    rows = sorted(totals.items(), key=lambda kv: (-kv[1], kv[0]))
    return "item,quantity\n" + "\n".join(f"{k},{v}" for k, v in rows)

apple,10
banana,7
apple,-2
orange,5
banana,3
orange,-1

item,quantity
banana,10
apple,8
orange,4

Apply signed quantity adjustments by item and return CSV with header item,quantity sorted by descending final quantity then item name.


Submission 0DMPRR

import json

def transform(text):
    counts = {}
    for u in json.loads(text)["users"]:
        for t in u["tags"]:
            counts[t] = counts.get(t, 0) + 1
    ordered = dict(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])))
    return json.dumps(ordered, separators=(",", ":"))

Count tag frequencies across all users and return compact JSON sorted by descending count then tag name.


Submission NSVD0X

import json
from datetime import datetime

def transform(text):
    out = {}
    for line in text.strip().splitlines():
        ts, event = line.split(",", 1)
        hour = datetime.fromisoformat(ts.replace("Z", "+00:00")).strftime("%H")
        out.setdefault(hour, {})
        out[hour][event] = out[hour].get(event, 0) + 1
    ordered = {h: {e: out[h][e] for e in sorted(out[h])} for h in sorted(out)}
    return json.dumps(ordered, separators=(",", ":"))

Count event names per UTC hour and return JSON keyed by hour with nested event counts.


Submission 3QXMJI

import json

def transform(text):
    out = {}
    for line in text.strip().splitlines():
        k, v = line.split(":", 1)
        k, v = k.strip(), v.strip()
        if "," in v:
            val = sorted(set(x.strip() for x in v.split(",") if x.strip()))
        elif v.lower() in ("yes", "no"):
            val = v.lower() == "yes"
        elif v.lstrip("-").isdigit():
            val = int(v)
        else:
            val = v
        out[k] = val
    return json.dumps(out, separators=(",", ":"))

name: Ada
skills: python, math, python
active: yes
age: 37

Parse simple `key: value` lines; convert comma-separated values to a deduplicated sorted list, yes/no to booleans, integers to numbers, and return compact JSON.


Submission 68XXV9

import json

def transform(text):
    ranges = sorted(json.loads(text)["ranges"])
    merged = []
    for a, b in ranges:
        if not merged or a > merged[-1][1] + 1:
            merged.append([a, b])
        else:
            merged[-1][1] = max(merged[-1][1], b)
    return json.dumps(merged, separators=(",", ":"))

Merge overlapping or touching integer ranges and return the merged ranges as compact JSON.


Submission SJVGDH

import csv, io

def transform(text):
    rows = list(csv.DictReader(io.StringIO(text.strip())))
    rows.sort(key=lambda r: (int(r["priority"]), r["title"]))
    return "priority,title\n" + "\n".join(f'{r["priority"]},{r["title"]}' for r in rows)

priority,title
2,fix docs
1,deploy
3,refactor
1,backup
2,test

priority,title
1,backup
1,deploy
2,fix docs
2,test
3,refactor

Sort CSV tasks by ascending numeric priority then title and return a normalized CSV string with the same header.


Submission 8WQNPR

import json

def transform(text):
    out = {}
    for line in text.strip().splitlines():
        email, role = line.split(",", 1)
        out.setdefault(email.lower(), set()).add(role)
    ordered = {e: sorted(out[e]) for e in sorted(out)}
    return json.dumps(ordered, separators=(",", ":"))

alice@example.com,Admin
ALICE@example.com,Editor
bob@example.com,Viewer
Bob@Example.com,Viewer

Normalize email addresses to lowercase, merge duplicate rows, deduplicate roles case-sensitively, and return compact JSON keyed by normalized email with sorted roles.


Submission 8576VP

import csv, io, json

def transform(text):
    rows = csv.DictReader(io.StringIO(text.strip()), delimiter="\t")
    out = {}
    for r in rows:
        out.setdefault(r["region"], {})
        out[r["region"]][r["product"]] = out[r["region"]].get(r["product"], 0) + int(r["revenue"])
    ordered = {rg: {p: out[rg][p] for p in sorted(out[rg])} for rg in sorted(out)}
    return json.dumps(ordered, separators=(",", ":"))

region	product	revenue
north	A	120
south	A	90
north	B	75
south	B	140
north	A	30

Aggregate TSV revenue by region and product and return nested JSON sorted by region then product.


Submission 1G8J1G

import json, re

def transform(text):
    out = {}
    for part in text.strip().split(";"):
        if not part.strip():
            continue
        k, v = [x.strip() for x in part.split("=", 1)]
        if v.lower() in ("true", "false"):
            val = v.lower() == "true"
        elif re.fullmatch(r"-?\d+", v):
            val = int(v)
        elif re.fullmatch(r"-?\d+\.\d+", v):
            val = float(v)
        else:
            val = v
        out[k] = val
    return json.dumps(out, separators=(",", ":"))

id = 7 ; name =  Ada Lovelace ; active = TRUE ; score = 98.5

Parse semicolon-separated key=value pairs, trim whitespace, coerce integer/float/boolean values, and return compact JSON.


Submission GAFDPC

import json
from datetime import date

def transform(text):
    d = json.loads(text)
    asof = date.fromisoformat(d["as_of"])
    out = {}
    for p in d["people"]:
        b = date.fromisoformat(p["birth"])
        age = asof.year - b.year - ((asof.month, asof.day) < (b.month, b.day))
        out[p["name"]] = age
    return json.dumps(dict(sorted(out.items())), separators=(",", ":"))

Compute each person's integer age as of the supplied ISO date and return a compact JSON object keyed by name.


Submission A91F3B

import json

def transform(text):
    out = {}
    for line in text.strip().splitlines():
        fields = dict(part.split("=", 1) for part in line.split())
        h = fields["host"]
        status = int(fields["status"])
        size = int(fields["bytes"])
        a = out.setdefault(h, {"requests": 0, "bytes": 0, "errors": 0})
        a["requests"] += 1
        a["bytes"] += size
        a["errors"] += int(status >= 400)
    return json.dumps({h: out[h] for h in sorted(out)}, separators=(",", ":"))

host=a.example.com status=200 bytes=120
host=b.example.com status=500 bytes=30
host=a.example.com status=200 bytes=80
host=b.example.com status=200 bytes=70

Parse space-separated key=value log fields and return compact JSON per host with request count, total bytes, and error count for status >= 400.


Submission V0BOZT

import json

def transform(text):
    out = {}
    for line in text.strip().splitlines():
        ip, method, path, status = line.split()
        klass = status[0] + "xx"
        if klass not in ("2xx", "4xx", "5xx"):
            continue
        out.setdefault(ip, {})
        out[ip][klass] = out[ip].get(klass, 0) + 1
    ordered = {ip: {k: out[ip][k] for k in ("2xx", "4xx", "5xx") if k in out[ip]} for ip in sorted(out)}
    return json.dumps(ordered, separators=(",", ":"))

Parse space-separated log rows and return JSON mapping IP to counts of 2xx, 4xx, and 5xx responses, omitting zero-valued classes.


Submission 4C5I0L

import json

def transform(text):
    rows = []
    for line in text.strip().splitlines():
        d, v = line.split(",")
        rows.append((d, int(v)))
    deltas = [{"date": rows[i][0], "delta": rows[i][1] - rows[i-1][1]} for i in range(1, len(rows))]
    best = max(deltas, key=lambda x: x["delta"])["date"]
    return json.dumps({"deltas": deltas, "max_increase_date": best}, separators=(",", ":"))

Convert date,value rows into JSON containing day-over-day deltas starting from the second day and the maximum increase date.


Submission 1KTSDL

import json

def transform(text):
    m = json.loads(text)["matrix"]
    t = [list(col) for col in zip(*m)]
    n = len(m)
    return json.dumps({"transpose": t, "main_diagonal": sum(m[i][i] for i in range(n)), "anti_diagonal": sum(m[i][n-1-i] for i in range(n))}, separators=(",", ":"))

Transpose the rectangular matrix in the JSON input and return compact JSON containing the transposed matrix and both diagonal sums of the original.


Submission T5LHEU

import csv, io, json

def transform(text):
    out = {}
    for r in csv.DictReader(io.StringIO(text.strip())):
        out.setdefault(r["team"], {})
        out[r["team"]][r["member"]] = out[r["team"]].get(r["member"], 0) + int(r["hours"])
    ordered = {t: {m: out[t][m] for m in sorted(out[t])} for t in sorted(out)}
    return json.dumps(ordered, separators=(",", ":"))

team,member,hours
A,Lee,3
A,Sam,5
B,Ira,4
A,Lee,2
B,Ira,1
B,Moe,6

Aggregate CSV hours first by team then member and return nested compact JSON with members sorted alphabetically.


Submission 761TFD

import json, re

def transform(text):
    d = json.loads(text)
    stop = {s.lower() for s in d["stop"]}
    counts = {}
    for w in re.findall(r"[A-Za-z]+", d["text"].lower()):
        if w in stop:
            continue
        counts[w] = counts.get(w, 0) + 1
    ordered = dict(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])))
    return json.dumps(ordered, separators=(",", ":"))

Red fish, blue fish; red bird. BLUE bird!

Tokenize alphabetic words case-insensitively, remove stop words, count remaining words, and return compact JSON sorted by descending frequency then alphabetically.


Submission ERTQ0C

import json

def transform(text):
    sums, counts = {}, {}
    for line in text.strip().splitlines():
        _, p, r = line.split(",")
        sums[p] = sums.get(p, 0) + int(r)
        counts[p] = counts.get(p, 0) + 1
    out = {p: round(sums[p] / counts[p], 2) for p in sorted(sums)}
    return json.dumps(out, separators=(",", ":"))

Parse user,product,rating rows and return JSON with average rating per product rounded to two decimals, sorted by product.


Submission CYXM9O

import json

def transform(text):
    d = json.loads(text)
    out = {}
    for r in d["records"]:
        if r["value"] < d["threshold"]:
            continue
        a = out.setdefault(r["category"], {"count": 0, "sum": 0})
        a["count"] += 1
        a["sum"] += r["value"]
    ordered = {k: out[k] for k in sorted(out)}
    return json.dumps(ordered, separators=(",", ":"))

Filter records to values at least threshold, then return JSON counts and sums by category.


Submission JCVJS5

import json

def transform(text):
    out = []
    for line in text.strip().splitlines():
        i, n, p, a = line.split("|")
        out.append({"id": int(i), "name": n, "price": float(p), "active": a.lower() == "true"})
    return json.dumps(out, separators=(",", ":"))

001|Widget A|12.50|true
002|Widget B|0|false
003|Widget C|7.25|true

Parse pipe-delimited product rows and return compact JSON array coercing id to integer, price to float, and active to boolean.


Submission 7LB266

import json

def transform(text):
    tx = json.loads(text)["transactions"]
    bal = {}
    for t in tx:
        bal[t["acct"]] = bal.get(t["acct"], 0) + t["amount"]
    bal = dict(sorted(bal.items()))
    pos = [k for k, v in bal.items() if v > 0]
    return json.dumps({"balances": bal, "positive_accounts": pos}, separators=(",", ":"))

Compute net transaction amount per account and return compact JSON containing balances plus positive-account names sorted alphabetically.


Submission MBV185

import json

def transform(text):
    d = json.loads(text)
    vals, w = d["values"], d["window"]
    sums = [sum(vals[i:i+w]) for i in range(len(vals)-w+1)]
    return json.dumps({"window_sums": sums, "max_sum": max(sums)}, separators=(",", ":"))

Compute sliding-window sums of the given width and return compact JSON with the sums and the maximum sum.


Submission 6TMAGK

import json

def transform(text):
    scores = json.loads(text)["scores"]
    avgs = {k: round(sum(v)/len(v), 2) for k, v in sorted(scores.items())}
    best = sorted(avgs, key=lambda k: (-avgs[k], k))[0]
    return json.dumps({"averages": avgs, "best_question": best}, separators=(",", ":"))

For each question, compute its average score and return compact JSON with per-question averages plus the question with the highest average; break ties lexicographically.


Submission P00F15

import json

def transform(text):
    paths = json.loads(text)["paths"]
    counts = {}
    for p in paths:
        seg = [s for s in p.split("/") if s]
        key = "/" + "/".join(seg[:2])
        counts[key] = counts.get(key, 0) + 1
    return json.dumps(dict(sorted(counts.items())), separators=(",", ":"))

Group URL paths by their first two non-empty segments (or the entire shorter path), count them, and return compact JSON sorted by group key.


Submission D4R7T7

import csv, io, json

def transform(text):
    rows = csv.DictReader(io.StringIO(text.strip()))
    totals = {}
    for r in rows:
        totals[r["sku"]] = totals.get(r["sku"], 0) + int(r["stock"])
    return json.dumps(dict(sorted(totals.items())), separators=(",", ":"))

sku,warehouse,stock
P1,EAST,4
P1,WEST,7
P2,EAST,0
P2,WEST,3
P3,EAST,5

Aggregate CSV inventory by SKU and return a JSON object mapping each SKU to total stock, sorted by SKU.


Submission GLHQUI

import json

def transform(text):
    data = json.loads(text)
    lines = [{"id": o["id"], "line_total": o["qty"] * o["price"]} for o in data["orders"]]
    grand = sum(x["line_total"] for x in lines)
    top = max(lines, key=lambda x: x["line_total"])["id"]
    return json.dumps({"grand_total": grand, "highest_value_order": top}, separators=(",", ":"))

Parse the JSON order list, compute each line total, and return JSON containing the grand total and the id of the highest-value line.


Submission 50YF4U

import json

def transform(text):
    sums, counts = {}, {}
    for line in text.strip().splitlines():
        _, service, ms = line.split(",")
        sums[service] = sums.get(service, 0) + int(ms)
        counts[service] = counts.get(service, 0) + 1
    out = {k: round(sums[k] / counts[k], 1) for k in sorted(sums)}
    return json.dumps(out, separators=(",", ":"))

Parse date,service,milliseconds rows and return JSON with average latency per service rounded to one decimal.


Submission 3OVIW0

import json

def transform(text):
    users = {}
    for line in text.strip().splitlines():
        user, roles = line.split("|", 1)
        users.setdefault(user, set()).update(r for r in roles.split(",") if r)
    out = {u: sorted(users[u]) for u in sorted(users)}
    return json.dumps(out, separators=(",", ":"))

alice|admin,editor
bob|viewer
carol|editor,viewer
alice|viewer

Parse user|comma-separated-roles lines, merge duplicate users, deduplicate roles, sort roles alphabetically, and return JSON keyed by username.


Submission HUTZFX

import json

def transform(text):
    data = json.loads(text)["events"]
    agg = {}
    for e in data:
        a = agg.setdefault(e["type"], {"total": 0, "successful": 0})
        a["total"] += 1
        a["successful"] += int(bool(e["ok"]))
    out = {}
    for k in sorted(agg):
        a = agg[k]
        out[k] = {"total": a["total"], "successful": a["successful"], "success_rate": round(a["successful"] / a["total"], 2)}
    return json.dumps(out, separators=(",", ":"))

Group events by type and return JSON with total count, successful count, and success_rate rounded to two decimals for each type.


Submission EW58DI

import json, statistics

def transform(text):
    vals = [x for x in json.loads(text)["readings"] if x is not None]
    return json.dumps({"count": len(vals), "min": min(vals), "max": max(vals), "median": statistics.median(vals)}, separators=(",", ":"))

From the JSON readings array, ignore nulls and return JSON with count, min, max, and median.


Submission L47GPX

def transform(text):
    totals = {}
    for line in text.strip().splitlines():
        k, v = line.split(":")
        totals[k] = totals.get(k, 0) + int(v)
    pairs = sorted(totals.items(), key=lambda kv: (-kv[1], kv[0]))
    return "\n".join(f"{k}={v}" for k, v in pairs)

Sum colon-separated integer values by key, then return lines sorted by descending total and key as `key=total`.


Submission KIEJIP

import csv, io, json

def transform(text):
    rows = csv.DictReader(io.StringIO(text.strip()))
    out = []
    for r in rows:
        total = int(r["qty"]) * float(r["unit_price"]) * (1 - float(r["discount_pct"]) / 100)
        out.append({"item": r["item"], "total": round(total, 2)})
    return json.dumps(out, separators=(",", ":"))

Compute each CSV line's discounted total and return a compact JSON array with item and total rounded to two decimals.


Submission MC1Q4Y

import json

def transform(text):
    rows=[(d,int(v)) for d,v in (line.split(",") for line in text.strip().splitlines())]
    mn=min(rows,key=lambda x:x[1]);mx=max(rows,key=lambda x:x[1])
    return json.dumps({"min":{"date":mn[0],"value":mn[1]},"max":{"date":mx[0],"value":mx[1]}},separators=(",",":"))

Parse date,value lines and return compact JSON with the minimum value, maximum value, and dates where they occur.


Submission K368L3

def transform(text):
    d={}
    for line in text.strip().splitlines():
        k,v=line.split("|");d[k]=d.get(k,0)+int(v)
    return "\n".join(f"{k}:{v}" for k,v in sorted(d.items(),key=lambda kv:(-kv[1],kv[0])))

Sum pipe-delimited quantities by color and return lines as color:total sorted by descending total then color.


Submission 50TOE7

import json

def transform(text):
    out={}
    for line in text.strip().splitlines():
        k,vals=line.split(":");out[k]=sum(map(int,vals.split(",")))
    return json.dumps(out,separators=(",",":"))

Parse label:comma-separated-integers lines and return compact JSON mapping each label to the sum of its values.


Submission 3MEKUK

import json

def transform(text):
    c={}
    for r in json.loads(text)["rows"]:
        if r["active"]:c[r["dept"]]=c.get(r["dept"],0)+1
    return json.dumps(dict(sorted(c.items())),separators=(",",":"))

Count only active JSON rows by department and return compact JSON sorted by department.


Submission FY0T7V

import json

def transform(text):
    a=list(map(int,text.strip().splitlines()))
    return json.dumps({"first":a[0],"last":a[-1],"change":a[-1]-a[0]},separators=(",",":"))

Convert newline-separated integers into compact JSON containing the first value, last value, and net change.


Submission 3INRMA

import json

def transform(text):
    out={}
    for k,v in json.loads(text)["pairs"]:out[k]=out.get(k,0)+v
    return json.dumps(dict(sorted(out.items())),separators=(",",":"))

Fold JSON key/value pairs into an object by summing repeated keys and return compact JSON sorted by key.


Submission 3RAYCO

import json

def transform(text):
    keys=[]
    for line in text.strip().splitlines():
        k,v=line.split("=")
        if v.lower()=="true":keys.append(k)
    return json.dumps(sorted(keys),separators=(",",":"))

Parse key=boolean lines case-insensitively and return compact JSON listing enabled keys alphabetically.


Submission RCNTCS

import json

def transform(text):
    vals=json.loads(text)["values"]
    c={}
    for v in vals:c[v]=c.get(v,0)+1
    return json.dumps({str(k):c[k] for k in sorted(c)},separators=(",",":"))

Count each integer in the JSON values array and return compact JSON keyed by the number as a string, ordered numerically.


Submission GTVQRF

import csv,io,json

def transform(text):
    d={}
    for r in csv.DictReader(io.StringIO(text.strip())):d[r["name"]]=d.get(r["name"],0)+int(r["score"])
    return json.dumps(dict(sorted(d.items())),separators=(",",":"))

name,score
Ari,8
Bea,10
Ari,6
Cal,7
Bea,4

Aggregate CSV scores by name and return compact JSON with each name’s total score, sorted alphabetically.


Submission V9S67N

import json

def transform(text):
    c={}
    for w in json.loads(text)["words"]:
        w=w.lower();c[w]=c.get(w,0)+1
    return json.dumps(dict(sorted(c.items(),key=lambda kv:(-kv[1],kv[0]))),separators=(",",":"))

Normalize words to lowercase, count frequencies, and return compact JSON ordered by descending count then word.


Submission S0H58R

import json

def transform(text):
    c={}
    for p in json.loads(text)["paths"]:
        k=p.split("/")[0];c[k]=c.get(k,0)+1
    return json.dumps(dict(sorted(c.items())),separators=(",",":"))

Count JSON slash-delimited paths by first segment and return compact JSON sorted by segment.


Submission CHJ0DF

import csv,io,json
from decimal import Decimal

def transform(text):
    out={}
    for r in csv.DictReader(io.StringIO(text.strip())):out[r["sku"]]=int(Decimal(r["price"])*100)
    return json.dumps(out,separators=(",",":"))

Convert CSV prices to integer cents and return compact JSON mapping SKU to cents in input order.


Submission XHJQZK

import json

def transform(text):
    d={}
    for line in text.strip().splitlines():
        _,k,v=line.split("|");d[k]=d.get(k,0)+int(v)
    return json.dumps(dict(sorted(d.items())),separators=(",",":"))

Aggregate pipe-delimited points by category, ignoring user id, and return compact JSON sorted by category.


Submission ON6YTJ

import json

def transform(text):
    d={}
    for line in text.strip().splitlines():
        k,v=line.split(",");d[k]=d.get(k,0)+int(v)
    k=sorted(d,key=lambda x:(-d[x],x))[0]
    return json.dumps({"key":k,"total":d[k]},separators=(",",":"))

Parse key,value rows and return compact JSON with the key having the highest total and that total; break ties alphabetically.


Submission B9DOO7

import json

def transform(text):
    s=0;out=[]
    for v in json.loads(text)["values"]:
        s+=v;out.append(s)
    return json.dumps(out,separators=(",",":"))

Return compact JSON with the cumulative sums of the input values.


Submission EPFGGZ

import json

def transform(text):
    r=sorted(json.loads(text)["records"],key=lambda x:x["id"])
    return json.dumps([x["name"] for x in r],separators=(",",":"))

Sort JSON records by numeric id ascending and return a compact JSON array of names only.


Submission RYA70N

import json

def transform(text):
    seen=set();out=[]
    for x in json.loads(text)["values"]:
        if x not in seen:seen.add(x);out.append(x)
    return json.dumps(out,separators=(",",":"))

Remove duplicate integers while preserving first occurrence order and return a compact JSON array.


Submission 5XIME3

import json

def transform(text):
    rows=json.loads(text)["rows"]
    return json.dumps([sum(col) for col in zip(*rows)],separators=(",",":"))

Compute column sums for the rectangular JSON rows matrix and return them as a compact JSON array.


Submission WWX8XC

import json

def transform(text):
    d=json.loads(text)
    return json.dumps(sorted(x for x in d["values"] if x>d["threshold"]),separators=(",",":"))

Filter values strictly above the JSON threshold, sort ascending, and return them as a compact JSON array.


Submission A2AEAB

import json

def transform(text):
    out={}
    for line in text.strip().splitlines():
        p,q,price=line.split(":");out[p]=int(q)*int(price)
    return json.dumps(dict(sorted(out.items())),separators=(",",":"))

Parse product:quantity:unit_price rows and return compact JSON mapping each product to line revenue, sorted by product.


Submission 3AD1L6

import csv,io,json

def transform(text):
    d={}
    for r in csv.DictReader(io.StringIO(text.strip())):
        t=int(r["temp"]);d[r["city"]]=max(t,d.get(r["city"],t))
    return json.dumps(dict(sorted(d.items())),separators=(",",":"))

city,temp
Delhi,32
Mumbai,29
Delhi,35
Mumbai,31

Compute maximum temperature per city from CSV and return compact JSON sorted by city.


Submission PBFY71

import json

def transform(text):
    g=json.loads(text)["groups"]
    return json.dumps({k:len(v) for k,v in sorted(g.items()) if v},separators=(",",":"))

Return compact JSON mapping each group to its item count and omit empty groups.


Submission 8G3NUE

import json

def transform(text):
    d={}
    for w in text.split():d[w]=d.get(w,0)+1
    return json.dumps(dict(sorted(d.items())),separators=(",",":"))

Count whitespace-delimited tokens across all lines and return compact JSON sorted alphabetically.


Submission 5L12PH

import csv,io,json

def transform(text):
    d={}
    for r in csv.DictReader(io.StringIO(text.strip())):d[r["status"]]=d.get(r["status"],0)+1
    return json.dumps(dict(sorted(d.items())),separators=(",",":"))

id,status
1,open
2,closed
3,open
4,pending
5,closed

Count CSV rows by status and return compact JSON sorted by status.


Submission IY3NVW

import json

def transform(text):
    a=json.loads(text)["nums"]
    return json.dumps({"negative":sum(x<0 for x in a),"zero":sum(x==0 for x in a),"positive":sum(x>0 for x in a)},separators=(",",":"))

Return compact JSON with counts of negative, zero, and positive numbers.


Submission 26Z283

import json

def transform(text):
    out={}
    for part in text.split(";"):
        k,v=part.split("=");v=int(v)
        if v>0 and v%2:out[k]=v
    return json.dumps(out,separators=(",",":"))

Parse semicolon-separated integer assignments and return compact JSON containing only entries with positive odd values, preserving key order.


Submission 2GV4X2

import json

def transform(text):
    out={}
    for r in json.loads(text)["items"]:out[r["k"]]=out.get(r["k"],1)*r["v"]
    return json.dumps(dict(sorted(out.items())),separators=(",",":"))

Group JSON items by k, multiply values within each group, and return compact JSON sorted by key.


Submission HNO9LM

import json

def transform(text):
    a=json.loads(text)["nums"]
    return json.dumps({"even":[x for x in a if x%2==0],"odd":[x for x in a if x%2]},separators=(",",":"))

Partition the JSON nums array into even and odd arrays and return compact JSON with evens first.


Submission C019SL

import json

def transform(text):
    total=0
    for line in text.strip().splitlines():
        s,w=line.split("|");total+=len(s)*int(w)
    return json.dumps({"weighted_chars":total},separators=(",",":"))

Parse token|weight lines and return compact JSON with total weighted character count, defined as len(token)*weight summed across rows.


Submission XHNJHF

import json

def transform(text):
    r=sorted(json.loads(text)["items"],key=lambda x:(-x["score"],x["name"]))[0]
    return json.dumps({"name":r["name"],"score":r["score"]},separators=(",",":"))

Select the highest-scoring item from JSON, breaking ties by name alphabetically, and return compact JSON with name and score.


Submission MGZ4EC

import json

def transform(text):
    result = {}
    for line in text.strip().split('\n'):
        line = line.strip()
        if line and not line.startswith('#') and '=' in line:
            key, _, value = line.partition('=')
            result[key.strip()] = value.strip()
    return json.dumps(result)

DATABASE_URL=postgres://localhost/mydb
SECRET_KEY=abc123xyz
DEBUG=true
PORT=8080

Parse a .env format file into a JSON object mapping variable names to their string values. Ignore comment lines and blank lines.


Submission MFJWSS

import csv, io

def transform(text):
    reader = csv.reader(io.StringIO(text.strip()))
    rows = list(reader)
    transposed = list(zip(*rows))
    out = io.StringIO()
    writer = csv.writer(out)
    writer.writerows(transposed)
    return out.getvalue().strip()

Transpose a CSV matrix: rows become columns and columns become rows, preserving all values.


Submission 1SCVPM

import json

def transform(text):
    data = json.loads(text)
    result = [{"id": u["id"], "name": u["profile"]["name"]} for u in data["users"]]
    return json.dumps(result)

Extract a flat list of objects containing only 'id' and 'name' from a nested JSON structure where the name is inside a 'profile' sub-object.


Submission YC0JRH

import csv, io, json

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    return json.dumps(list(reader))

Name,Age,City
Alice,30,New York
Bob,25,San Francisco
Carol,35,Chicago

Parse a CSV string with a header row and return a JSON array of objects where each object maps column names to values.


Submission 0ZLN96

import json

def to_camel(s):
    parts = s.split('_')
    return parts[0] + ''.join(p.title() for p in parts[1:])

def transform(text):
    data = json.loads(text)
    return json.dumps({to_camel(k): v for k, v in data.items()})

Convert all keys in a flat JSON object from snake_case to camelCase.


Submission 45PM6C

import json

def transform(text):
    data = json.loads(text)
    flat = [item for sublist in data for item in sublist]
    return json.dumps(flat)

Flatten a JSON array of arrays into a single JSON array containing all elements in order.


Submission WFNUL9

import json

def transform(text):
    nums = json.loads(text)
    n = len(nums)
    total = sum(nums)
    s = sorted(nums)
    mid = n // 2
    median = s[mid] if n % 2 == 1 else (s[mid - 1] + s[mid]) / 2
    return json.dumps({"count": n, "sum": total, "mean": round(total / n, 2), "min": s[0], "max": s[-1], "median": median})

Compute descriptive statistics (count, sum, mean, min, max, median) for a JSON array of numbers and return them as a JSON object.


Submission NWBPZ2

import json, csv, io

def transform(text):
    data = json.loads(text)
    out = io.StringIO()
    writer = csv.writer(out)
    writer.writerow(['name', 'salary', 'bonus', 'total'])
    for row in data:
        bonus = round(row['salary'] * row['bonus_pct'])
        total = row['salary'] + bonus
        writer.writerow([row['name'], row['salary'], bonus, total])
    return out.getvalue().strip()

Read a JSON array of employee records and output a CSV with headers name, salary, bonus, total. Bonus is salary * bonus_pct (rounded to integer). Total is salary + bonus.


Submission GRAK2Q

import json

def transform(text):
    data = json.loads(text)
    seen = set()
    result = []
    for item in data:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return json.dumps(result)

Deduplicate a JSON array of integers, preserving the first occurrence of each value, and return the result as a JSON array.


Submission U0BFQB

import re

def transform(text):
    results = []
    for line in text.strip().split('\n'):
        digits = re.sub(r'\D', '', line)
        if len(digits) == 11 and digits.startswith('1'):
            results.append(f'+{digits}')
        elif len(digits) == 10:
            results.append(f'+1{digits}')
    return '\n'.join(results)

Normalize US phone numbers to E.164 format (+1XXXXXXXXXX), stripping all non-digit characters and prepending +1 for 10-digit numbers.


Submission TSKNZ7

import json

def transform(text):
    tasks = []
    for line in text.strip().split('\n'):
        line = line.strip()
        if line.startswith('- ['):
            done = line[3] == 'x'
            title = line[6:].strip()
            tasks.append({"title": title, "done": done})
    return json.dumps(tasks)

- [x] Buy groceries
- [ ] Write documentation
- [x] Fix bug #123
- [ ] Deploy to production

Buy groceries

Write documentation

Fix bug #123

Deploy to production

Parse a Markdown-style task list and return a JSON array of objects with 'title' (string) and 'done' (boolean) fields.


Submission U538UL

def transform(text):
    domains = sorted(set(
        line.strip().split('@')[1]
        for line in text.strip().split('\n')
        if '@' in line.strip()
    ))
    return '\n'.join(domains)

alice@example.com
bob@company.org
carol@example.com
dave@university.edu
eve@company.org

Extract unique domain names from a list of email addresses and return them sorted alphabetically, one per line.


Submission M4H2E7

import json

def transform(text):
    result = {}
    section = None
    for line in text.strip().split('\n'):
        line = line.strip()
        if not line or line.startswith(';'):
            continue
        if line.startswith('[') and line.endswith(']'):
            section = line[1:-1]
            result[section] = {}
        elif '=' in line and section:
            k, _, v = line.partition('=')
            result[section][k.strip()] = v.strip()
    return json.dumps(result)

[database]
host=localhost
port=5432
name=mydb

[cache]
host=redis
port=6379
ttl=3600

Parse an INI-style configuration file into a nested JSON object where each section becomes a key and its entries become key-value pairs.


Submission UJ4YF4

import json, re
from collections import Counter

def transform(text):
    methods = Counter(
        re.search(r'"(\w+) ', line).group(1)
        for line in text.strip().split('\n')
        if line.strip()
    )
    return json.dumps(dict(sorted(methods.items())))

Parse Apache-style access log lines and return a JSON object counting requests by HTTP method, sorted alphabetically by method name.


Submission LL75MS

import json
from collections import Counter

def transform(text):
    words = text.strip().lower().split()
    top3 = dict(Counter(words).most_common(3))
    return json.dumps(top3)

apple banana apple cherry banana apple cherry cherry cherry banana

Count word frequency in the input text and return a JSON object with the top 3 most frequent words mapped to their counts.


Submission OIB6MG

import json

def transform(text):
    result = {}
    for line in text.strip().split('\n'):
        if '=' in line:
            k, _, v = line.partition('=')
            k = k.strip()
            if k.startswith('app_'):
                result[k[4:]] = v.strip()
    return json.dumps(result)

app_name=MyApp
app_version=1.2.3
db_host=localhost
db_port=5432
app_debug=true

Extract only the key=value pairs whose keys start with 'app_', strip the prefix, and return the remaining pairs as a JSON object.


Submission 25L5E8

def transform(text):
    return '\n'.join(
        '|'.join(line.split('\t'))
        for line in text.strip().split('\n')
    )

Name	Age	City
Alice	30	New York
Bob	25	San Francisco

Name|Age|City
Alice|30|New York
Bob|25|San Francisco

Convert a tab-delimited string to a pipe-delimited string, preserving all rows and columns.


Submission SWFLP8

import json

def transform(text):
    data = json.loads(text)
    lines = []
    for k, v in data.items():
        if isinstance(v, bool):
            lines.append(f"{k}: {'true' if v else 'false'}")
        else:
            lines.append(f"{k}: {v}")
    return '\n'.join(lines)

host: localhost
port: 5432
database: myapp
ssl: true

Convert a flat JSON object to a YAML-style text representation with one key: value pair per line. Boolean values should appear as 'true' or 'false' (lowercase).


Submission JJTXFY

import csv, io, json
from collections import defaultdict

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()), delimiter='\t')
    totals = defaultdict(int)
    for row in reader:
        totals[row['Region']] += int(row['Sales'])
    return json.dumps(dict(sorted(totals.items())))

Region	Product	Sales
North	Widget	500
South	Gadget	300
North	Gadget	700
South	Widget	400
East	Widget	200
North	Widget	300

Parse a tab-separated sales report and return a JSON object mapping each region to its total sales, sorted alphabetically by region name.


Submission Q6Z9S9

import re

def transform(text):
    def parse_duration(s):
        total = 0
        m = re.search(r'(\d+)h', s)
        if m: total += int(m.group(1)) * 3600
        m = re.search(r'(\d+)m', s)
        if m: total += int(m.group(1)) * 60
        m = re.search(r'(\d+)s', s)
        if m: total += int(m.group(1))
        return total
    return '\n'.join(str(parse_duration(line)) for line in text.strip().split('\n'))

Convert duration strings (e.g. '1h 30m 45s') to total seconds. Each line is one duration; output one integer per line.


Submission C70G90

import json
def transform(text):
 d=json.loads(text); out={}
 for r in d['transactions']: out[r['account']]=out.get(r['account'],0)+r['amount']
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 0

Aggregate JSON transactions by account and return compact sorted JSON balances. Scenario family 1.


Submission E9L1N5

import json
def transform(text):
 d={}
 for line in text.strip().splitlines():
  u,r=line.split('|'); d.setdefault(u,set()).add(r)
 return json.dumps({u:sorted(d[u]) for u in sorted(d)},separators=(',',':'))
# scenario 3

alice|admin
bob|viewer
alice|editor
bob|viewer

Parse pipe-delimited user,role rows, deduplicate roles, and return compact sorted JSON. Scenario family 4.


Submission VTO3AZ

import json
def transform(text):
 d={}
 for line in text.strip().splitlines():
  u,r=line.split('|'); d.setdefault(u,set()).add(r)
 return json.dumps({u:sorted(d[u]) for u in sorted(d)},separators=(',',':'))
# scenario 1

Parse pipe-delimited user,role rows, deduplicate roles, and return compact sorted JSON. Scenario family 2.


Submission JZIJP2

import json
def transform(text):
 a=json.loads(text)['values']; return json.dumps({'min':min(a),'max':max(a),'sum':sum(a),'mean':round(sum(a)/len(a),2)},separators=(',',':'))
# scenario 1

From JSON integer values, return compact JSON containing min, max, sum, and rounded mean. Scenario family 2.


Submission KSV03O

import json
def transform(text):
 a=json.loads(text)['values']; return json.dumps({'min':min(a),'max':max(a),'sum':sum(a),'mean':round(sum(a)/len(a),2)},separators=(',',':'))
# scenario 3

From JSON integer values, return compact JSON containing min, max, sum, and rounded mean. Scenario family 4.


Submission J95W06

import json
def transform(text):
 d=json.loads(text); rows=sorted((r for r in d['records'] if r['score']>=d['threshold']),key=lambda r:r['id'])
 return json.dumps([{'id':r['id'],'name':r['name']} for r in rows],separators=(',',':'))
# scenario 0

Filter JSON records whose score meets threshold, sort by id, and return id/name pairs as compact JSON. Scenario family 1.


Submission 59YEJL

import csv,io,json
def transform(text):
 out={}
 for r in csv.DictReader(io.StringIO(text)): out[r['category']]=out.get(r['category'],0)+int(r['value'])
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 0

Parse CSV category,value rows and return compact JSON totals sorted by category. Scenario family 1.


Submission QK7XM7

import json
def transform(text):
 d={}
 for line in text.strip().splitlines():
  u,r=line.split('|'); d.setdefault(u,set()).add(r)
 return json.dumps({u:sorted(d[u]) for u in sorted(d)},separators=(',',':'))
# scenario 0

Parse pipe-delimited user,role rows, deduplicate roles, and return compact sorted JSON. Scenario family 1.


Submission WZSVCC

import csv,io,json
def transform(text):
 out={}
 for r in csv.DictReader(io.StringIO(text)): out[r['category']]=out.get(r['category'],0)+int(r['value'])
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 1

Parse CSV category,value rows and return compact JSON totals sorted by category. Scenario family 2.


Submission KTA64F

import json
def transform(text):
 a=json.loads(text)['values']; return json.dumps({'min':min(a),'max':max(a),'sum':sum(a),'mean':round(sum(a)/len(a),2)},separators=(',',':'))
# scenario 0

From JSON integer values, return compact JSON containing min, max, sum, and rounded mean. Scenario family 1.


Submission 1YRZNR

import json
def transform(text):
 d=json.loads(text); rows=sorted((r for r in d['records'] if r['score']>=d['threshold']),key=lambda r:r['id'])
 return json.dumps([{'id':r['id'],'name':r['name']} for r in rows],separators=(',',':'))
# scenario 1

Filter JSON records whose score meets threshold, sort by id, and return id/name pairs as compact JSON. Scenario family 2.


Submission XAMVF1

import json
def transform(text):
 d=json.loads(text); out={}
 for r in d['transactions']: out[r['account']]=out.get(r['account'],0)+r['amount']
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 1

Aggregate JSON transactions by account and return compact sorted JSON balances. Scenario family 2.


Submission 5X64EO

import json
def transform(text):
 d=json.loads(text); out={}
 for r in d['transactions']: out[r['account']]=out.get(r['account'],0)+r['amount']
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 2

Aggregate JSON transactions by account and return compact sorted JSON balances. Scenario family 3.


Submission J1HUP0

import csv,io,json
def transform(text):
 out={}
 for r in csv.DictReader(io.StringIO(text)): out[r['category']]=out.get(r['category'],0)+int(r['value'])
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 2

Parse CSV category,value rows and return compact JSON totals sorted by category. Scenario family 3.


Submission OXCBN0

import json
def transform(text):
 a=json.loads(text)['values']; return json.dumps({'min':min(a),'max':max(a),'sum':sum(a),'mean':round(sum(a)/len(a),2)},separators=(',',':'))
# scenario 2

From JSON integer values, return compact JSON containing min, max, sum, and rounded mean. Scenario family 3.


Submission 3IM90Q

import json
def transform(text):
 d=json.loads(text); out={}
 for r in d['transactions']: out[r['account']]=out.get(r['account'],0)+r['amount']
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 3

Aggregate JSON transactions by account and return compact sorted JSON balances. Scenario family 4.


Submission RNBW3P

import json
def transform(text):
 d=json.loads(text); rows=sorted((r for r in d['records'] if r['score']>=d['threshold']),key=lambda r:r['id'])
 return json.dumps([{'id':r['id'],'name':r['name']} for r in rows],separators=(',',':'))
# scenario 2

Filter JSON records whose score meets threshold, sort by id, and return id/name pairs as compact JSON. Scenario family 3.


Submission RLC9KX

import json
def transform(text):
 d={}
 for line in text.strip().splitlines():
  u,r=line.split('|'); d.setdefault(u,set()).add(r)
 return json.dumps({u:sorted(d[u]) for u in sorted(d)},separators=(',',':'))
# scenario 2

Parse pipe-delimited user,role rows, deduplicate roles, and return compact sorted JSON. Scenario family 3.


Submission XC66KK

import json
def transform(text):
 d=json.loads(text); rows=sorted((r for r in d['records'] if r['score']>=d['threshold']),key=lambda r:r['id'])
 return json.dumps([{'id':r['id'],'name':r['name']} for r in rows],separators=(',',':'))
# scenario 3

Filter JSON records whose score meets threshold, sort by id, and return id/name pairs as compact JSON. Scenario family 4.


Submission BJG5AO

import csv,io,json
def transform(text):
 out={}
 for r in csv.DictReader(io.StringIO(text)): out[r['category']]=out.get(r['category'],0)+int(r['value'])
 return json.dumps(dict(sorted(out.items())),separators=(',',':'))
# scenario 3

Parse CSV category,value rows and return compact JSON totals sorted by category. Scenario family 4.


Submission ONP7TG

import csv, io, json
from collections import defaultdict

def transform(text):
    agg=defaultdict(lambda:{'count':0,'total':0})
    for r in csv.DictReader(io.StringIO(text)):
        d=agg[r['dept']]; d['count']+=1; d['total']+=int(r['amount'])
    return json.dumps(dict(sorted(agg.items())), sort_keys=True)

dept,amount
eng,120
sales,80
eng,30
sales,20
ops,50

Parse the CSV and return a JSON object keyed by department with row count and total amount; keys must be sorted alphabetically.


Submission GPEJ2B

import json

def transform(text):
    rows=json.loads(text)
    rows=[{'id':r['id'],'score':r['score']} for r in rows if r.get('active') and r['score']>=10]
    rows.sort(key=lambda r:(-r['score'],r['id']))
    return json.dumps(rows)

From the JSON array, keep active records with score at least 10, sort by descending score then id, and return only id and score as JSON.


Submission HDBFY7

import urllib.parse, json

def transform(text):
    pairs=urllib.parse.parse_qsl(text, keep_blank_values=True)
    out={}
    for k,v in pairs:
        out.setdefault(k,[])
        if v not in out[k]: out[k].append(v)
    return json.dumps({k:out[k] for k in sorted(out)})

Parse the query string, preserve repeated values, deduplicate each key's values in first-seen order, and return a JSON object with alphabetically sorted keys.


Submission SIB9WW

import json

def transform(text):
    out={}
    for line in text.strip().splitlines():
        k,v=line.split('|'); v=int(v)
        out[k]=max(out.get(k,v),v)
    return json.dumps(dict(sorted(out.items())))

Parse pipe-delimited name/value rows and return a JSON object containing the maximum value observed for each name, sorted by name.


Submission MUNYR2

import json
from collections import defaultdict

def transform(text):
    agg=defaultdict(lambda:defaultdict(int))
    for line in text.strip().splitlines():
        day,svc,count=line.split(','); agg[day][svc]+=int(count)
    out={d:{s:agg[d][s] for s in sorted(agg[d])} for d in sorted(agg)}
    return json.dumps(out)

Parse date,service,count rows and return JSON totals per date, with nested service totals and dates/services sorted lexicographically.


Submission SHM13N

import json
# scenario_19
def transform(text):
 n=[int(x) for x in text.split(",")];k=2
 return json.dumps([sum(n[i:i+k]) for i in range(len(n)-k+1)],separators=(",",":"))

Parse CSV integers and compute width-2 consecutive sums (scenario_19).


Submission F659CY

import json
# scenario_3
def transform(text):
 rows=json.loads(text)
 return json.dumps([{"id":r["id"],"score":r["score"]} for r in rows if r["active"] and r["score"]>=30],separators=(",",":"))

Filter active JSON rows at score >= 30, project id and score, preserve order (scenario_3).


Submission ILXU1I

import json
from collections import defaultdict
# scenario_8
def transform(text):
 t=defaultdict(int)
 for r in json.loads(text): t[r["region"]]+=r["units"]*r["price"]
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Aggregate sales by region as units*price and key-sort compact JSON (scenario_8).


Submission 9JSV9Z

import json
from collections import defaultdict
# scenario_22
def transform(text):
 t=defaultdict(int)
 for l in text.splitlines():
  k,x=l.split("|",1);t[k]+=int(x)
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Parse key|integer lines, sum repeated keys, sort keys (scenario_22).


Submission S1W23E

import json
# scenario_45
def transform(text):
 d=json.loads(text);k="zone"
 return json.dumps([{"id":u["id"],k:u["profile"][k]} for u in d["users"]],separators=(",",":"))

Extract id and nested profile.zone from users (scenario_45).


Submission GPDRWX

# scenario_28
def transform(text):
 seen=set();out=[]
 for w in text.splitlines():
  k=w.casefold()
  if k not in seen: seen.add(k);out.append(w)
 return "\n".join(out)

Alpha2
BETA
alpha2
Gamma
beta
GAMMA
Delta2

Deduplicate tokens case-insensitively, retaining first spelling/order (scenario_28).


Submission 81HROD

import json
from collections import defaultdict
# scenario_24
def transform(text):
 t=defaultdict(int)
 for l in text.splitlines():
  k,x=l.split("~",1);t[k]+=int(x)
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Parse key~integer lines, sum repeated keys, sort keys (scenario_24).


Submission GLI1AQ

import json,re
# scenario_33
def transform(text):
 out=[]
 for l in text.splitlines():
  h,m,s=map(int,re.fullmatch(r"(\d+)h (\d+)m (\d+)s",l).groups());out.append(h*3600+m*60+s)
 return json.dumps(out,separators=(",",":"))

Convert required h/m/s duration lines to JSON seconds (scenario_33).


Submission BHF33N

import json
# scenario_47
def transform(text):
 r=json.loads(text);r.sort(key=lambda x:(-x["priority"],x["age"],x["name"]))
 return json.dumps([{"name":x["name"],"priority":x["priority"]} for x in r[:3]],separators=(",",":"))

Select top 3 jobs by priority desc, age/name asc (scenario_47).


Submission VK65BC

import json
# scenario_4
def transform(text):
 rows=json.loads(text)
 return json.dumps([{"id":r["id"],"score":r["score"]} for r in rows if r["active"] and r["score"]>=35],separators=(",",":"))

Filter active JSON rows at score >= 35, project id and score, preserve order (scenario_4).


Submission 7BOMAL

import json
# scenario_1
def transform(text):
 rows=json.loads(text)
 return json.dumps([{"id":r["id"],"score":r["score"]} for r in rows if r["active"] and r["score"]>=20],separators=(",",":"))

Filter active JSON rows at score >= 20, project id and score, preserve order (scenario_1).


Submission TWKQ6A

import json
# scenario_2
def transform(text):
 rows=json.loads(text)
 return json.dumps([{"id":r["id"],"score":r["score"]} for r in rows if r["active"] and r["score"]>=25],separators=(",",":"))

Filter active JSON rows at score >= 25, project id and score, preserve order (scenario_2).


Submission OTTNH5

import json
# scenario_5
def transform(text):
 rows=json.loads(text)
 return json.dumps([{"id":r["id"],"score":r["score"]} for r in rows if r["active"] and r["score"]>=40],separators=(",",":"))

Filter active JSON rows at score >= 40, project id and score, preserve order (scenario_5).


Submission L2OSB9

import json
from collections import defaultdict
# scenario_7
def transform(text):
 t=defaultdict(int)
 for r in json.loads(text): t[r["region"]]+=r["units"]*r["price"]
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Aggregate sales by region as units*price and key-sort compact JSON (scenario_7).


Submission HGEHLW

import json
from collections import defaultdict
# scenario_6
def transform(text):
 t=defaultdict(int)
 for r in json.loads(text): t[r["region"]]+=r["units"]*r["price"]
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Aggregate sales by region as units*price and key-sort compact JSON (scenario_6).


Submission A9PQ0T

import json
# scenario_11
def transform(text):
 d=json.loads(text);p="app_"
 return json.dumps({k[len(p):]:v for k,v in d.items() if k.startswith(p)},separators=(",",":"))

Select 'app_' JSON keys, strip the prefix, preserve values (scenario_11).


Submission 85JZCY

import json
from collections import defaultdict
# scenario_9
def transform(text):
 t=defaultdict(int)
 for r in json.loads(text): t[r["region"]]+=r["units"]*r["price"]
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Aggregate sales by region as units*price and key-sort compact JSON (scenario_9).


Submission 7DG4U8

import json
# scenario_12
def transform(text):
 d=json.loads(text);p="svc_"
 return json.dumps({k[len(p):]:v for k,v in d.items() if k.startswith(p)},separators=(",",":"))

Select 'svc_' JSON keys, strip the prefix, preserve values (scenario_12).


Submission GD84M3

import json
from collections import defaultdict
# scenario_10
def transform(text):
 t=defaultdict(int)
 for r in json.loads(text): t[r["region"]]+=r["units"]*r["price"]
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Aggregate sales by region as units*price and key-sort compact JSON (scenario_10).


Submission LUEHVE

import json
# scenario_16
def transform(text):
 n=[int(x) for x in text.split(",")];k=2
 return json.dumps([sum(n[i:i+k]) for i in range(len(n)-k+1)],separators=(",",":"))

Parse CSV integers and compute width-2 consecutive sums (scenario_16).


Submission NS4TQ3

import json
# scenario_15
def transform(text):
 d=json.loads(text);p="job_"
 return json.dumps({k[len(p):]:v for k,v in d.items() if k.startswith(p)},separators=(",",":"))

Select 'job_' JSON keys, strip the prefix, preserve values (scenario_15).


Submission PWSK7W

import json
# scenario_14
def transform(text):
 d=json.loads(text);p="ui_"
 return json.dumps({k[len(p):]:v for k,v in d.items() if k.startswith(p)},separators=(",",":"))

Select 'ui_' JSON keys, strip the prefix, preserve values (scenario_14).


Submission C2R1SL

import json
# scenario_13
def transform(text):
 d=json.loads(text);p="db_"
 return json.dumps({k[len(p):]:v for k,v in d.items() if k.startswith(p)},separators=(",",":"))

Select 'db_' JSON keys, strip the prefix, preserve values (scenario_13).


Submission Y1V34N

import json
# scenario_17
def transform(text):
 n=[int(x) for x in text.split(",")];k=3
 return json.dumps([sum(n[i:i+k]) for i in range(len(n)-k+1)],separators=(",",":"))

Parse CSV integers and compute width-3 consecutive sums (scenario_17).


Submission R44VU9

import json
# scenario_18
def transform(text):
 n=[int(x) for x in text.split(",")];k=4
 return json.dumps([sum(n[i:i+k]) for i in range(len(n)-k+1)],separators=(",",":"))

Parse CSV integers and compute width-4 consecutive sums (scenario_18).


Submission LQ1VUO

import json
# scenario_20
def transform(text):
 n=[int(x) for x in text.split(",")];k=3
 return json.dumps([sum(n[i:i+k]) for i in range(len(n)-k+1)],separators=(",",":"))

Parse CSV integers and compute width-3 consecutive sums (scenario_20).


Submission 2T95YY

import json
from collections import defaultdict
# scenario_23
def transform(text):
 t=defaultdict(int)
 for l in text.splitlines():
  k,x=l.split(":",1);t[k]+=int(x)
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Parse key:integer lines, sum repeated keys, sort keys (scenario_23).


Submission R9IYFR

import json
from collections import defaultdict
# scenario_21
def transform(text):
 t=defaultdict(int)
 for l in text.splitlines():
  k,x=l.split("=",1);t[k]+=int(x)
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Parse key=integer lines, sum repeated keys, sort keys (scenario_21).


Submission HQIU44

# scenario_26
def transform(text):
 seen=set();out=[]
 for w in text.splitlines():
  k=w.casefold()
  if k not in seen: seen.add(k);out.append(w)
 return "\n".join(out)

Alpha0
BETA
alpha0
Gamma
beta
GAMMA
Delta0

Deduplicate tokens case-insensitively, retaining first spelling/order (scenario_26).


Submission 0US7US

import json
from collections import defaultdict
# scenario_25
def transform(text):
 t=defaultdict(int)
 for l in text.splitlines():
  k,x=l.split(";",1);t[k]+=int(x)
 return json.dumps(dict(sorted(t.items())),separators=(",",":"))

Parse key;integer lines, sum repeated keys, sort keys (scenario_25).


Submission IW92M4

# scenario_27
def transform(text):
 seen=set();out=[]
 for w in text.splitlines():
  k=w.casefold()
  if k not in seen: seen.add(k);out.append(w)
 return "\n".join(out)

Alpha1
BETA
alpha1
Gamma
beta
GAMMA
Delta1

Deduplicate tokens case-insensitively, retaining first spelling/order (scenario_27).


Submission 453GNB

import json,re
# scenario_31
def transform(text):
 out=[]
 for l in text.splitlines():
  h,m,s=map(int,re.fullmatch(r"(\d+)h (\d+)m (\d+)s",l).groups());out.append(h*3600+m*60+s)
 return json.dumps(out,separators=(",",":"))

Convert required h/m/s duration lines to JSON seconds (scenario_31).


Submission T31VTH

import json,re
# scenario_32
def transform(text):
 out=[]
 for l in text.splitlines():
  h,m,s=map(int,re.fullmatch(r"(\d+)h (\d+)m (\d+)s",l).groups());out.append(h*3600+m*60+s)
 return json.dumps(out,separators=(",",":"))

Convert required h/m/s duration lines to JSON seconds (scenario_32).


Submission QWPN9A

# scenario_30
def transform(text):
 seen=set();out=[]
 for w in text.splitlines():
  k=w.casefold()
  if k not in seen: seen.add(k);out.append(w)
 return "\n".join(out)

Alpha4
BETA
alpha4
Gamma
beta
GAMMA
Delta4

Deduplicate tokens case-insensitively, retaining first spelling/order (scenario_30).


Submission NCRTQ7

# scenario_29
def transform(text):
 seen=set();out=[]
 for w in text.splitlines():
  k=w.casefold()
  if k not in seen: seen.add(k);out.append(w)
 return "\n".join(out)

Alpha3
BETA
alpha3
Gamma
beta
GAMMA
Delta3

Deduplicate tokens case-insensitively, retaining first spelling/order (scenario_29).


Submission QCQV40

import json
# scenario_36
def transform(text):
 o={"low":0,"mid":0,"high":0}
 for s in json.loads(text): o["low" if s<40 else "mid" if s<70 else "high"]+=1
 return json.dumps(o,separators=(",",":"))

Bucket scores below 40, 40-69, and >=70 (scenario_36).


Submission HUZ69U

import json,re
# scenario_34
def transform(text):
 out=[]
 for l in text.splitlines():
  h,m,s=map(int,re.fullmatch(r"(\d+)h (\d+)m (\d+)s",l).groups());out.append(h*3600+m*60+s)
 return json.dumps(out,separators=(",",":"))

Convert required h/m/s duration lines to JSON seconds (scenario_34).


Submission BHUWXD

import json,re
# scenario_35
def transform(text):
 out=[]
 for l in text.splitlines():
  h,m,s=map(int,re.fullmatch(r"(\d+)h (\d+)m (\d+)s",l).groups());out.append(h*3600+m*60+s)
 return json.dumps(out,separators=(",",":"))

Convert required h/m/s duration lines to JSON seconds (scenario_35).


Submission IZ7D9A

import json
# scenario_37
def transform(text):
 o={"low":0,"mid":0,"high":0}
 for s in json.loads(text): o["low" if s<41 else "mid" if s<71 else "high"]+=1
 return json.dumps(o,separators=(",",":"))

Bucket scores below 41, 41-70, and >=71 (scenario_37).


Submission 4C3RCC

import json
# scenario_38
def transform(text):
 o={"low":0,"mid":0,"high":0}
 for s in json.loads(text): o["low" if s<42 else "mid" if s<72 else "high"]+=1
 return json.dumps(o,separators=(",",":"))

Bucket scores below 42, 42-71, and >=72 (scenario_38).


Submission H423UO

import json
# scenario_40
def transform(text):
 o={"low":0,"mid":0,"high":0}
 for s in json.loads(text): o["low" if s<44 else "mid" if s<74 else "high"]+=1
 return json.dumps(o,separators=(",",":"))

Bucket scores below 44, 44-73, and >=74 (scenario_40).


Submission XW28C9

import json
# scenario_39
def transform(text):
 o={"low":0,"mid":0,"high":0}
 for s in json.loads(text): o["low" if s<43 else "mid" if s<73 else "high"]+=1
 return json.dumps(o,separators=(",",":"))

Bucket scores below 43, 43-72, and >=73 (scenario_39).


Submission 93M5Z5

import json
# scenario_43
def transform(text):
 d=json.loads(text);k="role"
 return json.dumps([{"id":u["id"],k:u["profile"][k]} for u in d["users"]],separators=(",",":"))

Extract id and nested profile.role from users (scenario_43).


Submission P3HB92

import json
# scenario_42
def transform(text):
 d=json.loads(text);k="city"
 return json.dumps([{"id":u["id"],k:u["profile"][k]} for u in d["users"]],separators=(",",":"))

Extract id and nested profile.city from users (scenario_42).


Submission 9K0SMU

import json
# scenario_41
def transform(text):
 d=json.loads(text);k="email"
 return json.dumps([{"id":u["id"],k:u["profile"][k]} for u in d["users"]],separators=(",",":"))

Extract id and nested profile.email from users (scenario_41).


Submission UTH0LR

import json
# scenario_44
def transform(text):
 d=json.loads(text);k="team"
 return json.dumps([{"id":u["id"],k:u["profile"][k]} for u in d["users"]],separators=(",",":"))

Extract id and nested profile.team from users (scenario_44).


Submission UHIJPS

import json
# scenario_46
def transform(text):
 r=json.loads(text);r.sort(key=lambda x:(-x["priority"],x["age"],x["name"]))
 return json.dumps([{"name":x["name"],"priority":x["priority"]} for x in r[:2]],separators=(",",":"))

Select top 2 jobs by priority desc, age/name asc (scenario_46).


Submission WC0PTO

import json
# scenario_48
def transform(text):
 r=json.loads(text);r.sort(key=lambda x:(-x["priority"],x["age"],x["name"]))
 return json.dumps([{"name":x["name"],"priority":x["priority"]} for x in r[:4]],separators=(",",":"))

Select top 4 jobs by priority desc, age/name asc (scenario_48).


Submission QQ2A77

import json
# scenario_49
def transform(text):
 r=json.loads(text);r.sort(key=lambda x:(-x["priority"],x["age"],x["name"]))
 return json.dumps([{"name":x["name"],"priority":x["priority"]} for x in r[:2]],separators=(",",":"))

Select top 2 jobs by priority desc, age/name asc (scenario_49).


Submission LMT5LO

import json
# scenario_50
def transform(text):
 r=json.loads(text);r.sort(key=lambda x:(-x["priority"],x["age"],x["name"]))
 return json.dumps([{"name":x["name"],"priority":x["priority"]} for x in r[:3]],separators=(",",":"))

Select top 3 jobs by priority desc, age/name asc (scenario_50).


Submission DMU169

def transform(text):
    totals = {}
    for line in text.strip().split('\n'):
        sku, qty, price = line.split(':')
        totals[sku] = totals.get(sku, 0.0) + int(qty) * float(price)
    ordered = sorted(totals.items(), key=lambda kv: (-kv[1], kv[0]))
    return '\n'.join(f'{sku}={total:.2f}' for sku, total in ordered)

Each line is 'sku:quantity:unit_price'. Compute the total revenue per SKU (quantity * unit_price summed across lines) and return lines of 'sku=total' formatted to 2 decimal places, sorted by total descending, then sku ascending.


Submission 95UZCI

def transform(text):
    counts = {}
    for line in text.strip().split('\n'):
        parts = line.split()
        if len(parts) >= 2 and parts[1] == 'ERROR':
            counts[parts[0]] = counts.get(parts[0], 0) + 1
    rows = ['date,errors'] + [f'{d},{counts[d]}' for d in sorted(counts)]
    return '\n'.join(rows)

2026-01-15 ERROR db timeout
2026-01-15 INFO started
2026-01-16 ERROR disk full
2026-01-16 ERROR db timeout
2026-01-17 WARN slow query

Count ERROR lines per date and return a CSV string with header 'date,errors', one row per date that has at least one ERROR, sorted by date ascending.


Submission RUJZOD

import json

def transform(text):
    users = json.loads(text)
    tag_map = {}
    for user in users:
        for tag in set(user['tags']):
            tag_map.setdefault(tag, []).append(user['name'])
    return json.dumps({t: sorted(tag_map[t]) for t in sorted(tag_map)})

Given a JSON array of users, return a JSON object mapping each distinct tag to the sorted list of user names that carry it. Ignore duplicate tags within a single user. Tags in the result must be sorted alphabetically.


Submission M3MYNF

import csv, io, json

def transform(text):
    totals = {}
    for row in csv.DictReader(io.StringIO(text.strip())):
        region = row['region']
        totals[region] = totals.get(region, 0.0) + float(row['amount'])
    return json.dumps({k: round(totals[k], 2) for k in sorted(totals)})

id,region,amount
1,north,120.50
2,south,80
3,north,45.25
4,east,200
5,south,19.75

Parse the CSV and return a JSON object mapping each region to its total amount (as a float), with regions sorted alphabetically.


Submission 5XX2H9

def transform(text):
    seen = []
    for part in text.strip().split(';'):
        email = part.strip().lower()
        if email and email not in seen:
            seen.append(email)
    return '\n'.join(seen)

alice@example.com;  Bob.Smith@Test.ORG ;carol@example.com;bob.smith@test.org;dan@sample.net

alice@example.com
bob.smith@test.org
carol@example.com
dan@sample.net

Split the semicolon-separated email list, trim whitespace, lowercase every address, remove duplicates while keeping first-seen order, and return them joined by newlines.


Submission SQ7R6H

import json

def transform(text):
    def flatten(obj, prefix=''):
        out = {}
        for k, v in obj.items():
            key = f'{prefix}.{k}' if prefix else k
            if isinstance(v, dict):
                out.update(flatten(v, key))
            else:
                out[key] = v
        return out
    flat = flatten(json.loads(text))
    return json.dumps({k: flat[k] for k in sorted(flat)})

Flatten the nested JSON object into a single-level JSON object whose keys are dot-joined paths (e.g. 'config.server.host'). Keys in the result must be sorted alphabetically.


Submission W3PP5E

import json, re
from collections import Counter

def transform(text):
    words = re.findall(r'[a-z]+', text.lower())
    counts = Counter(words)
    top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
    return json.dumps(dict(top))

The quick brown fox. The lazy dog! A quick test? The FOX runs.

Return a JSON object with the three most frequent words (case-insensitive, punctuation stripped), mapping word to count; break count ties alphabetically.


Submission NJXZJW

import json

def transform(text):
    readings = json.loads(text)
    out = [{'ts': r['ts'], 'temp_c': round((r['temp_f'] - 32) * 5 / 9, 1)} for r in readings]
    return json.dumps(out)

Convert each reading's temp_f (Fahrenheit) to Celsius rounded to 1 decimal, rename the key to temp_c, keep ts unchanged, and return the JSON array.


Submission 0GVZ6G

import json
from collections import Counter

def transform(text):
    nums = [int(x) for x in text.strip().split(',')]
    counts = Counter(nums)
    top = max(counts.values())
    mode = min(v for v, c in counts.items() if c == top)
    return json.dumps({'min': min(nums), 'max': max(nums), 'mean': round(sum(nums) / len(nums), 2), 'mode': mode, 'distinct': len(counts)})

Parse the comma-separated integers and return a JSON object with keys 'min', 'max', 'mean' (rounded to 2 decimals), 'mode' (smallest value if tied), and 'distinct' (count of unique values).


Submission JHA7T7

import json

def transform(text):
    data = json.loads(text)['employees']
    groups = {}
    for e in data:
        groups.setdefault(e['dept'], []).append(e['salary'])
    return json.dumps({d: {'count': len(s), 'avg_salary': round(sum(s) / len(s))} for d, s in sorted(groups.items())})

Group employees by dept and return a JSON object mapping dept to {'count': n, 'avg_salary': average rounded to nearest integer}, with depts sorted alphabetically.


Submission E6FWJC

import json

def transform(text):
    lines = text.strip().split('\n')[1:]
    result = {}
    section = None
    for line in lines:
        line = line.strip()
        if line.startswith('[') and line.endswith(']'):
            section = line[1:-1]
            result[section] = {}
        elif '=' in line and section is not None:
            k, v = line.split('=', 1)
            result[section][k.strip()] = v.strip()
    return json.dumps(result)

INI
[database]
host = db.internal
port = 5432
[cache]
host = cache.internal
ttl = 300

Skip the first line, parse the INI-style sections and key = value pairs, and return a JSON object of {section: {key: value}} with all values kept as strings. Preserve section and key order as they appear.


Submission CDAFQB

from collections import Counter

def transform(text):
    paths = [line.split('?')[0] for line in text.strip().split('\n')]
    counts = Counter(paths)
    ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
    return '\n'.join(f'{p} {c}' for p, c in ordered)

/api/users?page=2
/api/users?page=3
/api/orders
/api/users?page=2
/health
/api/orders

Strip query strings from each request path, count hits per bare path, and return lines of 'path count' sorted by count descending then path ascending.


Submission BJFMFQ

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', '') == ''
        result.append(row)
    return json.dumps(result)

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.


Submission Z3VIF3

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())
        avg = round(sum(scores) / len(scores), 1)
        result.append({'name': student['name'], 'average': avg, 'grade': grade(avg)})
    return json.dumps(result)

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.


Submission ACACE2

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, salaries in dept_salaries.items()}
    return json.dumps(result)

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.


Submission 5838CO

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']),
            'name': row['name'],
            'price': price,
            'quantity': qty,
            'total_value': round(price * qty, 2)
        })
    return json.dumps(result)

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

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.


Submission 5T90L5

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(',')
        amount = float(amount)
        if txtype == 'credit':
            balance += amount
        else:
            balance -= amount
        writer.writerow([date, f'{amount:.2f}', txtype, f'{round(balance, 2):.2f}'])
    return out.getvalue().strip()

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.


Submission Y9FZZC

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['away_team']
        else:
            winner = 'draw'
        result.append({'home_team': row['home_team'], 'away_team': row['away_team'], 'winner': winner})
    return json.dumps(result)

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

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.


Submission Y7R0ZA

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)

Extract only ERROR-level log entries and return them as a JSON array, keeping only the 'msg' and 'ts' fields.


Submission 9WAQKX

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])
    return out.getvalue().strip()

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.


Submission 6BUOH6

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

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.


Submission NUS9IF

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!
python programming
data science and AI
strip 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.


Submission 0CNGV0

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_oldest[city][0] or (year == city_oldest[city][0] and name < city_oldest[city][1]):
            city_oldest[city] = (year, name)
    return json.dumps({city: info[1] for city, info in city_oldest.items()})

name,birth_year,city
Alice,1990,Seattle
Bob,1985,Portland
Carol,1992,Seattle
Dave,1988,Portland
Eve,1995,Seattle

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.


Submission JYQO9B

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]))
    return json.dumps(sorted_groups)

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.


Submission 25HPCI

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.items():
        result[sid] = {
            'min': round(min(temps), 2),
            'max': round(max(temps), 2),
            'avg': round(sum(temps) / len(temps), 2)
        }
    return json.dumps(result)

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.


Submission C1R7T7

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))

From shipped orders only, collect all unique items across all such orders, sort them alphabetically, and return a JSON array of those item names.


Submission NHOZGK

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):
            end = d
        else:
            ranges.append({'start': start.isoformat(), 'end': end.isoformat()})
            start = end = d
    ranges.append({'start': start.isoformat(), 'end': end.isoformat()})
    return json.dumps(ranges)

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.


Submission NQOFR0

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())}
    return json.dumps(result)

Invert the tag-to-product mapping: return a JSON object where each tag maps to a sorted list of SKUs that have that tag.


Submission ZZOO6W

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):
    data = json.loads(text.strip())
    flat = flatten(data['config'])
    return json.dumps(flat)

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'.


Submission OBBV4M

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 = int(row['duration_seconds'])
        user_data[uid]['total_duration'] += dur
        if action not in user_data[uid]['actions']:
            user_data[uid]['actions'].append(action)
    result = [{'user_id': uid, 'total_duration': info['total_duration'], 'actions': info['actions']}
              for uid, info in sorted(user_data.items())]
    return json.dumps(result)

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

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.


Submission EID7LY

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 = io.StringIO()
    writer = csv.DictWriter(out, fieldnames=cols)
    writer.writeheader()
    for row in rows:
        norm_row = {}
        for c in cols:
            v = float(row[c])
            mn, mx = col_min[c], col_max[c]
            norm_row[c] = round((v - mn) / (mx - mn), 4) if mx != mn else 0.0
        writer.writerow(norm_row)
    return out.getvalue().strip()

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.


Submission DBAVC4

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(val) else val
    return json.dumps(result)

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).


Submission S1X7QZ

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_odds': len(odds)
    })

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.


Submission Y7P97B

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()
        })
    return json.dumps(result)

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

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.


Submission FWUK5H

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': s['step'], 'duration_seconds': dur})
    longest = max(steps, key=lambda x: x['duration_seconds'])['step']
    return json.dumps({'steps': steps, 'longest_step': longest})

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).


Submission GIZGJ1

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
        margin = round(profit / revenue * 100, 1)
        region_data[row['region']].append({
            'quarter': row['report_date'],
            'profit': profit,
            'profit_margin_pct': margin
        })
    return json.dumps(dict(region_data))

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.


Submission IZWR49

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())}
    return json.dumps(result)

apple
banana
apricot
avocado
blueberry
cherry
blackberry
cantaloupe

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.


Submission MKD90C

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 else result

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 '. '.


Submission SEN9O3

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(f'{n}: {a}' for n, a in rows)

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.


Submission 6LHBPK

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))

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.


Submission 8N1CS2

def transform(text):
    nums = sorted(set(int(x.strip()) for x in text.strip().split(',')))
    return ','.join(str(n) for n in nums)

Given a comma-separated list of numbers, return the numbers sorted in ascending order with duplicates removed, as a comma-separated string.


Submission 9QLJEF

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)))
    return json.dumps(rows)

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.


Submission 3PZVDV

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 json.dumps(dict(counts))

src/app.py
src/utils.py
README
docs/guide.md
bin/run
src/test.py

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'.


Submission SPC1HY

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

Parse a semicolon-separated list of 'name=value' pairs (like a cookie header) into a JSON object, trimming whitespace around names and values.


Submission 1IFG1C

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)

Convert a duration string like '2h30m15s' (any subset of hours/minutes/seconds) into total seconds as an integer string.


Submission URI4L5

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(v)
        except ValueError:
            pass
        result[k] = v
    return json.dumps(result)

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.


Submission 9VXEKZ

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)

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.


Submission GO826H

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.append(a - b)
            elif tok == '*':
                stack.append(a * b)
            else:
                stack.append(int(math.trunc(a / b)))
        else:
            stack.append(int(tok))
    return str(stack[0])

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).


Submission HSKMFZ

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: round(v, 2) for k, v in totals.items()})

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.


Submission Z25YMX

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)

Given a list of integers one per line, compute the running maximum after each element and output as a comma-separated string.


Submission 9RYCED

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 = n, 1
    groups.append((current, count))
    return ' '.join(f'{c}x{v}' for v, c in groups)

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).


Submission OMRAKY

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 json.dumps(result)

Convert a nested JSON object into a flattened single-level JSON object using dot notation for nested keys.


Submission MJBL3Z

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

Parse a simple Markdown unordered list (lines starting with '- ') and return a JSON array of the item strings, ignoring non-list lines.