Submission 2GK6SY

def transform(text):
    import json
    records = []
    for rec in text.split(';'):
        rec = rec.strip()
        if not rec:
            continue
        fields = rec.split('|')
        d = {}
        for f in fields:
            k, v = f.split(':', 1)
            k = k.strip()
            if k == 'scores':
                d[k] = [int(x) for x in v.split(',')]
            elif k == 'id':
                d[k] = int(v)
            else:
                d[k] = v.strip()
        records.append(d)
    return json.dumps(records)

This text encodes student records separated by ';', with fields inside each record separated by '|' as key:value pairs. The 'scores' field is a comma-separated list of integers and 'id' is an integer. Parse this into a JSON array of objects with properly typed fields.


Submission IGX5FJ

def transform(text):
    import csv, io
    rows = []
    keys_order = []
    for line in text.strip().splitlines():
        fields = line.split('|')
        d = {}
        for f in fields:
            k, v = f.split('=', 1)
            d[k] = v
            if k not in keys_order:
                keys_order.append(k)
        rows.append(d)
    out = io.StringIO()
    writer = csv.DictWriter(out, fieldnames=keys_order, lineterminator='\n')
    writer.writeheader()
    for r in rows:
        writer.writerow(r)
    return out.getvalue()

This log has one event per line, with pipe-separated key=value fields. Extract the fields from every line and convert the whole log into standard CSV text, using the key names from the first line as column headers, in the order they first appear.


Submission A9EG68

def transform(text):
    import json
    from collections import Counter
    counts = Counter()
    for line in text.strip().splitlines():
        if not line.strip():
            continue
        obj = json.loads(line)
        level = obj.get('level', 'INFO')
        counts[level] += 1
    return json.dumps(dict(sorted(counts.items())))

{"msg": "start", "level": "INFO"}
{"msg": "disk low", "level": "WARNING"}
{"msg": "oops"}
{"msg": "crash", "level": "ERROR"}
{"msg": "another warn", "level": "WARNING"}
{"msg": "ok"}

This is a JSON Lines (JSONL) log where each line is an independent JSON object with a 'msg' field and an optional 'level' field. Entries missing 'level' should be treated as 'INFO'. Count how many entries fall into each level and return a JSON object mapping level name to count, with keys sorted alphabetically.


Submission XE597X

def transform(text):
    import json
    seen = []
    seen_set = set()
    for line in text.splitlines():
        line = line.strip()
        if not line:
            continue
        normalized = ' '.join(line.split()).title()
        if normalized not in seen_set:
            seen_set.add(normalized)
            seen.append(normalized)
    return json.dumps(seen)

  ALICE johnson
Bob   SMITH
alice Johnson
	CAROL  white
BOB smith

Each line is a person's name with inconsistent capitalization and irregular internal/leading/trailing whitespace (tabs, multiple spaces). Normalize each name to Title Case with single spaces between words, remove duplicate names (case-insensitive after normalization), and return a JSON array of the unique names in their first-seen order.


Submission QQYRZ0

def transform(text):
    import csv, io, json
    reader = csv.reader(io.StringIO(text), delimiter='\t')
    rows = list(reader)
    header = rows[0]
    data_rows = rows[1:]
    result = []
    for row in data_rows:
        merged = {}
        for h, v in zip(header, row):
            if h not in merged:
                merged[h] = v
            elif merged[h] == '' and v != '':
                merged[h] = v
        result.append(merged)
    return json.dumps(result)

id	name	name	email
1	Alice		a@example.com
2		Bob	b@example.com

This is tab-separated data whose header row contains a duplicated column name ('name' appears twice, representing two data-entry attempts for the same field). For each row, merge the duplicate columns by keeping the first non-empty value among them. Return a JSON array of objects with one 'name' key per row (duplicate columns collapsed).


Submission 3D4IEQ

def transform(text):
    import csv, io, json
    from datetime import datetime
    formats = ["%m/%d/%Y", "%Y-%m-%d", "%d-%b-%Y"]
    reader = csv.DictReader(io.StringIO(text))
    result = []
    for row in reader:
        d = dict(row)
        raw = row['signup_date'].strip()
        parsed = None
        if raw:
            for fmt in formats:
                try:
                    parsed = datetime.strptime(raw, fmt).strftime("%Y-%m-%d")
                    break
                except ValueError:
                    continue
        d['signup_date'] = parsed
        result.append(d)
    return json.dumps(result)

Parse this CSV of user signups whose 'signup_date' column mixes MM/DD/YYYY, YYYY-MM-DD, and DD-Mon-YYYY formats, with some rows missing the date entirely. Normalize every present date to ISO 8601 (YYYY-MM-DD) and use null for missing dates. Return a JSON array of the row objects with the normalized 'signup_date' field.


Submission EA6IC2

def transform(text):
    import json
    tree = {}
    for line in text.strip().splitlines():
        parts = [p.strip() for p in line.split('>')]
        node = tree
        for p in parts:
            node = node.setdefault(p, {})
    return json.dumps(tree)

Home > Electronics > Phones > Smartphones
Home > Electronics > Laptops
Home > Garden > Tools
Home > Electronics > Phones > Accessories

Each line is a category breadcrumb path with segments separated by '>'. Merge all the paths into a single nested tree structure where each category name maps to an object of its child categories (leaf categories map to an empty object). Return the tree as a JSON object.


Submission YAH7BG

def transform(text):
    import json
    result = {}
    for line in text.strip().splitlines():
        line = line.strip()
        if not line.startswith('export '):
            continue
        line = line[len('export '):]
        key, val = line.split('=', 1)
        val = val.strip()
        if val.startswith('"') and val.endswith('"'):
            result[key] = val[1:-1]
            continue
        if val.lower() in ('true', 'false'):
            result[key] = val.lower() == 'true'
            continue
        if ',' in val:
            result[key] = val.split(',')
            continue
        try:
            result[key] = float(val) if '.' in val else int(val)
        except ValueError:
            result[key] = val
    return json.dumps(result)

export DEBUG=true
export MAX_RETRIES=5
export TIMEOUT=30.0
export APP_NAME="My App"
export FEATURE_FLAGS=beta,new_ui,dark_mode

Parse these shell-style 'export KEY=VALUE' lines into a single JSON object. Coerce 'true'/'false' to booleans, plain integers and decimals to numbers, strip surrounding double quotes from quoted string values, and split comma-separated values (with no quotes) into a JSON array of strings. Return the resulting JSON object.


Submission BPNL59

def transform(text):
    versions = [v.strip() for v in text.split(',') if v.strip()]
    versions.sort(key=lambda v: tuple(int(p) for p in v.split('.')))
    return ', '.join(versions)

Sort semantic version strings in ascending order by numeric component (so 1.10.0 comes after 1.9.2) and return them comma-separated.


Submission DUXQ69

def transform(text):
    lines = [l for l in text.strip().split('\n') if l.strip()]
    rows = [l.split('\t') for l in lines[1:]]
    metrics = sorted({r[1] for r in rows})
    dates = []
    table = {}
    for date, metric, value in rows:
        if date not in table:
            table[date] = {}
            dates.append(date)
        table[date][metric] = value
    out = ['\t'.join(['date'] + metrics)]
    for date in dates:
        out.append('\t'.join([date] + [table[date].get(m, '0') for m in metrics]))
    return '\n'.join(out)

Pivot long-format 'date\tmetric\tvalue' TSV into wide TSV with a header row of 'date' plus each metric sorted alphabetically. Missing combinations become 0.


Submission 669SY9

import re

def transform(text):
    units = {'h': 3600, 'm': 60, 's': 1}
    out = []
    for line in text.split('\n'):
        spec = line.strip()
        if not spec:
            continue
        total = 0
        for amount, unit in re.findall(r'(\d+)([hms])', spec):
            total += int(amount) * units[unit]
        out.append('{}={}'.format(spec, total))
    return '\n'.join(out)

Parse compact duration strings like '1h30m', '45s', '2h', '3m10s' into total seconds and return 'original=seconds' lines in the input order.


Submission VGLT7O

import re

def transform(text):
    entries = []
    for line in text.split('\n'):
        match = re.match(r'^(#+)\s+(.*)$', line.strip())
        if match:
            entries.append((len(match.group(1)), match.group(2).strip()))
    if not entries:
        return ''
    base = min(level for level, _ in entries)
    out = []
    for level, title in entries:
        slug = re.sub(r'[^a-z0-9]+', '-', title.lower()).strip('-')
        out.append('{}- {} (#{})'.format('  ' * (level - base), title, slug))
    return '\n'.join(out)

# Getting Started
some text
## Install & Setup
### Windows Notes
## FAQ

- Getting Started (#getting-started)
  - Install & Setup (#install-setup)
    - Windows Notes (#windows-notes)
  - FAQ (#faq)

Build a table of contents from Markdown ATX headings: indent two spaces per level below the top level found, and render each as '- <title> (#<slug>)' with a lowercase hyphen slug.


Submission QNWK0W

import re

def transform(text):
    out = []
    for line in text.split('\n'):
        raw = line.strip()
        if not raw:
            continue
        digits = re.sub(r'\D', '', raw)
        if len(digits) == 11 and digits.startswith('1'):
            digits = digits[1:]
        if len(digits) != 10:
            out.append('INVALID:{}'.format(raw))
        else:
            out.append('+1-{}-{}-{}'.format(digits[:3], digits[3:6], digits[6:]))
    return '\n'.join(out)

Normalize phone numbers to '+1-XXX-XXX-XXXX' when they have exactly 10 digits (or 11 starting with 1); otherwise emit 'INVALID:<original>'. One result per input line.


Submission 7R5QI9

def transform(text):
    seen = set()
    kept = []
    for line in text.split('\n'):
        addr = line.strip()
        if not addr:
            continue
        key = addr.lower()
        if key in seen:
            continue
        seen.add(key)
        kept.append(addr)
    return '\n'.join(kept + ['count={}'.format(len(kept))])

Ana@Example.com
bob@example.com
ANA@example.com
carl@Example.COM
bob@Example.com

Ana@Example.com
bob@example.com
carl@Example.COM
count=3

Deduplicate a newline-separated list of email addresses case-insensitively, keeping the first spelling seen, and return them one per line followed by a final 'count=N' line.


Submission ABMML1

def transform(text):
    cells = {}
    max_row = max_col = 0
    for line in text.split('\n'):
        if not line.strip():
            continue
        row, col, value = [p.strip() for p in line.split(',')]
        row, col = int(row), int(col)
        cells[(row, col)] = value
        max_row = max(max_row, row)
        max_col = max(max_col, col)
    grid = []
    for r in range(max_row + 1):
        grid.append(' '.join(cells.get((r, c), '.') for c in range(max_col + 1)))
    return '\n'.join(grid)

Convert 'row,col,value' triplets into a dense space-separated grid sized to the maximum row and column present, filling absent cells with '.'.


Submission PAJZ16

import json

def transform(text):
    rows = []
    for line in text.split('\n'):
        if not line.strip():
            continue
        rows.append({
            'sku': line[0:7].strip(),
            'name': line[7:20].strip(),
            'qty': int(line[20:].strip()),
        })
    return json.dumps(rows)

A1001  widget bolt  42
A1002  hex nut      7
A1003  washer plate 115

Parse fixed-width records (cols 0-6 sku, 7-19 name, 20-end qty) into a JSON array of objects with keys sku, name, qty (qty as integer). Trim padding whitespace; skip blank lines.


Submission RNHN15

import json

def transform(text):
    result = {}
    section = None
    for raw in text.split('\n'):
        line = raw.strip()
        if not line or line.startswith(';'):
            continue
        if line.startswith('[') and line.endswith(']'):
            section = line[1:-1]
            result[section] = {}
            continue
        key, _, value = line.partition('=')
        key = key.strip()
        value = value.strip()
        if value in ('true', 'false'):
            coerced = value == 'true'
        elif value.lstrip('-').isdigit():
            coerced = int(value)
        else:
            coerced = value
        result[section][key] = coerced
    return json.dumps(result)

; deployment
[server]
host = localhost
port = 8080
debug = false

[cache]
ttl = 300
name = edge-1

Parse an INI-style config into nested JSON by section. Coerce 'true'/'false' to booleans and bare integers to numbers; leave everything else as a string. Ignore ';' comment lines.


Submission UUZ5KF

import csv, io

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    totals = {}
    for row in reader:
        totals[row['region']] = totals.get(row['region'], 0) + int(row['amount'])
    ordered = sorted(totals.items(), key=lambda kv: (-kv[1], kv[0]))
    return '\n'.join('{}={}'.format(k, v) for k, v in ordered)

region,amount
north,120
south,80
north,45
east,80
south,20

Read CSV with headers region,amount and return lines 'region=total' sorted by descending total then ascending region name. Totals are integers.


Submission F8TQHA

import csv, io, json

def transform(text):
    rows = json.loads(text)
    keys = sorted({k for row in rows for k in row})
    out = io.StringIO()
    writer = csv.DictWriter(out, fieldnames=keys, restval='', lineterminator='\n')
    writer.writeheader()
    for row in rows:
        writer.writerow(row)
    return out.getvalue().strip()

id,name,note
1,"Ada, R.","said ""hi"""
2,Bo,

Convert a JSON array of objects into CSV. Use the union of all keys sorted alphabetically as the header, leave missing values empty, and quote fields per standard CSV rules.


Submission KC1AIO

def transform(text):
    nums = sorted({int(p) for p in text.split(',') if p.strip()})
    parts = []
    start = prev = nums[0]
    for value in nums[1:] + [None]:
        if value is not None and value == prev + 1:
            prev = value
            continue
        parts.append(str(start) if start == prev else '{}-{}'.format(start, prev))
        if value is not None:
            start = prev = value
    return ','.join(parts)

Collapse a comma-separated list of integers into sorted ranges: consecutive runs become 'start-end', isolated values stay bare, joined by commas.


Submission 9GFEZA

import json

def transform(text):
    data = json.loads(text)
    before, after = data['before'], data['after']
    lines = []
    for key in sorted(set(before) | set(after)):
        if key not in before:
            lines.append('added {} {}'.format(key, after[key]))
        elif key not in after:
            lines.append('removed {} {}'.format(key, before[key]))
        elif before[key] != after[key]:
            lines.append('changed {} {}->{}'.format(key, before[key], after[key]))
    return '\n'.join(lines)

changed b 20->25
removed c 30
added d 40

Given a JSON object with 'before' and 'after' maps of id->price, report changes as sorted lines: 'added id price', 'removed id price', or 'changed id old->new'. Skip unchanged ids.


Submission 440VO1

import json

def transform(text):
    data = json.loads(text)
    flat = {}
    def walk(node, prefix):
        if isinstance(node, dict):
            for key, value in node.items():
                walk(value, prefix + '.' + key if prefix else key)
        elif isinstance(node, list):
            for index, value in enumerate(node):
                walk(value, '{}.{}'.format(prefix, index))
        else:
            flat[prefix] = node
    walk(data, '')
    return json.dumps(flat, sort_keys=True)

Flatten a nested JSON object into dotted key paths, indexing list elements numerically, and return the result as a JSON object with keys sorted alphabetically.


Submission LW9S28

def transform(text):
    s = text.strip()
    out = []
    index = 0
    while index < len(s):
        run = 1
        while index + run < len(s) and s[index + run] == s[index]:
            run += 1
        if run >= 3:
            out.append('{}{}'.format(run, s[index]))
        else:
            out.append(s[index] * run)
        index += run
    return ''.join(out)

Run-length encode a string, but only collapse runs of 3 or more characters into '<count><char>'; shorter runs are emitted literally.


Submission BT2AMC

import json

def transform(text):
    out={}
    for part in text.strip().split(','):
        k,v=part.split('=',1); out[k]=int(v)
    return json.dumps(out)

Parse comma-separated key=value pairs and return a JSON object with integer values.


Submission 3SNUGU

import json
from collections import Counter

def transform(text):
    return json.dumps(dict(Counter(text.split())))

Count whitespace-separated tokens and return a JSON object of token frequencies.


Submission IYMQGL

import json

def transform(text):
    return json.dumps({k:float(v) for k,v in (line.split(',') for line in text.strip().splitlines())})

Convert label,value rows into a JSON object with floating-point values.


Submission SKQVIO

import csv,io,json

def transform(text):
    rows=list(csv.DictReader(io.StringIO(text)))
    for r in rows:r['id']=int(r['id'])
    return json.dumps(rows)

Convert a two-column CSV with header into a JSON array of records, converting id to integer.


Submission YBPGNY

import json

def transform(text):
    m=[[int(x) for x in line.split()] for line in text.strip().splitlines()]
    return json.dumps([sum(col) for col in zip(*m)])

Parse a whitespace-separated integer matrix and return its column sums as a JSON array.


Submission GIBAV2

import json

def transform(text):
    return json.dumps([line.strip().lower() for line in text.splitlines() if line.strip()])

Trim each line, remove blank lines, lowercase the remaining values, and return a JSON array.


Submission DSN6ON

import json

def transform(text):
    return json.dumps([int(a)-int(b) for a,b in (line.split(',') for line in text.strip().splitlines())])

For each comma-separated gross,discount row, compute net=gross-discount and return nets as a JSON array.


Submission 45LNQN

import json

def transform(text):
    obj=json.loads(text)
    return json.dumps([u['name'] for u in obj['users'] if u['active']])

Parse the JSON and return a JSON array containing names of active users.


Submission 8OH7AB

import json

def transform(text):
    rows=[line.split(',') for line in text.strip().splitlines()]
    return json.dumps([list(col) for col in zip(*rows)])

Transpose comma-separated rows and return the transposed matrix as JSON.


Submission SD1UBV

import csv,io,json

def transform(text):
    rows=csv.DictReader(io.StringIO(text))
    return json.dumps([r['first_name']+' '+r['last_name'] for r in rows])

Convert CSV rows into full-name strings and return them as a JSON array.


Submission 3TKIVX

import json

def transform(text):
    out=[]
    for line in text.strip().splitlines():
        k,v=line.split('='); out.extend([k]*int(v))
    return json.dumps(out)

Parse key=count lines and expand them into a JSON array repeating each key count times, preserving input key order.


Submission 91LQHV

import json

def transform(text):
    total=0; out=[]
    for x in map(int,text.split(',')):
        total+=x; out.append(total)
    return json.dumps(out)

Convert comma-separated integers into cumulative sums and return them as a JSON array.


Submission XNJOAE

import json

def transform(text):
    out={}
    for line in text.strip().splitlines():
        k,a,b=line.split(); out[k]=max(int(a),int(b))
    return json.dumps(out)

For each whitespace-separated label,x,y row, return a JSON object mapping label to the larger integer.


Submission SKNIAU

import json
from collections import Counter

def transform(text):
    c=Counter(text.split(','))
    return json.dumps(sorted(c,key=lambda k:(-c[k],k)))

Return a JSON array of tokens sorted by decreasing frequency and then alphabetically.


Submission CPXD7M

import json

def transform(text):
    out={}
    for line in text.strip().splitlines():
        k,v=line.split(':',1); v=v.strip(); out[k.strip()]= True if v=='true' else False if v=='false' else v
    return json.dumps(out)

name: Ada Lovelace
role: Engineer
active: true

Parse colon-separated lines into a JSON object, converting true/false values to booleans.


Submission 289YEZ

import json

def transform(text):
    nums=[int(x) for x in text.split(',') if x]
    return json.dumps({'count':len(nums),'sum':sum(nums),'min':min(nums),'max':max(nums)})

Parse comma-separated integers and return a JSON object containing count, sum, minimum, and maximum.


Submission V9VRHJ

import json

def transform(text):
    rows=[]
    for line in text.strip().splitlines():
        name,score=line.split('|'); rows.append({'name':name,'score':int(score)})
    return json.dumps(rows)

Convert pipe-delimited name-score rows into a JSON array of objects with score as an integer.


Submission RFGSQ5

import json
from collections import defaultdict

def transform(text):
    d=defaultdict(int)
    for line in text.strip().splitlines():
        day,val=line.split(','); d[day]+=int(val)
    return json.dumps(dict(d))

Aggregate comma-separated date,value rows by date and return summed values as JSON.


Submission Y7IN63

import json

def transform(text):
    return json.dumps([w for w in text.split() if len(w)>=4])

Return a JSON array containing only words with length at least four, preserving order.


Submission YPMVY3

import json

def transform(text):
    seen=set(); out=[]
    for line in text.strip().splitlines():
        if line not in seen: seen.add(line); out.append(line)
    return json.dumps(out)

Return a JSON array of unique lines in first-seen order.


Submission B8QHFE

import json

def transform(text):
    rows=[line.split(':',1) for line in text.strip().splitlines()]
    rows.sort(key=lambda x:int(x[0]))
    return json.dumps([v for _,v in rows])

Sort colon-separated priority:text rows by numeric priority and return only the text values as JSON array.


Submission RL4IO6

import json

def transform(text):
    s=text.strip(); out=[]
    for ch in s:
        if out and out[-1][0]==ch: out[-1][1]+=1
        else: out.append([ch,1])
    return json.dumps(out)

Run-length encode the input string as a JSON array of [character,count] pairs.


Submission 1G7YFE

import json

def transform(text):
    nums=[int(x) for x in text.splitlines() if x.strip()]
    return json.dumps({'negative':[x for x in nums if x<0],'zero':[x for x in nums if x==0],'positive':[x for x in nums if x>0]})

Partition newline-separated integers into negative, zero, and positive arrays in JSON.


Submission RQHIQ3

import json
from collections import defaultdict

def transform(text):
    d=defaultdict(float)
    for line in text.strip().splitlines():
        k,v=line.split(':'); d[k]+=float(v)
    return json.dumps({k:round(v,2) for k,v in d.items()})

Aggregate currency:value lines by currency and return totals rounded to two decimals in JSON.


Submission CB51AD

import json
from collections import defaultdict

def transform(text):
    d=defaultdict(list)
    for line in text.strip().splitlines():
        i,c=line.split(','); d[c].append(i)
    return json.dumps(dict(d))

Group first-column IDs by second-column category and return a JSON object mapping category to ID arrays.


Submission EN7JXP

import json

def transform(text):
    vals=[float(x) for x in text.splitlines() if x.strip()]
    return json.dumps({'mean':round(sum(vals)/len(vals),2),'count':len(vals)})

Parse newline-separated floats and return a JSON object with the rounded arithmetic mean and count.


Submission 2CQ8YA

import json

def transform(text):
    pairs=[part.split(':') for part in text.strip().split(';')]
    pairs.sort(key=lambda kv:(-int(kv[1]),kv[0]))
    return json.dumps([k for k,_ in pairs])

Parse semicolon-separated key:value entries and return keys sorted by descending numeric value as a JSON array.


Submission T0LOT7

import json
from datetime import datetime

def transform(text):
    ts=[datetime.fromisoformat(x.replace('Z','+00:00')) for x in text.strip().splitlines()]
    return json.dumps([int((ts[i+1]-ts[i]).total_seconds()) for i in range(len(ts)-1)])

Parse ISO timestamps and return elapsed seconds between each adjacent pair as a JSON array.


Submission EGMAWC

import json
from collections import defaultdict

def transform(text):
    d=defaultdict(list)
    for line in text.strip().splitlines():
        k,v=line.split('='); d[k].append(int(v))
    return json.dumps(dict(d))

Parse repeated key=value lines and return a JSON object mapping each key to an array of integer values.


Submission 4IFKTI

import csv, io, json

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    return json.dumps([dict(row) for row in reader])

Parse CSV text with a header row and return a JSON array of objects, one per data row, with values kept as strings.


Submission 7ICGTN

def transform(text):
    def camel(s):
        parts = s.split('_')
        return parts[0] + ''.join(p.capitalize() for p in parts[1:])
    return '\n'.join(camel(l) for l in text.strip().split('\n'))

Convert a snake_case identifier list (one per line) into camelCase, returned as a newline-separated string in the same order.


Submission MX9LSV

import json

def transform(text):
    d = {}
    for line in text.strip().split('\n'):
        if ':' in line:
            k, v = line.split(':', 1)
            d[k.strip()] = v.strip()
    return json.dumps(d)

host: localhost
port: 8080
host: 127.0.0.1
debug: true

Given lines of 'key: value' pairs, return them as a JSON object. If a key repeats, the last value wins.


Submission QPCP4Q

import json

def transform(text):
    line = text.rstrip('\n')
    return json.dumps({'name': line[0:10].strip(), 'age': line[10:13].strip(), 'city': line[13:].strip()})

Given a fixed-width record where columns are at positions 0-9 (name), 10-12 (age), 13+ (city), return a JSON object with those three trimmed fields.


Submission UXWPUO

import json
from collections import Counter

def transform(text):
    words = text.strip().lower().split()
    c = Counter(words)
    return json.dumps({k: c[k] for k in sorted(c)})

Given a block of text, return a JSON object mapping each distinct word (lowercased, split on whitespace) to its count, with keys sorted alphabetically.


Submission 1K7H42

import json

def transform(text):
    out = []
    total = 0.0
    for l in text.strip().split('\n'):
        total += float(l)
        out.append(round(total, 1))
    return json.dumps(out)

Given newline-separated floats, return a JSON array of the running (cumulative) sum after each value, each rounded to one decimal place.


Submission ZP16JR

import json, io, csv

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()), delimiter='\t')
    out = []
    for row in reader:
        obj = {}
        for k, v in row.items():
            obj[k] = int(v) if v.isdigit() else v
        out.append(obj)
    return json.dumps(out)

name	age	zip
Alice	30	07008
Bob	25	10001

Given tab-separated values with a header, return a JSON array of objects, coercing any all-digit field to an integer.


Submission M7JO6L

import json

def transform(text):
    ips = [l.strip() for l in text.strip().split('\n') if l.strip()]
    ips.sort(key=lambda ip: tuple(int(o) for o in ip.split('.')))
    return json.dumps(ips)

Given a list of IPv4 addresses (one per line), return a JSON array sorted numerically by octet, not lexicographically.


Submission YHKZGR

import json

def transform(text):
    rows = json.loads(text)
    out = {}
    for r in rows:
        out[r['category']] = out.get(r['category'], 0) + r['amount']
    return json.dumps(out)

Given a JSON array of objects each with 'category' and 'amount', return a JSON object summing amount per category, keys in first-seen order.


Submission EY3IVK

import json

def transform(text):
    out = {}
    for line in text.strip().split('\n'):
        k, v = line.split('=', 1)
        vl = v.strip().lower()
        if vl == 'true':
            out[k.strip()] = True
        elif vl == 'false':
            out[k.strip()] = False
        elif v.strip().isdigit():
            out[k.strip()] = int(v.strip())
        else:
            out[k.strip()] = v.strip()
    return json.dumps(out)

enabled=TRUE
retries=3
name=server1
verbose=False

Given key-value lines in 'k=v' form, return a JSON object where any value that is 'true' or 'false' (case-insensitive) becomes a boolean and any all-digit value becomes an integer.


Submission GK98NL

import json

def transform(text):
    d = json.loads(text)
    mean = sum(d.values()) / len(d)
    return json.dumps(sorted(k for k, v in d.items() if v >= mean))

Given a JSON object of scores, return a JSON array of keys whose value is at or above the mean, sorted alphabetically.


Submission FJ5K8V

import re

def transform(text):
    out = []
    for ch, count in re.findall(r'([a-z])(\d+)', text.strip()):
        out.append(ch * int(count))
    return ''.join(out)

Given a run-length spec like 'a3b1c2', expand it into the full string 'aaabcc'.


Submission BPUFYR

def transform(text):
    lines = text.split('\n')
    return '\n'.join('{}:\t{}'.format(i, l) for i, l in enumerate(lines, 1))

Given a multi-line string, return it with each line prefixed by its 1-based line number, a colon, and a tab; join with newlines.


Submission Z9QYD2

import json

def transform(text):
    nums = [int(l) for l in text.strip().split('\n') if l.strip()]
    return json.dumps({'sum': sum(nums), 'min': min(nums), 'max': max(nums), 'mean': round(sum(nums)/len(nums), 2)})

Given newline-separated integers, return a JSON object with keys 'sum', 'min', 'max', and 'mean' where mean is rounded to two decimal places.


Submission FM44O9

import json
from collections import Counter

def transform(text):
    nums = json.loads(text)
    c = Counter(nums)
    return json.dumps(sorted(n for n in c if c[n] > 1))

Given a JSON array of numbers, return a JSON array containing only the numbers that appear more than once, in ascending order, each listed once.


Submission THY2UK

import re

def transform(text):
    m = re.search(r'[.!?]', text)
    if not m:
        return text.strip()
    return text[:m.end()].strip()

Hello there. This is the second one! And a third.

Given a paragraph, return the first sentence (text up to and including the first period, question mark, or exclamation mark), trimmed.


Submission 5P28JV

def transform(text):
    pairs = []
    for part in text.strip().split(';'):
        name, score = part.split('=')
        pairs.append((name.strip(), int(score)))
    pairs.sort(key=lambda p: (-p[1], p[0]))
    return '\n'.join(p[0] for p in pairs)

Parse a semicolon-separated list of 'name=score' pairs and return the names sorted by descending score, then alphabetically for ties, as a newline-separated string.


Submission 2FHYJV

import json

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

Convert a flat JSON object into a list of 'key=value' lines sorted by key, joining with newlines. Boolean values become lowercase 'true'/'false'.


Submission B4QVW0

import json

def transform(text):
    def is_prime(n):
        if n < 2:
            return False
        i = 2
        while i * i <= n:
            if n % i == 0:
                return False
            i += 1
        return True
    nums = [int(x) for x in text.strip().split(',')]
    return json.dumps([[n, is_prime(n)] for n in nums])

Given a comma-separated list of integers, return a JSON array of [value, is_prime] pairs preserving order, where is_prime is a boolean.


Submission GKMHVM

import re

def transform(text):
    total = 0
    for line in text.strip().split('\n'):
        m = re.match(r'(?:(\d+)h)?(?:(\d+)m)?$', line.strip())
        h = int(m.group(1)) if m and m.group(1) else 0
        mins = int(m.group(2)) if m and m.group(2) else 0
        total += h * 60 + mins
    return str(total)

Given lines each containing a duration like '1h30m' or '45m' or '2h', return the total number of minutes as a plain integer string.


Submission M3BOYG

MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December')
DAYS = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')

def join_list(items):
    if len(items) == 1:
        return items[0]
    return ', '.join(items[:-1]) + ' and ' + items[-1]

def describe_unit(field, singular, plural):
    if field == '*':
        return 'every ' + singular
    if field.startswith('*/'):
        return 'every ' + field[2:] + 'th ' + singular
    parts = field.split(',')
    if len(parts) == 1:
        return singular + ' ' + parts[0]
    return plural + ' ' + join_list(parts)

def transform(text):
    out = []
    for raw in text.split('\n'):
        expression = raw.strip()
        if not expression:
            continue
        fields = expression.split()
        if len(fields) != 5:
            out.append(expression + ' => ERROR: expected 5 fields')
            continue
        minute, hour, dom, month, dow = fields
        parts = [describe_unit(minute, 'minute', 'minutes'),
                 describe_unit(hour, 'hour', 'hours')]
        parts.append('every day of the month' if dom == '*' else 'day-of-month ' + dom)
        parts.append('every month' if month == '*' else MONTHS[int(month) - 1])
        if dow == '*':
            parts.append('every day of the week')
        elif '-' in dow:
            start, end = dow.split('-')
            parts.append(DAYS[int(start)] + ' through ' + DAYS[int(end)])
        else:
            parts.append(DAYS[int(dow)])
        out.append(expression + ' => ' + ', '.join(parts))
    return '\n'.join(out)

*/15 * * * * => every 15th minute, every hour, every day of the month, every month, every day of the week
0 9,17 * * 1-5 => minute 0, hours 9 and 17, every day of the month, every month, Monday through Friday
30 2 1 * * => minute 30, hour 2, day-of-month 1, every month, every day of the week
0 0 * 12 0 => minute 0, hour 0, every day of the month, December, Sunday
0 12 * * => ERROR: expected 5 fields

Describe each cron expression in English. Each non-blank input line is one expression; split it on whitespace.
If it does not have exactly 5 fields, the description is 'ERROR: expected 5 fields'. Otherwise the fields are minute, hour, day-of-month, month and day-of-week, and each is rendered by these rules:
- minute: '*' -> 'every minute'; '*/N' -> 'every Nth minute'; a single number M -> 'minute M'; a comma list -> 'minutes ' followed by the numbers joined with ', ' except that the last two are joined with ' and '.
- hour: '*' -> 'every hour'; '*/N' -> 'every Nth hour'; a single number H -> 'hour H'; a comma list -> 'hours ' followed by the same joining rule.
- day-of-month: '*' -> 'every day of the month'; a single number D -> 'day-of-month D'.
- month: '*' -> 'every month'; a single number 1-12 -> the English month name ('January' ... 'December').
- day-of-week: '*' -> 'every day of the week'; a single number 0-6 -> the English day name where 0 is 'Sunday' and 6 is 'Saturday'; a range 'A-B' -> '<name of A> through <name of B>'.
Join the five rendered fields with ', ' in that order to form the description.
Emit one line per input line as '<expression> => <description>', where the expression is the input line stripped of surrounding whitespace, and return the lines joined with '\n' and no trailing newline.


Submission KEOBS8

import base64

def transform(text):
    lines = text.split('\n')
    width = int(lines[0].split('=', 1)[1].strip())
    payload = ''.join(''.join(line.split()) for line in lines[1:])
    payload = payload.replace('=', '')
    while len(payload) % 4 != 0:
        payload += '='
    out = [payload[i:i + width] for i in range(0, len(payload), width)]
    decoded = base64.b64decode(payload)
    out.append('bytes=' + str(len(decoded)))
    return '\n'.join(out)

WIDTH=20
SGVsbG8sIER
hdGFCb3VudHkh

IFRoaXMgaXMg YSBiYXNlNjQg cmV3cmFwIHRlc3Q

SGVsbG8sIERhdGFCb3Vu
dHkhIFRoaXMgaXMgYSBi
YXNlNjQgcmV3cmFwIHRl
c3Q=
bytes=47

Re-wrap a base64 payload that arrived in ragged, unpadded chunks.
The first line is 'WIDTH=N' giving the target line width in characters. Every following line is a fragment of one single base64 payload.
Concatenate the fragments after removing ALL whitespace characters (including the line breaks and any spaces inside a fragment). Strip any '=' characters that are already present, then re-append the correct padding: while the length is not a multiple of 4, append one '='.
Emit the padded payload split into consecutive lines of exactly N characters, with the final line holding the remainder (possibly fewer than N characters).
Then append a final line 'bytes=M' where M is the number of bytes obtained by base64-decoding the padded payload.
Return the lines joined with '\n' and no trailing newline.


Submission 61A7GN

import json

def transform(text):
    head, body = text.split('\n', 1)
    maxdepth = int(head.split('=', 1)[1].strip())
    data = json.loads(body)
    out = []

    def walk(array, level):
        for element in array:
            if isinstance(element, list) and level <= maxdepth:
                walk(element, level + 1)
            else:
                out.append(json.dumps(element, separators=(',', ':')))

    walk(data, 1)
    return '\n'.join(out)

Flatten a nested JSON array, but only down to a given nesting depth.
The first line is 'maxdepth=N'. Everything after the first line is one JSON array (the outermost array).
Assign levels like this: the direct elements of the outermost array are at level 1, the elements of an array at level L are at level L+1. Walk the structure in order; when an element is an array, expand it (emit its elements instead of itself) if its own level is less than or equal to N, and otherwise emit that array itself as one item. Non-array elements are always emitted. An array that is expanded and has no elements contributes nothing.
Render every emitted item as compact JSON using separators ',' and ':' with no spaces, so strings keep their double quotes and JSON null is rendered as 'null'.
Return the rendered items one per line, joined with '\n' and with no trailing newline.


Submission L13NL2

def transform(text):
    files = []
    minus_path = None
    current = None
    for line in text.split('\n'):
        if line.startswith('\\'):
            continue
        if line.startswith('--- '):
            minus_path = line[4:].strip()
            current = None
            continue
        if line.startswith('+++ '):
            plus_path = line[4:].strip()
            if plus_path == '/dev/null':
                path = minus_path[2:] if minus_path.startswith('a/') else minus_path
            else:
                path = plus_path[2:] if plus_path.startswith('b/') else plus_path
            current = {'path': path, 'added': 0, 'removed': 0}
            files.append(current)
            continue
        if line.startswith('@@'):
            continue
        if current is None:
            continue
        if line.startswith('+'):
            current['added'] += 1
        elif line.startswith('-'):
            current['removed'] += 1
    out = []
    total_added = 0
    total_removed = 0
    for entry in files:
        changed = entry['added'] + entry['removed']
        marks = '+' * entry['added'] + '-' * entry['removed']
        out.append('{} | {} {}'.format(entry['path'], changed, marks))
        total_added += entry['added']
        total_removed += entry['removed']

    def plural(count, word):
        return '{} {}{}'.format(count, word, '' if count == 1 else 's')

    out.append('{} changed, {}(+), {}(-)'.format(
        plural(len(files), 'file'),
        plural(total_added, 'insertion'),
        plural(total_removed, 'deletion')))
    return '\n'.join(out)

diff --git a/app/main.py b/app/main.py
index 83db48f..bf269f4 100644
--- a/app/main.py
+++ b/app/main.py
@@ -1,5 +1,6 @@
 import sys
-import os
+import pathlib
+import json
 def main():
     pass
diff --git a/README.md b/README.md
deleted file mode 100644
--- a/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-# Project
-Docs
\ No newline at end of file

app/main.py | 3 ++-
README.md | 2 --
2 files changed, 2 insertions(+), 3 deletions(-)

Produce a git-style diffstat from a unified diff.
Scan the input line by line. A line starting with '--- ' or '+++ ' is a file header, a line starting with '@@' is a hunk header, and a line starting with '\' (such as '\ No newline at end of file') is ignored. Inside a hunk, a line starting with '+' counts as one insertion and a line starting with '-' counts as one deletion; any other line is context.
A file's reported path comes from its '+++ ' header with a leading 'b/' removed, except when that header is '+++ /dev/null', in which case use the '--- ' header path with a leading 'a/' removed. Files appear in the output in the order their headers appear in the input.
For each file emit '<path> | <changed> <marks>' where <changed> is insertions plus deletions and <marks> is one '+' per insertion followed by one '-' per deletion, with no scaling.
Then emit a final summary line '<F> file<s> changed, <I> insertion<s>(+), <D> deletion<s>(-)' where F, I and D are the totals and each of the three words takes an 's' only when its number is not 1.
Return the lines joined with '\n' and no trailing newline.


Submission R9LA3X

def transform(text):
    def to_minutes(hhmm):
        hours, minutes = hhmm.split(':')
        return int(hours) * 60 + int(minutes)

    def to_clock(total):
        return '{:02d}:{:02d}'.format(total // 60, total % 60)

    intervals = []
    for line in text.split('\n'):
        line = line.strip()
        if not line:
            continue
        start_text, end_text = line.split('-')
        start = to_minutes(start_text)
        end = to_minutes(end_text)
        if end <= start:
            continue
        intervals.append((start, end))
    intervals.sort()
    merged = []
    for start, end in intervals:
        if merged and start <= merged[-1][1]:
            if end > merged[-1][1]:
                merged[-1][1] = end
        else:
            merged.append([start, end])
    lines = [to_clock(s) + '-' + to_clock(e) for s, e in merged]
    lines.append('total=' + str(sum(e - s for s, e in merged)))
    return '\n'.join(lines)

Merge a list of same-day time ranges. Each non-blank input line is 'HH:MM-HH:MM' and describes the half-open interval [start, end) in minutes since midnight.
1. Discard any interval whose end is less than or equal to its start (this drops reversed and zero-length ranges).
2. Sort the surviving intervals by start ascending, then by end ascending.
3. Merge two intervals whenever the next start is less than OR EQUAL TO the current end, so intervals that merely touch at a boundary are merged into one.
4. Emit each merged interval as 'HH:MM-HH:MM' with hours and minutes zero-padded to two digits, one per line, in ascending order.
5. Append a final line 'total=N' where N is the sum of the merged interval lengths in minutes.
Return the lines joined with '\n' and no trailing newline.


Submission EQHMV6

PAIRS = (
    (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
    (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
    (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'),
)
DIGITS = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}

def to_roman(number):
    out = []
    remaining = number
    for value, symbol in PAIRS:
        while remaining >= value:
            out.append(symbol)
            remaining -= value
    return ''.join(out)

def transform(text):
    lines = []
    for raw in text.split('\n'):
        token = raw.strip()
        if not token:
            continue
        if token.isdigit():
            number = int(token)
            result = to_roman(number) if 1 <= number <= 3999 else 'ERROR'
        elif all(ch in DIGITS for ch in token):
            total = 0
            for index, ch in enumerate(token):
                value = DIGITS[ch]
                nxt = DIGITS[token[index + 1]] if index + 1 < len(token) else 0
                total += -value if value < nxt else value
            result = str(total) if to_roman(total) == token else 'ERROR'
        else:
            result = 'ERROR'
        lines.append(token + ' -> ' + result)
    return '\n'.join(lines)

1994 -> MCMXCIV
XLII -> 42
0 -> ERROR
4000 -> ERROR
IIII -> ERROR
MMXXVI -> 2026
58 -> LVIII
iv -> ERROR

Convert each non-blank line of a mixed list between Arabic integers and Roman numerals.
For each line, strip surrounding whitespace and classify the token:
1. If it consists only of decimal digits, parse it as an integer. If the integer is between 1 and 3999 inclusive, convert it to a Roman numeral using the standard subtractive pairs (M=1000, CM=900, D=500, CD=400, C=100, XC=90, L=50, XL=40, X=10, IX=9, V=5, IV=4, I=1) applied greedily from largest to smallest. Otherwise the result is 'ERROR'.
2. Otherwise, if it consists only of the upper-case letters M, D, C, L, X, V and I, evaluate it with the usual rule (a smaller value immediately before a larger one is subtracted, otherwise added). Accept it only if it is the canonical form, i.e. converting the resulting integer back to a Roman numeral by the greedy rule reproduces the token exactly; if it does, the result is that integer written in decimal, otherwise the result is 'ERROR'.
3. Any other token (including lower-case Roman numerals) gives 'ERROR'.
Emit one line per input line, in input order, formatted as '<token> -> <result>' with a single space on each side of '->'.
Return the lines joined with '\n' and no trailing newline.


Submission YNK12V

def transform(text):
    kept = []
    seen = {}
    skipped = 0
    for raw in text.split('\n'):
        address = raw.strip()
        if not address:
            continue
        if address.count('@') != 1:
            skipped += 1
            continue
        local, domain = address.lower().split('@')
        if not local or not domain:
            skipped += 1
            continue
        if '+' in local:
            local = local.split('+', 1)[0]
        if domain in ('gmail.com', 'googlemail.com'):
            local = local.replace('.', '')
            domain = 'gmail.com'
        key = local + '@' + domain
        if key not in seen:
            seen[key] = True
            kept.append(address)
    kept.append('skipped=' + str(skipped))
    return '\n'.join(kept)

First.Last+news@Gmail.com
firstlast@gmail.com
Bob@Example.COM
bob@example.com
b.o.b@example.com
carol@googlemail.com
c.a.r.o.l@gmail.com
not-an-email
dave@@example.com
  Eve@Example.com

First.Last+news@Gmail.com
Bob@Example.COM
b.o.b@example.com
carol@googlemail.com
Eve@Example.com
skipped=2

Deduplicate a list of email addresses using provider-aware canonical keys.
Strip surrounding whitespace from every line and skip lines that are then empty. A line is invalid, and is skipped and counted, if it does not contain exactly one '@', or if the part before or after the '@' is empty.
For a valid address build its canonical key like this: lower-case the whole address; drop everything from the first '+' in the local part up to (but not including) the '@'; if the domain is 'gmail.com' or 'googlemail.com', remove every '.' from the local part and use the domain 'gmail.com'; for any other domain leave the local part's dots alone.
Keep only the FIRST address of each distinct key and output it exactly as it appeared in the input after whitespace stripping (original casing, dots and '+tag' preserved), one per line, in order of first appearance.
Then append a final line 'skipped=N' where N is the number of invalid lines.
Return the lines joined with '\n' and no trailing newline.


Submission 512VP6

def transform(text):
    def key(version):
        core = version
        build = ''
        if '+' in core:
            core, build = core.split('+', 1)
        pre = ''
        if '-' in core:
            core, pre = core.split('-', 1)
        major, minor, patch = (int(p) for p in core.split('.'))
        if pre == '':
            pre_key = (1,)
        else:
            ids = []
            for ident in pre.split('.'):
                if ident.isdigit():
                    ids.append((0, int(ident), ''))
                else:
                    ids.append((1, 0, ident))
            pre_key = (0, tuple(ids))
        return (major, minor, patch, pre_key)

    versions = []
    for line in text.split('\n'):
        line = line.strip()
        if not line:
            continue
        if line.startswith('v'):
            line = line[1:]
        versions.append(line)
    versions.sort(key=key)
    return '\n'.join(versions)

Sort a newline-separated list of SemVer 2.0.0 version strings into ascending precedence order.
Ignore blank lines. A single optional leading 'v' is stripped from each version and is NOT present in the output.
Precedence rules:
1. Compare major, then minor, then patch as integers.
2. Build metadata (everything from the first '+' onward) is ignored for comparison but is preserved verbatim in the output.
3. A version WITH a pre-release (text after the first '-') has LOWER precedence than the same major.minor.patch without one.
4. Pre-releases are compared by splitting on '.' and comparing identifiers left to right: an identifier made only of digits is compared numerically and always ranks lower than an identifier containing a non-digit; two non-numeric identifiers are compared by ASCII string order.
5. If all identifiers of the shorter pre-release equal their counterparts, the version with MORE identifiers has higher precedence.
The input contains no two versions with equal precedence.
Return the versions one per line, ascending, with no trailing newline.


Submission RYXNVW

def transform(text):
    lines = text.split('\n')
    if lines and lines[-1] == '':
        lines = lines[:-1]
    header = lines[0]
    shift = int(header.split(':', 1)[1].strip()) % 26
    out = []
    for line in lines[1:]:
        chars = []
        for ch in line:
            if 'a' <= ch <= 'z':
                chars.append(chr((ord(ch) - 97 + shift) % 26 + 97))
            elif 'A' <= ch <= 'Z':
                chars.append(chr((ord(ch) - 65 + shift) % 26 + 65))
            else:
                chars.append(ch)
        out.append(''.join(chars))
    return '\n'.join(out)

shift: -3
Attack at Dawn, 07:00!

Zulu & aardvark -- ready?

Xqqxzh xq Axtk, 07:00!

Wrir & xxoasxoh -- obxav?

Apply a Caesar shift to a block of text.
The FIRST line of the input has the form 'shift: N' where N is an integer that may be negative or larger than 26; reduce it modulo 26 to get the effective shift. Every line after the first is body text.
Shift each ASCII letter forward by the effective shift, wrapping within its own alphabet, and preserve its case ('A'-'Z' stay upper case, 'a'-'z' stay lower case). Leave every other character, including digits, punctuation and spaces, exactly as it is.
Keep the body lines in their original order, including blank lines, and do not emit the 'shift:' header line.
Return the transformed body lines joined with '\n' and no trailing newline.


Submission 7IJK9G

import urllib.parse

SMALL_WORDS = ('and', 'of', 'the', 'in')
SUFFIXES = ('.html', '.htm', '.php')

def render_segment(segment):
    for suffix in SUFFIXES:
        if segment.endswith(suffix):
            segment = segment[:-len(suffix)]
            break
    words = [w for w in segment.replace('-', ' ').replace('_', ' ').split(' ') if w]
    rendered = []
    for index, word in enumerate(words):
        if index > 0 and word.lower() in SMALL_WORDS:
            rendered.append(word.lower())
        else:
            rendered.append(word[:1].upper() + word[1:])
    return ' '.join(rendered)

def transform(text):
    out = []
    for raw in text.split('\n'):
        line = raw.strip()
        if not line:
            continue
        line = line.split('#', 1)[0]
        line = line.split('?', 1)[0]
        marker = line.find('://')
        if marker != -1:
            slash = line.find('/', marker + 3)
            line = line[slash:] if slash != -1 else ''
        path = urllib.parse.unquote(line, encoding='utf-8')
        segments = [s for s in path.split('/') if s]
        crumbs = ['Home'] + [render_segment(s) for s in segments]
        out.append(' > '.join(c for c in crumbs if c))
    return '\n'.join(out)

Home > Docs > Getting Started > Install Guide
Home
Home > Blog > 2026 > The Art of Data Cleaning
Home > Shop > Mens Shoes

Turn each URL into a breadcrumb trail.
For every non-blank line: discard anything from the first '#' onward, then anything from the first '?' onward. Remove a leading scheme and host by deleting a leading 'scheme://host' when the remainder starts with '://' after a scheme; concretely, if the text contains '://', drop everything up to and including the first '/' that follows it. Then percent-decode the path using UTF-8 and split it on '/', dropping empty segments.
For each segment: if it ends with '.html', '.htm' or '.php' (case-sensitive) remove that suffix; replace every '-' and '_' with a space; split on spaces and drop empty words; then capitalise each word by upper-casing its first character and leaving the rest unchanged, EXCEPT that a word equal to 'and', 'of', 'the' or 'in' (compared lower-case) stays entirely lower-case unless it is the first word of the segment. Rejoin the words with single spaces.
The breadcrumb is the literal 'Home' followed by the rendered segments, joined with ' > ' (space, greater-than, space). A URL with no path segments yields just 'Home'.
Emit one breadcrumb per input line in input order, joined with '\n' and no trailing newline.


Submission 3J3IJ6

import csv

RATES = {'food': 0, 'book': 5, 'general': 10, 'luxury': 20}

def transform(text):
    lines = [l for l in text.split('\n') if l != '']
    reader = csv.DictReader(lines)
    out = []
    subtotal_sum = 0
    tax_sum = 0
    skipped = 0
    for row in reader:
        qty_text = (row.get('qty') or '').strip()
        price_text = (row.get('unit_price_cents') or '').strip()
        try:
            qty = int(qty_text)
            price = int(price_text)
        except ValueError:
            skipped += 1
            continue
        category = (row.get('category') or '').strip()
        rate = RATES.get(category, RATES['general'])
        subtotal = qty * price
        tax = (subtotal * rate + 50) // 100
        subtotal_sum += subtotal
        tax_sum += tax
        out.append('{} x{} = {} (tax {})'.format(row['name'], qty, subtotal, tax))
    out.append('SUBTOTAL=' + str(subtotal_sum))
    out.append('TAX=' + str(tax_sum))
    out.append('TOTAL=' + str(subtotal_sum + tax_sum))
    out.append('SKIPPED=' + str(skipped))
    return '\n'.join(out)

name,qty,unit_price_cents,category
Sourdough Loaf,2,650,food
Novel,1,1899,book
USB Cable,3,999,general
Perfume,1,12500,luxury
Mystery Item,1,500,widgets
Broken Row,,300,general
Free Sample,0,250,food

Sourdough Loaf x2 = 1300 (tax 0)
Novel x1 = 1899 (tax 95)
USB Cable x3 = 2997 (tax 300)
Perfume x1 = 12500 (tax 2500)
Mystery Item x1 = 500 (tax 50)
Free Sample x0 = 0 (tax 0)
SUBTOTAL=19196
TAX=2945
TOTAL=22141
SKIPPED=1

Total a shopping cart whose tax rate depends on the line's category.
The input is CSV with the header 'name,qty,unit_price_cents,category'. All money is in integer cents.
Tax rates by category: 'food' 0 percent, 'book' 5 percent, 'general' 10 percent, 'luxury' 20 percent. Any other category is taxed at the 'general' rate of 10 percent.
Skip a data row, and count it as skipped, if its qty field or its unit_price_cents field is empty or is not a valid integer. A qty of 0 is a valid row and simply contributes zero.
For each kept row: subtotal = qty * unit_price_cents, and tax = (subtotal * rate_percent + 50) // 100 (integer floor division, i.e. round half up to the nearest cent).
Emit one line per kept row, in input order, as '<name> x<qty> = <subtotal> (tax <tax>)'. Then emit, in this order, the lines 'SUBTOTAL=<sum of subtotals>', 'TAX=<sum of taxes>', 'TOTAL=<subtotal sum plus tax sum>' and 'SKIPPED=<count>'.
Return the lines joined with '\n' and no trailing newline.


Submission 7TV6MS

import re

KEY_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
REF_RE = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}')

def transform(text):
    values = {}
    interpolating = {}
    ignored = 0
    for raw in text.split('\n'):
        line = raw.strip()
        if not line or line.startswith('#'):
            continue
        if line.startswith('export '):
            line = line[len('export '):].strip()
        if '=' not in line:
            ignored += 1
            continue
        key, value = line.split('=', 1)
        key = key.strip()
        if not KEY_RE.match(key):
            ignored += 1
            continue
        value = value.strip()
        expand = True
        if len(value) >= 2 and value[0] == '"' and value[-1] == '"':
            value = value[1:-1]
        elif len(value) >= 2 and value[0] == "'" and value[-1] == "'":
            value = value[1:-1]
            expand = False
        values[key] = value
        interpolating[key] = expand
    for _ in range(10):
        for key in list(values):
            if not interpolating[key]:
                continue
            values[key] = REF_RE.sub(lambda m: values.get(m.group(1), ''), values[key])
    out = [k + '=' + values[k] for k in sorted(values)]
    out.append('ignored=' + str(ignored))
    return '\n'.join(out)

# database settings
DB_HOST=localhost
DB_PORT=5432
DB_URL=postgres://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/app
DB_USER=admin
export DB_PASS='s3cr3t#1'
GREETING="Hello ${DB_USER}"
EMPTY=
LITERAL='raw ${DB_USER}'
badline
PATH_EXTRA=$HOME/bin
TIMEOUT=${MISSING}30

DB_HOST=localhost
DB_PASS=s3cr3t#1
DB_PORT=5432
DB_URL=postgres://admin:s3cr3t#1@localhost:5432/app
DB_USER=admin
EMPTY=
GREETING=Hello admin
LITERAL=raw ${DB_USER}
PATH_EXTRA=$HOME/bin
TIMEOUT=30
ignored=1

Parse a .env style file and resolve '${VAR}' references.
Ignore lines that are empty after stripping and lines whose first non-space character is '#'. Strip a leading 'export ' prefix. A line is ignored and counted as ignored if it has no '=' or if the text before the first '=', once stripped, does not match the regular expression [A-Za-z_][A-Za-z0-9_]* .
Take the raw value as everything after the first '=', stripped of surrounding whitespace. If it starts and ends with a double quote (length at least two), remove the quotes and mark the value as interpolating. If it starts and ends with a single quote, remove the quotes and mark it as literal, i.e. never interpolated. Otherwise keep it as it is and mark it as interpolating. If the same key is defined twice, the later definition wins and the earlier one is discarded (it is NOT counted as ignored).
Then resolve references by repeating this pass exactly 10 times: for every interpolating value, replace each occurrence of '${NAME}' - where NAME matches [A-Za-z_][A-Za-z0-9_]* - with the current value of NAME if NAME is one of the parsed keys, or with the empty string if it is not. Only the '${NAME}' form is a reference; a bare '$NAME' is left untouched.
Emit one 'KEY=value' line per parsed key, sorted by key in ascending Unicode code point order (a key whose value is empty produces 'KEY=' with nothing after the '='), then a final line 'ignored=N' with the ignored-line count.
Return the lines joined with '\n' and no trailing newline.


Submission U3RCS2

def transform(text):
    values = {}
    for line in text.split('\n'):
        if not line.strip():
            continue
        if ':' not in line:
            continue
        raw_name, raw_value = line.split(':', 1)
        parts = raw_name.strip().lower().split('-')
        name = '-'.join(p[:1].upper() + p[1:] for p in parts)
        value = raw_value.strip()
        if name not in values:
            values[name] = []
        if value:
            values[name].append(value)
    lines = []
    for name in sorted(values):
        joined = ', '.join(values[name])
        lines.append(name + ': ' + joined if joined else name + ':')
    return '\n'.join(lines)

content-type: application/json
X-Request-ID: abc-123
accept:    text/html
set-cookie: session=a1
this line has no colon
SET-COOKIE: theme=dark
x-empty:
Host: api.example.com

Accept: text/html
Content-Type: application/json
Host: api.example.com
Set-Cookie: session=a1, theme=dark
X-Empty:
X-Request-Id: abc-123

Normalise a raw HTTP header block into a canonical, sorted list.
1. Process the input line by line, ignoring lines that are empty after stripping and lines that contain no ':' character.
2. Split each remaining line at the FIRST ':' only: the part before is the name, the part after is the value.
3. Canonicalise the name: strip surrounding whitespace, lowercase it, then upper-case the first character of each '-'-separated token and lowercase the rest (so 'content-type' and 'X-Request-ID' become 'Content-Type' and 'X-Request-Id').
4. Strip leading and trailing whitespace from the value.
5. Collect the values of each canonical name in the order the lines appeared in the input, discarding values that are the empty string, and join the remaining ones with ', ' (comma then one space).
6. Emit one line per canonical name, sorted by canonical name in ascending Unicode code point order.
7. Format each line as 'Name: value'. If the joined value is empty (the name had no non-empty value), emit 'Name:' with nothing after the colon and no trailing space.
Join the emitted lines with '\n' and return them with no trailing newline.


Submission RBUB5I

def transform(text):
    lines = [l for l in text.split('\n') if l.strip()]
    cc = lines[0].split('=', 1)[1].strip()
    out = []
    for raw in lines[1:]:
        body = raw
        for marker in ('x', 'X'):
            position = body.find(marker)
            if position != -1:
                body = body[:position]
        plus = body.lstrip().startswith('+')
        digits = ''.join(ch for ch in body if ch.isdigit())
        if plus:
            national = digits
        elif digits.startswith('00'):
            national = digits[2:]
        elif digits.startswith('0'):
            national = cc + digits[1:]
        else:
            national = cc + digits
        if 8 <= len(national) <= 15:
            out.append('+' + national)
        else:
            out.append('INVALID')
    return '\n'.join(out)

Normalise a list of raw phone numbers to E.164.
The first line is 'cc=N' giving the default country calling code as digits. Every following non-blank line is one raw number.
For each raw number, in this order:
1. Drop an extension: if the line contains 'x' or 'X', discard that character and everything after it.
2. Note whether the remaining text, after stripping leading whitespace, starts with '+'. Then keep only its digit characters.
3. Build the international digits: if the '+' was present, use the digits as they are; else if the digits start with '00', drop that '00' and use the rest; else if the digits start with a single '0', drop that '0' and prepend the default country code; otherwise prepend the default country code to all the digits.
4. If the resulting digit string has fewer than 8 or more than 15 digits, the result for that line is the literal 'INVALID'; otherwise it is '+' followed by those digits.
Emit one result per input number line, in input order, and return them joined with '\n' with no trailing newline.


Submission 6J2GAC

def transform(text):
    lines = [l for l in text.split('\n') if l.strip()]
    rows, cols = (int(p) for p in lines[0].split())
    grid = [[0] * cols for _ in range(rows)]
    for line in lines[1:]:
        row, col, value = (int(p) for p in line.split())
        if 0 <= row < rows and 0 <= col < cols:
            grid[row][col] = value
    rendered = [[str(v) for v in row] for row in grid]
    width = 0
    for row in rendered:
        for cell in row:
            if len(cell) > width:
                width = len(cell)
    return '\n'.join(' '.join(cell.rjust(width) for cell in row) for row in rendered)

Expand a sparse matrix given as triplets into a dense text grid.
The first non-blank line holds two integers 'ROWS COLS' separated by whitespace. Every following non-blank line holds three integers 'ROW COL VALUE' with zero-based indices.
Rules: start from a grid of all zeros; ignore any triplet whose row is not in [0, ROWS-1] or whose column is not in [0, COLS-1]; if two kept triplets address the same cell, the one appearing LATER in the input wins.
Render the grid with one row per line. Every value is rendered with str() and right-aligned in a field whose width is the length of the longest rendered value anywhere in the finished grid (minus signs count towards that length); cells are separated by a single space. Because of the right alignment no line ends in whitespace.
Return the rows joined with '\n' and no trailing newline.


Submission 2Z6RBN

import re

PLACEHOLDER = re.compile(r'\{\{([^{}]*)\}\}')

def transform(text):
    lines = text.split('\n')
    if lines and lines[-1] == '':
        lines = lines[:-1]
    separator = lines.index('---')
    table = {}
    for line in lines[:separator]:
        if '=' not in line:
            continue
        key, value = line.split('=', 1)
        table[key.strip()] = value

    def replace(match):
        body = match.group(1)
        if '|' in body:
            name, default = body.split('|', 1)
            default = default.strip()
        else:
            name, default = body, ''
        name = name.strip()
        if name in table:
            return table[name]
        return default

    rendered = [PLACEHOLDER.sub(replace, line).rstrip() for line in lines[separator + 1:]]
    return '\n'.join(rendered)

name=Ada
city=
title=Engineer
---
Hello {{ name }}, welcome to {{city|Unknown}}.
Role: {{title}} / Team: {{team|Core}}
Contact: {{email}}

Hello Ada, welcome to .
Role: Engineer / Team: Core
Contact:

Render a small text template against a variable table.
The input has two sections separated by a line containing exactly '---'. Lines before it are variable definitions 'key=value' split at the FIRST '='; the key is stripped of surrounding whitespace and the value is taken verbatim after the '=' (so 'city=' defines city as the empty string). Lines after the separator are the template, in order.
In the template, replace every placeholder of the form '{{ NAME }}' or '{{ NAME|DEFAULT }}' (the name and the optional default are stripped of surrounding whitespace) as follows: if NAME is defined in the table use its value even when that value is the empty string; otherwise use DEFAULT if the placeholder supplied one; otherwise use the empty string.
Replacement values are inserted literally and are never rescanned for placeholders.
Finally strip trailing whitespace from every rendered line so no line ends in a space.
Return the rendered lines joined with '\n' and no trailing newline.


Submission JACQG4

from decimal import Decimal, ROUND_HALF_UP

FACTORS = {
    'in': ('cm', Decimal('2.54')),
    'ft': ('m', Decimal('0.3048')),
    'mi': ('km', Decimal('1.609344')),
    'lb': ('kg', Decimal('0.45359237')),
    'oz': ('g', Decimal('28.349523125')),
    'gal': ('L', Decimal('3.785411784')),
}
CENT = Decimal('0.01')

def transform(text):
    out = []
    for raw in text.split('\n'):
        line = raw.strip()
        if not line:
            continue
        parts = line.split()
        amount = Decimal(parts[0])
        unit = parts[1]
        if unit == 'F':
            value = (amount - Decimal('32')) * Decimal(5) / Decimal(9)
            target = 'C'
        elif unit in FACTORS:
            target, factor = FACTORS[unit]
            value = amount * factor
        else:
            out.append(line + ' = UNSUPPORTED')
            continue
        rounded = value.quantize(CENT, rounding=ROUND_HALF_UP)
        out.append(line + ' = ' + str(rounded) + ' ' + target)
    return '\n'.join(out)

12 in
3 ft
26.2 mi
150 lb
8 oz
98.6 F
-40 F
5 gal
7 furlong

Convert a list of imperial measurements to metric.
Each non-blank line is '<number> <unit>' separated by whitespace, where the number may be negative or fractional.
Supported units and their exact conversions are: 'in' -> cm, multiply by 2.54; 'ft' -> m, multiply by 0.3048; 'mi' -> km, multiply by 1.609344; 'lb' -> kg, multiply by 0.45359237; 'oz' -> g, multiply by 28.349523125; 'gal' -> L, multiply by 3.785411784 (US liquid gallon); 'F' -> C, subtract 32 then multiply by 5 and divide by 9.
Do the arithmetic in exact decimal (Python's decimal module, not binary floats) and round the result to exactly two decimal places using ROUND_HALF_UP. Always show two decimal places, keeping trailing zeros.
Emit one line per input line as '<original line stripped> = <result> <metric unit>'. If the unit is not one of the seven supported ones, emit '<original line stripped> = UNSUPPORTED' instead.
Return the lines joined with '\n' and no trailing newline.


Submission 8M8B1G

import csv
import io

def transform(text):
    lines = text.split('\n')
    if lines and lines[-1] == '':
        lines = lines[:-1]
    separator = lines.index('---')
    mapping = []
    for line in lines[:separator]:
        if '->' not in line:
            continue
        source, target = line.split('->', 1)
        mapping.append((source.strip(), target.strip()))
    rows = list(csv.reader(lines[separator + 1:]))
    header = rows[0]
    index_of = {}
    for position, name in enumerate(header):
        if name not in index_of:
            index_of[name] = position
    out = io.StringIO()
    writer = csv.writer(out, lineterminator='\n', quoting=csv.QUOTE_MINIMAL)
    writer.writerow([target for _, target in mapping])
    for row in rows[1:]:
        record = []
        for source, _ in mapping:
            position = index_of.get(source)
            if position is None or position >= len(row):
                record.append('')
            else:
                record.append(row[position])
        writer.writerow(record)
    return out.getvalue().rstrip('\n')

sku->Item Code
name->Product
price->Unit Price
discount->Discount
---
name,sku,price,notes
"Widget, large",W-100,19.99,n/a
Gadget,G-200,5.00
Doohickey,D-300,,extra,ignored

Item Code,Product,Unit Price,Discount
W-100,"Widget, large",19.99,
G-200,Gadget,5.00,
D-300,Doohickey,,

Reorder and rename the columns of a CSV according to a header map.
The input has two sections separated by a line containing exactly '---'. Each line before the separator is 'source_column->output_column'; the order of these lines is the order of the output columns. Lines after the separator are CSV data parsed with standard rules (comma delimiter, double-quote quoting), the first of which is the header row.
For every data row, produce one output row containing, for each map entry in order, the value of that source column. Handle the edge cases as follows: if a source column name does not appear in the CSV header, its output value is the empty string for every row; if a row has fewer fields than the header, the missing fields count as the empty string; if a row has more fields than the header, the extra fields are ignored.
Write the result as CSV using the output column names as the header row, comma delimiter, minimal quoting (a field is quoted only if it contains a comma, a double quote, a carriage return or a newline) and '\n' as the line terminator.
Return the CSV text with no trailing newline.


Submission K0UDHG

def transform(text):
    out = []
    for raw in text.split('\n'):
        line = raw.strip()
        if not line:
            continue
        digits = line.replace(' ', '').replace('-', '')
        if not digits.isdigit() or not digits.isascii():
            out.append(line + ': INVALID_CHARS')
            continue
        if len(digits) < 13 or len(digits) > 19:
            out.append(line + ': INVALID_LENGTH')
            continue
        total = 0
        for position, ch in enumerate(reversed(digits)):
            value = int(ch)
            if position % 2 == 1:
                value *= 2
                if value > 9:
                    value -= 9
            total += value
        status = 'VALID' if total % 10 == 0 else 'FAILED_CHECKSUM'
        masked = '*' * (len(digits) - 4) + digits[-4:]
        out.append(masked + ': ' + status)
    return '\n'.join(out)

Validate a list of payment card numbers with the Luhn algorithm and mask them.
For each non-blank line, strip surrounding whitespace, then remove every space and every '-' character. Then, in order:
1. If the remaining text contains any character that is not an ASCII digit, the line's status is 'INVALID_CHARS'.
2. Otherwise, if the number of digits is below 13 or above 19, the status is 'INVALID_LENGTH'.
3. Otherwise apply the Luhn check: walking the digits from right to left, leave every first digit unchanged and double every second digit, subtracting 9 from any doubled value greater than 9; the status is 'VALID' if the resulting sum is divisible by 10, and 'FAILED_CHECKSUM' if it is not.
The label for a line is its masked number when the status is 'VALID' or 'FAILED_CHECKSUM' - the digit string with every digit except the last four replaced by '*' - and the whitespace-stripped ORIGINAL line otherwise.
Emit one line per input line as '<label>: <status>', in input order, joined with '\n' and with no trailing newline.


Submission GC3P1S

import json

def to_scalar(raw):
    value = raw
    if not value.startswith('"') and not value.startswith("'"):
        position = value.find(' #')
        if position != -1:
            value = value[:position]
    value = value.strip()
    if len(value) >= 2 and ((value[0] == '"' and value[-1] == '"') or (value[0] == "'" and value[-1] == "'")):
        return value[1:-1]
    if value == 'true':
        return True
    if value == 'false':
        return False
    if value in ('null', '~'):
        return None
    body = value[1:] if value.startswith('-') else value
    if body.isdigit() and body.isascii():
        return int(value)
    try:
        return float(value)
    except ValueError:
        return value

def parse_block(entries, index, indent):
    if entries[index][1].startswith('- '):
        items = []
        while index < len(entries) and entries[index][0] == indent and entries[index][1].startswith('- '):
            items.append(to_scalar(entries[index][1][2:]))
            index += 1
        return items, index
    mapping = {}
    while index < len(entries) and entries[index][0] == indent:
        content = entries[index][1]
        key, _, rest = content.partition(':')
        key = key.strip()
        if rest.strip() == '':
            child, index = parse_block(entries, index + 1, indent + 2)
            mapping[key] = child
        else:
            mapping[key] = to_scalar(rest.strip())
            index += 1
    return mapping, index

def transform(text):
    entries = []
    for line in text.split('\n'):
        if not line.strip():
            continue
        if line.lstrip().startswith('#'):
            continue
        entries.append((len(line) - len(line.lstrip(' ')), line.strip()))
    parsed, _ = parse_block(entries, 0, 0)
    return json.dumps(parsed, indent=2)

# service configuration
name: api-gateway
version: 2
enabled: true
replicas: 3  # desired count
timeout: 1.5
notes: null
owner:
  team: platform
  email: "ops@example.com"
tags:
  - production
  - "eu-west"
  - 42
limits:
  cpu: 500m
  memory: 1Gi

Parse a restricted YAML-like configuration block into JSON.
Ignore lines that are empty after stripping and lines whose first non-space character is '#'. Indentation is always a multiple of two spaces, and a nested block is always indented exactly two spaces deeper than the 'key:' line that introduces it.
A line of the form 'key: value' is a scalar entry; a line of the form 'key:' with nothing after the colon introduces a nested block, which is either a mapping (its lines are 'key: value' or 'key:') or a list (all of its lines start with '- '). List items are scalars only. Mapping keys keep the order in which they appear.
Before converting a scalar, remove an inline comment: if the value does not begin with a single or double quote and the two-character sequence ' #' occurs in it, drop that sequence and everything after it; then strip surrounding whitespace.
Convert a scalar like this: if it starts and ends with a double quote, or starts and ends with a single quote, and is at least two characters long, the value is the text between the quotes as a string; else 'true' becomes JSON true and 'false' becomes JSON false; else 'null' or '~' becomes JSON null; else a token matching an optional '-' followed by digits only becomes an integer; else a token that Python's float() accepts becomes a number; else it stays a string.
Return the resulting object serialised with json.dumps using indent=2 (two-space indentation, keys in insertion order, no sort), with no trailing newline.


Submission 3A30F5

def transform(text):
    added = 0
    removed = 0
    for line in text.split('\n'):
        if line.startswith('+++') or line.startswith('---'):
            continue
        if line.startswith('+'):
            added += 1
        elif line.startswith('-'):
            removed += 1
    return 'added={} removed={} net={}'.format(added, removed, added - removed)

--- a/app.py
+++ b/app.py
@@ -1,4 +1,5 @@
 context
-old one
-old two
+new one
+new two
+new three
 context

Collapse a unified-diff hunk into a summary: count added and removed lines (ignoring the +++/--- headers) and return 'added=N removed=M net=K' where net is added minus removed.


Submission 9FRWVL

def transform(text):
    totals = {}
    for line in text.strip().split('\n'):
        if not line.strip():
            continue
        code, amount = line.split()
        totals[code] = totals.get(code, 0.0) + float(amount)
    return '\n'.join('{} {:.2f}'.format(c, totals[c]) for c in sorted(totals))

Given 'currency amount' lines, sum per currency and return 'CUR total' lines sorted by currency code, with totals formatted to exactly two decimal places.


Submission Z4CDE7

def transform(text):
    children = {}
    seen_child = set()
    nodes = set()
    for line in text.strip().split('\n'):
        if not line.strip():
            continue
        parent, child = line.strip().split('>')
        children.setdefault(parent, []).append(child)
        seen_child.add(child)
        nodes.add(parent)
        nodes.add(child)
    out = []
    def emit(node, depth):
        out.append('  ' * depth + node)
        for kid in sorted(children.get(node, [])):
            emit(kid, depth + 1)
    for root in sorted(nodes - seen_child):
        emit(root, 0)
    return '\n'.join(out)

app>web
app>api
web>static
api>db
lib>util

app
  api
    db
  web
    static
lib
  util

Given lines of 'parent>child', emit an indented tree from every root (a node that is never a child), two spaces per level, children sorted alphabetically, roots sorted alphabetically.


Submission 779MZJ

def transform(text):
    rows = []
    for line in text.strip().split('\n')[1:]:
        if not line.strip():
            continue
        name, score = line.split(',')
        rows.append((name.strip(), int(score)))
    def grade(score):
        for cutoff, letter in ((90, 'A'), (80, 'B'), (70, 'C')):
            if score >= cutoff:
                return letter
        return 'F'
    rows.sort(key=lambda r: (-r[1], r[0]))
    return '\n'.join('{} {}'.format(n, grade(s)) for n, s in rows)

name,score
rhea,90
olu,89
mina,70
kade,69
bea,90

Read 'name,score' CSV lines and return 'name grade' lines where the grade is the letter band A (>=90), B (>=80), C (>=70), else F, ordered by descending score then ascending name.


Submission 7OR3YS

def transform(text):
    entries = []
    for line in text.strip().split('\n'):
        if not line.strip():
            continue
        clock, name = line.split(None, 1)
        hours, minutes = clock.split(':')
        entries.append((int(hours) * 60 + int(minutes), name.strip()))
    entries.sort()
    lines = ['{}: {}'.format(name, mins) for mins, name in entries]
    lines.append('span={}'.format(entries[-1][0] - entries[0][0]))
    return '\n'.join(lines)

09:15 standup
14:05 review
08:00 prep
17:30 wrapup

prep: 480
standup: 555
review: 845
wrapup: 1050
span=570

Parse 'HH:MM name' schedule lines and return each entry as 'name: minutes-since-midnight', sorted chronologically, followed by a final 'span=N' line giving minutes between first and last.


Submission H0INQD

import csv, io, json

def transform(text):
    readings = {}
    for row in csv.DictReader(io.StringIO(text.strip())):
        readings.setdefault(row["sensor"], []).append(float(row["reading"]))
    summary = {}
    for sensor, values in readings.items():
        summary[sensor] = {
            "min": min(values),
            "max": max(values),
            "mean": round(sum(values) / len(values), 2),
        }
    return json.dumps(summary)

For each sensor return min, max and mean of its readings as JSON, mean rounded to 2 decimals. Sensors are listed in first-seen order. Negative readings are included.


Submission B6T3W8

def transform(text):
    masked = []
    for chunk in text.strip().split(";"):
        _, _, number = chunk.partition("=")
        number = number.strip()
        if not number:
            continue
        if len(number) <= 4:
            masked.append(number)
        else:
            masked.append("*" * (len(number) - 4) + number[-4:])
    return "\n".join(masked)

Mask each account number so only the last four characters remain visible, replacing the rest with '*'. Numbers of four characters or fewer are left untouched. Return the masked values one per line.


Submission VIOQB0

import re

def transform(text):
    def key(name):
        parts = re.split(r"(\d+)", name)
        return [int(part) if part.isdigit() else part.casefold() for part in parts]
    names = [line.strip() for line in text.strip().split("\n") if line.strip()]
    return "\n".join(sorted(names, key=key))

file10.txt
file2.txt
File1.txt
file20.txt

File1.txt
file2.txt
file10.txt
file20.txt

Sort the filenames naturally: split each name into digit and non-digit runs, compare text case-insensitively and digit runs numerically. Return the sorted names one per line.


Submission M2HLZH

def transform(text):
    keep = {"WARN", "ERROR"}
    rows = ["time\tlevel\tmessage"]
    for line in text.strip().split("\n"):
        parts = line.split(None, 3)
        if len(parts) < 4:
            continue
        date, time, level, message = parts
        if level not in keep:
            continue
        rows.append(time + "\t" + level + "\t" + message.strip())
    return "\n".join(rows)

2026-01-04 09:12:01 WARN  disk usage 91%
2026-01-04 09:12:04 INFO  heartbeat ok
2026-01-04 09:13:00 ERROR upload failed retry=2
malformed line without level

time	level	message
09:12:01	WARN	disk usage 91%
09:13:00	ERROR	upload failed retry=2

Convert the log into TSV with header 'time\tlevel\tmessage', keeping only WARN and ERROR lines. Use just the time portion of the timestamp. Lines that do not match the expected shape are skipped.


Submission SYVWQE

def transform(text):
    seen = set()
    kept = []
    for line in text.split("\n"):
        stripped = line.strip()
        if not stripped:
            continue
        key = stripped.casefold()
        if key in seen:
            continue
        seen.add(key)
        kept.append(stripped)
    return "\n".join(kept)

Remove duplicate lines case-insensitively, keeping the first spelling seen and the original order. Blank lines are dropped. Return the remaining lines.


Submission KV0RI0

def transform(text):
    factors = {"h": 3600, "m": 60, "s": 1}
    rows = ["duration,seconds"]
    for line in text.strip().split("\n"):
        duration = line.strip()
        total = 0
        for token in duration.split():
            total += int(token[:-1]) * factors[token[-1]]
        rows.append(duration + "," + str(total))
    return "\n".join(rows)

Convert each duration into total seconds, returning CSV with header 'duration,seconds' preserving the input order.


Submission ZG28UF

import json

def transform(text):
    groups = {}
    for line in text.strip().split("\n"):
        name, _rank, status = line.strip().split("|")
        groups.setdefault(status, []).append(name)
    ordered = {status: sorted(groups[status]) for status in sorted(groups)}
    return json.dumps(ordered)

Group the pipe-delimited rows by their status column and return JSON mapping each status to the sorted list of names, with statuses in alphabetical order.


Submission QY8WBX

import csv, io

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    totals = {}
    for row in reader:
        totals[row["region"]] = totals.get(row["region"], 0) + int(row["units"])
    ordered = sorted(totals.items(), key=lambda pair: (-pair[1], pair[0]))
    lines = ["region,total"]
    for region, total in ordered:
        lines.append(region + "," + str(total))
    return "\n".join(lines)

region,units
north,10
south,4
north,6
east,0
south,11

Aggregate the CSV by region, summing units. Return CSV with header 'region,total' sorted by total descending, then region ascending for ties. Regions totalling zero are still included.


Submission R9EJBY

import json

def transform(text):
    lines = [line for line in text.strip().split("\n") if line.strip()]
    rows = []
    for line in lines[1:]:
        sku = line[0:9].strip()
        qty = int(line[9:14].strip())
        unit_price = float(line[14:].strip())
        if qty == 0:
            continue
        rows.append({
            "sku": sku,
            "qty": qty,
            "line_total": round(qty * unit_price, 2),
        })
    return json.dumps(rows)

Parse the fixed-width inventory report (columns SKU, QTY, UNIT_PRICE) and return a JSON array of objects with keys sku, qty (integer, leading zeros stripped) and line_total (qty * unit_price rounded to 2 decimals). Skip rows whose qty is zero.


Submission 2QN262

import json

def transform(text):
    config = {}
    section = None
    for line in text.strip().split("\n"):
        line = line.strip()
        if not line:
            continue
        if line.startswith("[") and line.endswith("]"):
            section = line[1:-1]
            config[section] = {}
            continue
        key, _, raw = line.partition("=")
        key, raw = key.strip(), raw.strip()
        if raw in ("true", "false"):
            value = raw == "true"
        elif raw.isdigit():
            value = int(raw)
        else:
            value = raw
        config[section][key] = value
    return json.dumps(config)

[app]
retries = 3
debug = true
name = ingest worker

[db]
port = 5432
ssl = false

Parse the INI-style config into nested JSON, coercing values: 'true'/'false' become booleans, all-digit values become integers, everything else stays a string. Section names become top-level keys.


Submission E0OEBN

import json

def transform(text):
    blocks = [block for block in text.strip().split("\n\n") if block.strip()]
    lines = []
    for block in blocks:
        record = {}
        for line in block.strip().split("\n"):
            key, _, value = line.partition(":")
            record[key.strip()] = value.strip()
        lines.append(json.dumps(record, separators=(",", ":")))
    return "\n".join(lines)

id: 41
status: open

id: 42
status: closed
note: duplicate

id: 43
status: open

Split the blank-line separated 'key: value' blocks into JSON Lines — one compact JSON object per block, one per output line, preserving key order within a block.


Submission 3L6VUF

import json

def transform(text):
    root = []
    stack = [(-1, root)]
    for line in text.rstrip().split("\n"):
        if not line.strip():
            continue
        indent = len(line) - len(line.lstrip(" "))
        label = line.strip().lstrip("-").strip()
        node = {label: []}
        while stack and stack[-1][0] >= indent:
            stack.pop()
        stack[-1][1].append(node)
        stack.append((indent, node[label]))
    return json.dumps(root)

- platform
  - ingest
    - parser
  - storage
- web
  - api

Convert the two-space-indented Markdown bullet list into nested JSON where each node maps its label to a list of child nodes, and a leaf maps to an empty list.


Submission 2OZ0QL

import csv, io, json

def transform(text):
    records = json.loads(text)
    out = io.StringIO()
    writer = csv.writer(out, lineterminator="\n")
    writer.writerow(["name", "qty"])
    for record in records:
        writer.writerow([record["name"], record["qty"]])
    return out.getvalue().strip()

Convert the JSON array into CSV with header 'name,qty', applying standard CSV quoting so that names containing commas or double quotes survive a round trip. Rows keep their original order.


Submission 0E53FX

def transform(text):
    values = []
    for line in text.strip().split("\n"):
        raw = line.strip().replace("USD", "").replace("$", "").replace(",", "").strip()
        values.append(format(float(raw), ".2f"))
    return "\n".join(values)

Normalise the currency amounts to plain signed decimals with exactly two decimal places, stripping symbols, thousands separators and the 'USD' prefix. Return one value per line in the original order.


Submission 0NL09U

def transform(text):
    units = ["B", "KiB", "MiB", "GiB", "TiB"]
    lines = []
    for line in text.strip().split("\n"):
        name, _, raw = line.partition("\t")
        size = float(raw)
        if size == 0:
            lines.append(name + ": 0 B")
            continue
        index = 0
        while size >= 1024 and index < len(units) - 1:
            size /= 1024
            index += 1
        lines.append(name + ": " + format(round(size, 1), ".1f") + " " + units[index])
    return "\n".join(lines)

archive.tar	1536
video.mkv	2411724800
notes.txt	0
image.png	1048576

archive.tar: 1.5 KiB
video.mkv: 2.2 GiB
notes.txt: 0 B
image.png: 1.0 MiB

Convert byte sizes to human-readable units using binary multiples (1024), one decimal place, choosing the largest unit that keeps the value >= 1. Zero stays '0 B'. Output 'name: size' lines in the original order.


Submission PIT05U

import csv, io

def transform(text):
    rows = list(csv.DictReader(io.StringIO(text.strip())))
    metrics = sorted({row["metric"] for row in rows})
    table = {}
    for row in rows:
        table.setdefault(row["date"], {})[row["metric"]] = row["value"]
    out = io.StringIO()
    writer = csv.writer(out, lineterminator="\n")
    writer.writerow(["date"] + metrics)
    for date in sorted(table):
        writer.writerow([date] + [table[date].get(metric, "") for metric in metrics])
    return out.getvalue().strip()

Pivot the long-format CSV to wide: one row per date, one column per metric (columns sorted alphabetically). Missing combinations become empty cells. Header starts with 'date'.


Submission OQOLYG

import json

def transform(text):
    flat = {}

    def walk(node, prefix):
        if isinstance(node, dict):
            for key, value in node.items():
                walk(value, prefix + "." + key if prefix else key)
        elif isinstance(node, list):
            for index, value in enumerate(node):
                walk(value, prefix + "." + str(index))
        else:
            flat[prefix] = json.dumps(node)

    walk(json.loads(text), "")
    return "\n".join(path + "=" + flat[path] for path in sorted(flat))

debug=false
server.host="db1"
server.ports.0=5432
server.ports.1=5433

Flatten the nested JSON into dotted paths, indexing list elements by position, and return 'path=value' lines sorted by path. Values are rendered as JSON literals, so strings keep their double quotes and booleans stay lowercase.


Submission 32ZVRD

def transform(text):
    counts = {}
    for word in text.lower().split():
        counts[word] = counts.get(word, 0) + 1
    ordered = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
    return "\n".join(word + "=" + str(count) for word, count in ordered[:3])

Count word frequencies case-insensitively and return the top 3 as 'word=count' lines, ordered by count descending then word ascending.


Submission O6NF88

def transform(text):
    rows = []
    for line in text.rstrip("\n").split("\n"):
        rows.append("chars=" + str(len(line)) + " bytes=" + str(len(line.encode("utf-8"))))
    return "\n".join(rows)

chars=11 bytes=13
chars=10 bytes=12
chars=11 bytes=11

For each line report the character count and the byte length when encoded as UTF-8, as 'chars=<n> bytes=<n>' lines, so that multi-byte characters are visible as a difference.


Submission Z7JCME

def transform(text):
    rows = []
    for index, line in enumerate(text.strip().split("\n"), start=1):
        total = sum(int(cell) if cell.strip() else 0 for cell in line.split(","))
        rows.append("row" + str(index) + ": " + str(total))
    return "\n".join(rows)

Sum each CSV row, treating empty cells as zero, and return 'row<N>: <sum>' lines numbered from 1. A row of only empty cells sums to 0.


Submission 7WCJSK

import json

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    header = lines[0].split('\t')
    rows = []
    for line in lines[1:]:
        values = line.split('\t')
        rows.append(dict(zip(header, values)))
    return json.dumps(rows)

Convert a tab-separated values block (first row is the header) into a JSON array of objects, one per data row.


Submission L32RKS

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.split('=', 1)
            result[section][k.strip()] = v.strip()
    return json.dumps(result)

[server]
host = localhost
port = 8080

[database]
name = mydb
user = admin

Parse a simple INI-style config with [section] headers and key = value lines into a nested JSON object keyed by section, then key.


Submission YXE5PR

import re

def transform(text):
    nums = [float(n) for n in re.findall(r'-?\d+\.?\d*', text)]
    total = sum(nums)
    return str(total) if total != int(total) else str(int(total))

Order #1023: 3 items at 12.50 each, plus 2 items at 7 each, shipping -5 discount

Extract every number (integer or decimal, including negatives) embedded anywhere in the free text and return the sum as a plain string, without a trailing '.0' when the result is a whole number.


Submission 6TDABI

import json

def transform(text):
    pairs = [p.strip() for p in text.strip().split(';') if p.strip()]
    d = {}
    for p in pairs:
        k, v = p.split(':', 1)
        d[k.strip()] = v.strip()
    return json.dumps(dict(sorted(d.items())))

zebra: stripes; apple: fruit; mango: fruit

Parse a semicolon-separated list of 'key: value' pairs into a JSON object with keys sorted alphabetically.


Submission 341ZIF

def transform(text):
    words = text.strip().split()
    result = []
    i = 0
    while i < len(words):
        w = words[i]
        count = 1
        while i + count < len(words) and words[i + count] == w:
            count += 1
        result.append(f"{w}x{count}" if count > 1 else w)
        i += count
    return ' '.join(result)

the the the cat sat sat on on on on the mat

Collapse consecutive duplicate whitespace-separated words into a single 'wordxN' token when N>1 (keep single occurrences as-is), preserving overall word order.


Submission UXYS68

import json

def transform(text):
    lines = [l for l in text.split('\n') if l.strip()]
    rows = []
    for line in lines:
        name = line[0:10].strip()
        age = line[10:13].strip()
        city = line[13:].strip()
        rows.append({"name": name, "age": int(age), "city": city})
    return json.dumps(rows)

Alice      30 New York
Bob        25 Boston

Parse fixed-width text rows (name in columns 0-9, age in columns 10-12, city in the remainder) into a JSON array of objects with name, age (as an integer), and city.


Submission LT72GE

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    header, *rows = lines
    seen = {}
    order = []
    for row in rows:
        key = row.split(',')[0]
        if key not in seen:
            order.append(key)
        seen[key] = row
    out_lines = [header] + [seen[k] for k in order]
    return '\n'.join(out_lines)

Given CSV text with a header row and an id column first, deduplicate rows by id, keeping only the last occurrence of each id, and preserve the first-seen order of ids.


Submission HIRT2F

import json

def transform(text):
    result = {}
    for pair in text.strip().split(','):
        k, v = pair.split('=', 1)
        k, v = k.strip(), v.strip()
        if v.lower() in ('true', 'false'):
            result[k] = v.lower() == 'true'
        else:
            try:
                result[k] = int(v)
            except ValueError:
                try:
                    result[k] = float(v)
                except ValueError:
                    result[k] = v
    return json.dumps(result)

name=Widget, price=19.99, in_stock=true, quantity=42

Parse a comma-separated list of key=value pairs into a JSON object, inferring the type of each value as boolean, integer, float, or string.


Submission NXYQYC

import json

def transform(text):
    result = {}
    for pair in text.strip().split(';'):
        if not pair.strip():
            continue
        tag, value = pair.split(':', 1)
        result[tag.strip()] = value.strip()
    return json.dumps(result)

Parse a semicolon-separated list of tag:value pairs into a JSON object mapping each tag to its value.


Submission ZJ3MI0

import json

def transform(text):
    temps = [float(x.strip()) for x in text.strip().split(',')]
    fahrenheit = [round(t * 9/5 + 32, 1) for t in temps]
    return json.dumps(fahrenheit)

Parse a comma-separated list of Celsius temperature readings and convert them to Fahrenheit, rounded to 1 decimal place, returned as a JSON array.