Submission C3UEMK

import csv
import io
import re

HEAD = re.compile(r'^\s*INSERT\s+INTO\s+([A-Za-z_][A-Za-z_0-9]*)\s*\(([^)]*)\)\s*VALUES\s*(.*)$',
                  re.IGNORECASE | re.DOTALL)

def _split_statements(text):
    kept = []
    for line in text.split('\n'):
        if line.strip().startswith('--'):
            continue
        kept.append(line)
    body = '\n'.join(kept)
    statements = []
    buf = []
    in_string = False
    i = 0
    while i < len(body):
        ch = body[i]
        if in_string:
            buf.append(ch)
            if ch == "'":
                if i + 1 < len(body) and body[i + 1] == "'":
                    buf.append("'")
                    i += 2
                    continue
                in_string = False
            i += 1
            continue
        if ch == "'":
            in_string = True
            buf.append(ch)
            i += 1
            continue
        if ch == ';':
            statements.append(''.join(buf))
            buf = []
            i += 1
            continue
        buf.append(ch)
        i += 1
    if ''.join(buf).strip():
        statements.append(''.join(buf))
    return statements

def _split_tuples(blob):
    tuples = []
    depth = 0
    in_string = False
    buf = []
    i = 0
    while i < len(blob):
        ch = blob[i]
        if in_string:
            buf.append(ch)
            if ch == "'":
                if i + 1 < len(blob) and blob[i + 1] == "'":
                    buf.append("'")
                    i += 2
                    continue
                in_string = False
            i += 1
            continue
        if ch == "'":
            in_string = True
            buf.append(ch)
        elif ch == '(':
            depth += 1
            if depth == 1:
                buf = []
                i += 1
                continue
            buf.append(ch)
        elif ch == ')':
            depth -= 1
            if depth == 0:
                tuples.append(''.join(buf))
                buf = []
                i += 1
                continue
            buf.append(ch)
        else:
            if depth >= 1:
                buf.append(ch)
        i += 1
    return tuples

def _split_values(chunk):
    values = []
    buf = []
    in_string = False
    i = 0
    while i < len(chunk):
        ch = chunk[i]
        if in_string:
            if ch == "'":
                if i + 1 < len(chunk) and chunk[i + 1] == "'":
                    buf.append("'")
                    i += 2
                    continue
                in_string = False
                buf.append(ch)
                i += 1
                continue
            buf.append(ch)
            i += 1
            continue
        if ch == "'":
            in_string = True
            buf.append(ch)
            i += 1
            continue
        if ch == ',':
            values.append(''.join(buf))
            buf = []
            i += 1
            continue
        buf.append(ch)
        i += 1
    values.append(''.join(buf))
    return values

def _cell(raw):
    token = raw.strip()
    if token.startswith("'") and token.endswith("'") and len(token) >= 2:
        return token[1:-1]
    upper = token.upper()
    if upper == 'NULL':
        return ''
    if upper == 'TRUE':
        return 'true'
    if upper == 'FALSE':
        return 'false'
    return token

def transform(text):
    header = None
    rows = []
    for statement in _split_statements(text):
        match = HEAD.match(statement)
        if not match:
            continue
        table, columns, blob = match.groups()
        if table.lower() != 'staff':
            continue
        if header is None:
            header = [c.strip() for c in columns.split(',')]
        for chunk in _split_tuples(blob):
            rows.append([_cell(v) for v in _split_values(chunk)])

    out = io.StringIO()
    writer = csv.writer(out, lineterminator='\n')
    if header is not None:
        writer.writerow(header)
    for row in rows:
        writer.writerow(row)
    result = out.getvalue()
    if result.endswith('\n'):
        result = result[:-1]
    return result

INSERT INTO staff (id, name, title, salary, active) VALUES (1, 'Ada Lovelace', 'Analyst', 91000.00, TRUE);
INSERT INTO staff (id, name, title, salary, active) VALUES
  (2, 'Grace O''Hara', 'Lead, Platform', 128500.5, TRUE),
  (3, 'Linus T', NULL, 74000, FALSE);
-- a commented out row
-- INSERT INTO staff (id, name) VALUES (99, 'ghost');
INSERT INTO audit (id, note) VALUES (7, 'ignored table');
INSERT INTO staff (id, name, title, salary, active) VALUES (4, 'Ren "Rex" Diaz', 'QA', 66000, true);

id,name,title,salary,active
1,Ada Lovelace,Analyst,91000.00,true
2,Grace O'Hara,"Lead, Platform",128500.5,true
3,Linus T,,74000,false
4,"Ren ""Rex"" Diaz",QA,66000,true

Extract rows from SQL INSERT statements into RFC 4180 CSV, keeping only the table named 'staff'.

Rules:
1. A line whose stripped form starts with '--' is a comment and is removed before parsing. '--' inside a
   single-quoted string literal is NOT a comment (only whole-line comments exist in this input).
2. Statements are terminated by ';' and may span several lines. Whitespace between tokens is arbitrary.
3. Only statements matching 'INSERT INTO <table> (<columns>) VALUES <tuples>' are used; the keywords are
   matched case-insensitively. Statements for any table other than 'staff' are skipped.
4. A statement may carry several comma-separated value tuples; each tuple becomes one output row.
5. Literal forms inside a tuple: a single-quoted string where '' is an escaped single quote; a number; the
   bare word NULL (any case); the bare words TRUE/FALSE (any case).
6. Conversion to CSV cell text: strings use their unescaped content; numbers use their literal text
   verbatim (so '128500.5' stays '128500.5' and '74000' stays '74000'); NULL becomes the empty cell;
   TRUE/FALSE become the lowercase words 'true' and 'false'.

Output: a header row built from the column list of the FIRST kept statement, then all data rows in
statement order and, within a statement, tuple order. Serialise with Python's csv module using the comma
delimiter, minimal quoting with '"' doubling, and a plain '\n' line terminator (NOT '\r\n'). Return the
CSV text with the final '\n' removed so there is no trailing newline and no carriage returns anywhere.


Submission FWN30D

from urllib.parse import unquote

CANON = {
    'domain': 'Domain',
    'path': 'Path',
    'expires': 'Expires',
    'max-age': 'Max-Age',
    'samesite': 'SameSite',
    'secure': 'Secure',
    'httponly': 'HttpOnly',
}
SAMESITE = {'strict': 'Strict', 'lax': 'Lax', 'none': 'None'}

def transform(text):
    cookies = {}
    order = []
    for raw in text.split('\n'):
        line = raw.strip()
        if not line or ':' not in line:
            continue
        header, value = line.split(':', 1)
        if header.strip().lower() != 'set-cookie':
            continue
        segments = [s.strip() for s in value.split(';')]
        if not segments or not segments[0]:
            continue
        first = segments[0]
        if '=' in first:
            name, cookie_value = first.split('=', 1)
        else:
            name, cookie_value = first, ''
        name = name.strip()
        attrs = {}
        for segment in segments[1:]:
            if not segment:
                continue
            if '=' in segment:
                key, val = segment.split('=', 1)
                key = key.strip().lower()
                val = val.strip()
            else:
                key, val = segment.strip().lower(), ''
            canon = CANON.get(key)
            if canon is None:
                continue
            attrs[canon] = val
        domain = attrs.get('Domain', '') or '-'
        path = attrs.get('Path', '') or '/'
        key = (name, domain, path)
        if key not in cookies:
            order.append(key)
        cookies[key] = (cookie_value.strip(), attrs, domain, path)

    lines = []
    for key in sorted(cookies):
        cookie_value, attrs, domain, path = cookies[key]
        decoded = unquote(cookie_value)
        if decoded == '':
            decoded = '(empty)'
        flags = [f for f in ('Secure', 'HttpOnly') if f in attrs]
        flag_text = '+'.join(flags) if flags else '-'
        samesite = attrs.get('SameSite')
        samesite_text = SAMESITE.get(samesite.strip().lower(), samesite) if samesite else '-'
        max_age = attrs.get('Max-Age')
        max_age_text = str(int(max_age)) if max_age not in (None, '') else '-'
        expires = attrs.get('Expires')
        expires_text = expires if expires else '-'
        lines.append(
            '%s | %s | domain=%s | path=%s | flags=%s | samesite=%s | max-age=%s | expires=%s'
            % (key[0], decoded, domain, path, flag_text, samesite_text,
               max_age_text, expires_text))
    return '\n'.join(lines)

Set-Cookie: sid=3f9a2b; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600
Set-Cookie: theme=dark; Path=/; Expires=Wed, 09 Jun 2027 10:18:14 GMT
Set-Cookie: sid=deadbeef; Domain=.example.com; Path=/admin; secure; samesite=strict
Set-Cookie: tracking=; Path=/; Max-Age=0
Set-Cookie: prefs=lang%3Den-GB
X-Frame-Options: DENY

prefs | lang=en-GB | domain=- | path=/ | flags=- | samesite=- | max-age=- | expires=-
sid | 3f9a2b | domain=- | path=/ | flags=Secure+HttpOnly | samesite=Lax | max-age=3600 | expires=-
sid | deadbeef | domain=.example.com | path=/admin | flags=Secure | samesite=Strict | max-age=- | expires=-
theme | dark | domain=- | path=/ | flags=- | samesite=- | max-age=- | expires=Wed, 09 Jun 2027 10:18:14 GMT
tracking | (empty) | domain=- | path=/ | flags=- | samesite=- | max-age=0 | expires=-

Parse HTTP Set-Cookie response headers into an attribute table.

Rules:
1. Only lines whose header name is 'set-cookie' (case-insensitive, split on the first ':') are used; every
   other header line is ignored.
2. The value is split on ';'. The FIRST segment is 'name=value' (split on the first '='); later segments
   are attributes, each either 'key=value' or a bare flag. Segments are stripped of surrounding spaces.
3. Attribute keys are matched case-insensitively and reported in canonical spelling: Domain, Path,
   Expires, Max-Age, SameSite, Secure, HttpOnly. Unknown attributes are ignored.
4. Cookie identity is the pair (name, Domain, Path) where a missing Domain is the literal '-' and a
   missing Path is '/'. Two Set-Cookie lines with the same identity: the later one wins completely (it
   replaces the earlier one, it does not merge). Different identities coexist.
5. The cookie value is reported percent-decoded (so 'lang%3Den-GB' becomes 'lang=en-GB'); '+' is NOT
   treated as a space. An empty value is reported as the literal '(empty)'.
6. Flags: report 'Secure' and 'HttpOnly' as the literal words when present, joined by '+', in that fixed
   order; when neither is present report '-'.
7. SameSite is normalised to capitalised form: Strict, Lax or None. Absent SameSite reports '-'.
8. Max-Age reports the integer as given; when absent report '-'. Expires reports the raw string as given;
   when absent report '-'.

Output: one line per surviving cookie, ordered by name ascending, then Domain ascending, then Path
ascending (ordinary Python string comparison), formatted
    '<name> | <value> | domain=<d> | path=<p> | flags=<f> | samesite=<s> | max-age=<m> | expires=<e>'
Join with '\n'; no trailing newline and no trailing whitespace on any line.


Submission NJQ1Y1

import csv
import io
from decimal import Decimal, ROUND_HALF_UP

REGIONS = {
    'Europe': ['DE', 'FR', 'GB', 'ES', 'IT', 'NL', 'PL', 'SE'],
    'Americas': ['US', 'CA', 'BR', 'MX', 'AR', 'CL'],
    'Asia': ['JP', 'IN', 'CN', 'SG', 'KR', 'ID'],
    'Africa': ['ZA', 'KE', 'NG', 'EG', 'MA'],
    'Oceania': ['AU', 'NZ', 'FJ'],
}
CODE_TO_REGION = {}
for _region, _codes in REGIONS.items():
    for _code in _codes:
        CODE_TO_REGION[_code] = _region

CENTS = Decimal('0.01')
TENTH = Decimal('0.1')
HUNDRED = Decimal(100)

def transform(text):
    reader = csv.reader(io.StringIO(text))
    rows = [row for row in reader if row and any(cell.strip() for cell in row)]
    stats = {}
    grand_orders = 0
    grand_total = Decimal(0)
    for row in rows[1:]:
        code = row[1].strip().upper() if len(row) > 1 else ''
        amount = Decimal(row[2].strip()) if len(row) > 2 and row[2].strip() else Decimal(0)
        region = CODE_TO_REGION.get(code, 'Unknown')
        entry = stats.setdefault(region, {'orders': 0, 'total': Decimal(0), 'codes': set()})
        entry['orders'] += 1
        entry['total'] += amount
        entry['codes'].add(code if code else '(blank)')
        grand_orders += 1
        grand_total += amount

    ordered = sorted(stats.items(), key=lambda kv: (-kv[1]['total'], kv[0]))

    lines = []
    for region, entry in ordered:
        total_major = (entry['total'] / HUNDRED).quantize(CENTS, rounding=ROUND_HALF_UP)
        if grand_total:
            share = (entry['total'] / grand_total * HUNDRED).quantize(
                TENTH, rounding=ROUND_HALF_UP)
        else:
            share = Decimal('0.0')
        codes = '/'.join(sorted(entry['codes']))
        lines.append('%s: orders=%d total=%s share=%s%% codes=%s'
                     % (region, entry['orders'], str(total_major), str(share), codes))
    grand_major = (grand_total / HUNDRED).quantize(CENTS, rounding=ROUND_HALF_UP)
    lines.append('TOTAL: orders=%d total=%s' % (grand_orders, str(grand_major)))
    return '\n'.join(lines)

Asia: orders=2 total=905.00 share=54.8% codes=IN/JP
Europe: orders=4 total=320.50 share=19.4% codes=DE/FR/GB
Oceania: orders=1 total=200.00 share=12.1% codes=AU
Americas: orders=3 total=172.99 share=10.5% codes=BR/CA/US
Africa: orders=1 total=33.00 share=2.0% codes=KE
Unknown: orders=2 total=19.00 share=1.2% codes=(blank)/ZZ
TOTAL: orders=13 total=1650.49

The input is CSV with header 'order_id,country,amount_minor'. Roll order amounts up to macro regions.

Use exactly this ISO 3166-1 alpha-2 to region map (codes compared case-insensitively after stripping):
  Europe: DE, FR, GB, ES, IT, NL, PL, SE
  Americas: US, CA, BR, MX, AR, CL
  Asia: JP, IN, CN, SG, KR, ID
  Africa: ZA, KE, NG, EG, MA
  Oceania: AU, NZ, FJ
Any code not in the map, and any empty code, rolls up to the region 'Unknown'.

amount_minor is an integer number of minor currency units. For each region compute:
  - orders: number of rows
  - total: sum of amount_minor rendered as a major-unit amount with exactly 2 decimals (divide by 100
    using Decimal, never float)
  - share: the region's total as a percentage of the grand total, as a Decimal rounded to one decimal
    place with ROUND_HALF_UP
  - codes: the distinct uppercased country codes seen in that region, sorted ascending and joined by '/';
    an empty code is represented by the literal '(blank)' and sorts as that literal string

Ordering: regions sorted by total DESCENDING; ties broken by region name ascending. 'Unknown' takes part
in the same ordering rule and is not special-cased. Regions with no rows are omitted.

Output: one line per region formatted
    '<region>: orders=<n> total=<t> share=<s>% codes=<codes>'
then a final line 'TOTAL: orders=<n> total=<t>'. Join with '\n'; no trailing newline and no trailing
whitespace on any line.


Submission O16YOT

1. HELLO WORLD
2. SOS NOW. AT 2148
3. MAYDAY[?] : !
4. [?] ABC
undecodable=2

Decode International Morse Code into text.

Structure: each input line is a message. Within a line, ' / ' (slash surrounded by spaces, or a bare '/'
token) separates words, and single spaces separate letters. Blank lines are skipped entirely and produce
no output line.

Supported codes: the 26 ASCII letters A-Z, the digits 0-9, and the punctuation '.' (.-.-.-), ',' (--..--),
'?' (..--..), "'" (.----.), '!' (-.-.--), '/' (-..-.), '(' (-.--.), ')' (-.--.-), '&' (.-...),
':' (---...), ';' (-.-.-.), '=' (-...-), '+' (.-.-.), '-' (-....-), '_' (..--.-), '"' (.-..-.),
'$' (...-..-), '@' (.--.-.). Decoded letters are uppercase.

Unknown edge case: a letter token that is not in the table decodes to the literal three-character sequence
'[?]' and is counted as an undecodable token. A token containing any character other than '.' and '-' is
also undecodable and decodes to '[?]'.

Words within a message are joined by a single space; letters are concatenated with no separator.

Output: one line per non-blank input line, in order, formatted '<n>. <decoded>' where <n> is a 1-based
counter over the emitted lines only. After all message lines, append a final line
    'undecodable=<count>'
with the total number of undecodable tokens across all messages. Join with '\n'; no trailing newline and
no trailing whitespace on any line.


Submission X3ORPC

MAJOR_CATS = {'removed', 'breaking'}
MINOR_CATS = {'added', 'changed', 'deprecated'}
PATCH_CATS = {'fixed', 'security', 'performance'}

def transform(text):
    blocks = []
    current = []
    for raw in text.split('\n'):
        line = raw.strip()
        if line == '---':
            blocks.append(current)
            current = []
            continue
        if line:
            current.append(line)
    blocks.append(current)

    releases = []
    index = 0
    while index < len(blocks):
        block = blocks[index]
        if block and block[0].lower().startswith('current:'):
            version = block[0].split(':', 1)[1].strip()
            changes = blocks[index + 1] if index + 1 < len(blocks) else []
            releases.append((version, changes))
            index += 2
            continue
        index += 1

    lines = []
    for version, changes in releases:
        level = 0
        for change in changes:
            if ':' not in change:
                continue
            category = change.split(':', 1)[0].strip().lower()
            if category in MAJOR_CATS:
                level = max(level, 3)
            elif category in MINOR_CATS:
                level = max(level, 2)
            elif category in PATCH_CATS:
                level = max(level, 1)
        if level == 0:
            lines.append('%s -> %s (none)' % (version, version))
            continue
        core = version.split('+', 1)[0].split('-', 1)[0]
        parts = core.split('.')
        major, minor, patch = int(parts[0]), int(parts[1]), int(parts[2])
        if level == 3:
            if major == 0:
                minor += 1
                patch = 0
                label = 'minor(major-demoted)'
            else:
                major += 1
                minor = 0
                patch = 0
                label = 'major'
        elif level == 2:
            minor += 1
            patch = 0
            label = 'minor'
        else:
            patch += 1
            label = 'patch'
        nxt = '%d.%d.%d' % (major, minor, patch)
        lines.append('%s -> %s (%s)' % (version, nxt, label))
    return '\n'.join(lines)

current: 2.4.9
---
added: streaming export endpoint
fixed: crash when the manifest is empty
deprecated: legacy /v1/search remains but warns
security: patch header smuggling in the proxy
---
current: 0.7.3
---
removed: the XML serialiser
fixed: retry accounting off by one
---
current: 1.0.0
---
changed: default page size is now 50
added: cursor pagination
---
current: 3.1.4
---
docs: rewrote the quickstart
chore: pinned CI image
---
current: 1.9.2-rc.1+build.7
---
fixed: nothing important

Decide the next SemVer 2.0.0 version for each release block.

Input structure: a sequence of blocks separated by lines containing exactly '---'. A block that starts
with 'current: <version>' opens a release; the block that follows it holds that release's change lines.
Each change line is '<category>: <text>'; the category is lowercased and stripped.

Bump rules, most severe wins:
- 'removed' or 'breaking' -> MAJOR
- 'added' or 'changed' or 'deprecated' -> MINOR
- 'fixed' or 'security' or 'performance' -> PATCH
- any other category (for example 'docs' or 'chore') contributes NOTHING
If no change line contributes anything, the version is unchanged and the bump is reported as 'none'.

Applying the bump to MAJOR.MINOR.PATCH:
- MAJOR: major+1, minor=0, patch=0 -- EXCEPT while major is 0, where SemVer's initial-development clause
  applies and a MAJOR bump is demoted to minor+1, patch=0 (so 0.7.3 becomes 0.8.0, not 1.0.0). The report
  still names the demoted level as 'minor(major-demoted)'.
- MINOR: minor+1, patch=0
- PATCH: patch+1
Any pre-release and build-metadata suffix on the current version is DROPPED by any non-'none' bump; with
bump 'none' the current version string is echoed unchanged including its suffixes.

Output: one line per release, in input order, formatted '<current> -> <next> (<bump>)' where <bump> is
'major', 'minor', 'patch', 'none' or 'minor(major-demoted)'. Join with '\n'; no trailing newline and no
trailing whitespace on any line.


Submission Y6EXTL

def transform(text):
    rows = []
    for line in text.strip().split('\n')[1:]:
        if not line.strip():
            continue
        name, dept, salary = [p.strip() for p in line.split(',')]
        rows.append((dept, name, int(salary)))
    groups = {}
    for dept, name, salary in rows:
        groups.setdefault(dept, []).append((name, salary))
    out = []
    for dept in sorted(groups):
        members = groups[dept]
        total = sum(s for _, s in members)
        top = sorted(members, key=lambda ns: (-ns[1], ns[0]))[0][0]
        out.append('{}: {}, {}, {}'.format(dept, len(members), total, top))
    return '\n'.join(out)

name,dept,salary
zed,eng,100
amy,eng,120
bo,ops,90
cy,eng,120
dee,ops,95

Given rows of 'name,dept,salary', return one line per department as 'dept: count, total, top' where top is the highest-paid member, ties broken alphabetically. Departments are ordered alphabetically.


Submission TE49VY

def transform(text):
    seen = {}
    for part in text.split(';'):
        if not part.strip():
            continue
        key, _, value = part.partition('=')
        seen[key.strip()] = value.strip()
    return '\n'.join('{} -> {}'.format(k, seen[k]) for k in sorted(seen))

Read semicolon-separated key=value pairs and return them as sorted 'key -> value' lines, where a key repeated later overrides the earlier value and blank segments are ignored.


Submission Y4VZNB

def transform(text):
    counters = []
    out = []
    for line in text.strip().split('\n'):
        if not line.strip():
            continue
        depth_s, _, title = line.partition('|')
        depth = int(depth_s)
        while len(counters) > depth + 1:
            counters.pop()
        if len(counters) == depth + 1:
            counters[depth] += 1
        else:
            counters.append(1)
        number = '.'.join(str(c) for c in counters) + '.'
        out.append('{} {}'.format(number, title.strip()))
    return '\n'.join(out)

0|Intro
1|Scope
1|Audience
0|Method
1|Setup
2|Hardware
0|Results

1. Intro
1.1. Scope
1.2. Audience
2. Method
2.1. Setup
2.1.1. Hardware
3. Results

Convert an ordered list of 'depth|text' outline rows into numbered section headings such as 1., 1.1., 1.2., 2. Depth 0 is a top-level section. Output 'number text' per line.


Submission 6O4NRK

import re

def transform(text):
    words = re.findall(r"[A-Za-z']+", text.lower())
    counts = {}
    for w in words:
        counts[w] = counts.get(w, 0) + 1
    ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
    return ','.join('{}:{}'.format(w, c) for w, c in ordered)

The cat sat. The CAT ran! A dog's day; the dog's day.

Given a block of text, return each distinct word lowercased with its count, ordered by descending count then alphabetically, as 'word:count' on one line separated by commas. Words are runs of letters and apostrophes; punctuation is stripped.


Submission 1JHEAG

def transform(text):
    out = []
    for line in text.rstrip('\n').split('\n'):
        if line.startswith('  ') and out:
            out[-1] = out[-1] + ' ' + line.strip()
        elif line.strip():
            key, _, value = line.partition(':')
            out.append('{}={}'.format(key.strip(), value.strip()))
    return '\n'.join(out)

title: The Long
  and Winding Road
artist: Someone
notes: first
  second
  third

title=The Long and Winding Road
artist=Someone
notes=first second third

Given lines of 'field: value' where a value may continue onto following lines that start with two spaces, join each continuation onto its field with a single space and return 'field=value' lines in the original order.


Submission GNZYYY

import json

def transform(text):
    result = {}
    for line in text.strip().split("\n"):
        if ":" not in line:
            continue
        key, value = line.split(":", 1)
        key = key.strip()
        value = value.strip()
        if value.lower() == "true":
            typed = True
        elif value.lower() == "false":
            typed = False
        elif value.lstrip("-").isdigit():
            typed = int(value)
        else:
            try:
                typed = float(value)
            except ValueError:
                typed = value
        result[key] = typed
    return json.dumps(result)

name: Widget
price: 19.99
in_stock: true
quantity: 42
discontinued: false

Parse simple 'key: value' lines into a JSON object, inferring booleans, integers, floats, and falling back to strings.


Submission X8TOQH

import json

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

[server]
host=localhost
port=8080
[database]
name=appdb
timeout=30

Parse an INI-style config file into a nested JSON object grouped by section, converting numeric values to integers.


Submission CJMQT6

import json

def transform(text):
    lines = [l for l in text.strip("\n").split("\n") if l.strip()]
    header = lines[0]
    col_starts = []
    for i, ch in enumerate(header):
        if ch != " " and (i == 0 or header[i-1] == " "):
            col_starts.append(i)
    names = header.split()
    rows = []
    for line in lines[1:]:
        values = []
        for idx, start in enumerate(col_starts):
            end = col_starts[idx + 1] if idx + 1 < len(col_starts) else len(line)
            values.append(line[start:end].strip())
        row = dict(zip(names, values))
        if "AGE" in row:
            row["AGE"] = int(row["AGE"])
        rows.append(row)
    return json.dumps(rows)

NAME      AGE  CITY
Alice     30   Boston
Bob       25   Denver
Carol     41   Reno

Convert a fixed-width column-aligned text table (header + rows) into a JSON list of objects, converting the AGE column to an integer.


Submission 9FR6GJ

import csv, io

def transform(text):
    lines = [l for l in text.strip("\n").split("\n") if l.strip()]
    rows = []
    for line in lines:
        fields = [f.strip('"') for f in line.split('";"')]
        fields[0] = fields[0].lstrip('"')
        fields[-1] = fields[-1].rstrip('"')
        rows.append(fields)
    out = io.StringIO()
    writer = csv.writer(out)
    for row in rows:
        writer.writerow(row)
    return out.getvalue().strip()

"Smith; John";"42";"New York; NY"
"Doe; Jane";"31";"Austin; TX"

Smith; John,42,New York; NY
Doe; Jane,31,Austin; TX

Convert semicolon-quoted rows like '"Field; A";"Field2"' into standard comma-separated CSV rows, preserving embedded semicolons inside each quoted field.


Submission VNPIAA

import json
from collections import defaultdict

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    header = lines[0].split(",")
    totals = defaultdict(float)
    for line in lines[1:]:
        parts = line.split(",")
        row = dict(zip(header, parts))
        revenue = int(row["qty"]) * float(row["price"])
        totals[row["product"]] += revenue
    rounded = {k: round(v, 2) for k, v in sorted(totals.items())}
    return json.dumps(rounded)

product,qty,price
widget,3,9.99
gadget,1,19.99
widget,2,9.99
gizmo,5,4.50
gadget,2,19.99

Compute total revenue (qty * price) per product from CSV lines with a header row, rounding each total to 2 decimal places.


Submission EIKBHF

import json, re

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    result = []
    for line in lines:
        m = re.match(r"- \[( |x)\] (.+)", line)
        done = m.group(1) == "x"
        result.append({"text": m.group(2), "done": done})
    return json.dumps(result)

- [ ] Buy milk
- [x] Walk dog
- [ ] Write report
- [x] Pay bills

Buy milk

Walk dog

Write report

Pay bills

Parse a Markdown todo list ('- [ ]' or '- [x]') into a JSON list of {text, done} objects.


Submission XDFHNB

import json

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    result = [round(float(l) * 9 / 5 + 32, 1) for l in lines]
    return json.dumps(result)

Convert a list of Celsius temperature lines into a JSON list of Fahrenheit values rounded to 1 decimal.


Submission 9TP05X

import json

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    header = lines[0].split(",")
    rows = []
    for line in lines[1:]:
        values = line.split(",")
        row = {}
        for k, v in zip(header, values):
            row[k] = int(v) if v.isdigit() else v
        rows.append(row)
    return json.dumps(rows)

Convert CSV with a header row into a JSON list of objects, converting numeric-looking values to integers.


Submission J42LE1

import json

def flatten(d, prefix=""):
    items = {}
    for k, v in d.items():
        key = f"{prefix}.{k}" if prefix else k
        if isinstance(v, dict):
            items.update(flatten(v, key))
        else:
            items[key] = v
    return items

def transform(text):
    data = json.loads(text)
    return json.dumps(flatten(data))

Flatten a nested JSON object into a single-level JSON object with dot-notation keys.


Submission J5N6JV

import json

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    result = []
    for line in lines:
        name, email = line.split(",")
        result.append({"name": name.strip(), "email": email.strip().lower()})
    return json.dumps(result)

Alice Smith,ALICE@Example.com
Bob Jones,BOB@test.COM

Convert 'name,email' CSV lines into a JSON list of objects with lower-cased email addresses.


Submission TWIGJE

import csv, io

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    header = lines[0].split(",")
    out = io.StringIO()
    writer = csv.writer(out)
    writer.writerow(header + ["running_total"])
    running = 0
    for line in lines[1:]:
        parts = line.split(",")
        running += int(parts[1])
        writer.writerow(parts + [str(running)])
    return out.getvalue().strip()

item,amount,running_total
coffee,4,4
bagel,3,7
tea,2,9

Add a cumulative running-total column to CSV data and return the result as a CSV string.


Submission 00NPXN

import json

def transform(text):
    data = json.loads(text)
    merged = {}
    order = []
    for row in data:
        rid = row["id"]
        if rid not in merged:
            order.append(rid)
            merged[rid] = {}
        merged[rid].update(row)
    return json.dumps([merged[rid] for rid in order])

Merge a JSON list of records by id, where later records override or add fields from earlier ones with the same id.


Submission H5XBJK

import math

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    points = [tuple(map(float, l.split(","))) for l in lines]
    total = 0.0
    for i in range(len(points) - 1):
        x1, y1 = points[i]
        x2, y2 = points[i + 1]
        total += math.hypot(x2 - x1, y2 - y1)
    return str(round(total, 2))

Given a list of x,y coordinate lines describing a path in order, compute the total Euclidean path distance rounded to 2 decimals.


Submission C3CZQ9

import json

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

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

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


Submission PX86QD

import re, json

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    result = []
    for line in lines:
        h = re.search(r"(\d+)h", line)
        m = re.search(r"(\d+)m", line)
        total = (int(h.group(1)) * 60 if h else 0) + (int(m.group(1)) if m else 0)
        result.append(total)
    return json.dumps(result)

Parse duration strings like '1h30m', '45m', or '2h' into a JSON list of total minutes.


Submission NDNG9M

import csv, io, json

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

"Smith, John",42,"Boston, MA"
"Doe, Jane",31,"Austin, TX"

Parse CSV rows where fields may be quoted and contain embedded commas, converting to a JSON list of [name, age, city] arrays.


Submission RC2DTV

import json
from collections import defaultdict

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    totals = defaultdict(int)
    for line in lines:
        name, qty = line.split(":")
        totals[name] += int(qty)
    return json.dumps(dict(sorted(totals.items())))

apple:3
banana:5
apple:2
cherry:1
banana:1

Sum quantities per fruit name from 'name:qty' lines and return a JSON object sorted by name.


Submission 8BKEAM

import json

def transform(text):
    stripped = text.strip()
    words = stripped.split()
    char_count = len(stripped.replace(" ", ""))
    return json.dumps({"word_count": len(words), "char_count": char_count})

The quick brown fox jumps over the lazy dog. The dog barks.

Compute word count and character count (excluding spaces) of a paragraph, returned as a JSON object.


Submission SRI729

def transform(text):
    return " ".join(word[::-1] for word in text.strip().split())

Reverse each word's letters individually while preserving word order.


Submission 2MWJ2Q

import json

def transform(text):
    lines = [l for l in text.strip("\n").split("\n") if l.strip()]
    result = []
    for line in lines:
        level = 0
        while line[level] == "#":
            level += 1
        result.append({"level": level, "text": line[level:].strip()})
    return json.dumps(result)

# Title
## Section A
## Section B
### Subsection B1

Title

Section A

Section B

Subsection B1

Convert a Markdown heading outline (# levels) into a JSON list of {level, text} objects.


Submission RXJP1U

import json
from collections import defaultdict

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    groups = defaultdict(list)
    for line in lines:
        fields = dict(p.split("=") for p in line.split("|"))
        groups[fields["dept"]].append(fields)
    return json.dumps(dict(groups))

Parse pipe-delimited key=value log lines and group the records into a JSON object keyed by 'dept'.


Submission N790QP

import json, re

def transform(text):
    pairs = re.findall(r"<(\w+)>(.*?)</\1>", text.strip())
    return json.dumps(dict(pairs))

Parse simple flat XML-like tags (no nesting or attributes) into a JSON object.


Submission OCWIE0

import re, json

def transform(text):
    nums = [int(n) for n in re.findall(r"\d+", text)]
    product = 1
    for n in nums:
        product *= n
    return json.dumps({"sum": sum(nums), "product": product})

There are 12 apples, 7 oranges, and 100 bananas in stock.

Extract all integers from free text and return their sum and product as a JSON object.


Submission 8OY8VR

import json, csv, io

def transform(text):
    data = json.loads(text)
    out = io.StringIO()
    writer = csv.DictWriter(out, fieldnames=list(data[0].keys()))
    writer.writeheader()
    for row in data:
        writer.writerow(row)
    return out.getvalue().strip()

Convert a JSON array of flat objects into a CSV string with a header row.


Submission 19JWPB

import json

def transform(text):
    lines = [l for l in text.strip().split("\n") if l.strip()]
    result = []
    ops = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b, "/": lambda a, b: a / b}
    for line in lines:
        a, op, b = line.split()
        result.append(ops[op](float(a), float(b)))
    return json.dumps(result)

Parse simple two-operand arithmetic expressions (one per line) and return a JSON list of computed results.


Submission G22XP6

import json

def transform(text):
    data = json.loads(text)
    total = sum(item["price"] for item in data)
    return str(total)

Parse a JSON array of objects and return the sum of the 'price' field as a string.


Submission 0MURLP

def transform(text):
    lines = [l[2:] for l in text.strip().split("\n") if l.startswith("- ")]
    return "\n".join(f"{i+1}. {item}" for i, item in enumerate(lines))

Convert a markdown bullet list (lines starting with '- ') into a numbered plain text list ('1. apple', etc.), joined by newlines.


Submission A058EY

def transform(text):
    lines = text.split("\n")
    return "\n".join("|".join(line.split("\t")) for line in lines)

Convert tab-separated rows of text into pipe-separated rows ('|' between fields), preserving row order.


Submission P0WBKL

from collections import Counter

def transform(text):
    words = text.lower().split()
    counts = Counter(words)
    ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
    return "\n".join(f"{w}:{c}" for w, c in ordered)

the quick brown fox the lazy dog the fox

the:3
fox:2
brown:1
dog:1
lazy:1
quick:1

Count word frequencies (case-insensitive) and return lines 'word:count' sorted by count descending then word ascending, joined by newlines.


Submission ZOHTKF

def transform(text):
    fs = [float(x) for x in text.split(",")]
    cs = [round((f - 32) * 5 / 9, 1) for f in fs]
    return ",".join(str(c) for c in cs)

Parse a comma-separated list of Fahrenheit temperatures and return a comma-separated list of Celsius equivalents rounded to 1 decimal place.


Submission S50FLN

import ast

def transform(text):
    data = ast.literal_eval(text)
    return repr({v: k for k, v in data.items()})

Parse a Python dict literal with unique integer values and return the value-to-key inverse mapping (as repr).


Submission 4GCGE0

def transform(text):
    lines = text.strip().split("\n")
    header = lines[0].split(",")
    result = []
    for line in lines[1:]:
        values = line.split(",")
        result.append(dict(zip(header, values)))
    return result

Parse CSV text (comma-separated, first row header) into a list of dicts mapping header to value; keep age as a string.


Submission ZLVWCA

import re

def transform(text):
    nums = [int(n) for n in re.findall(r"-?\d+", text)]
    return sum(nums)

I have 3 apples, 5 oranges and lost 2 along the way.

Extract all integers appearing in the text and return their sum as an int.


Submission ZKDJFY

import ast

def transform(text):
    data = ast.literal_eval(text)
    def to_camel(k):
        parts = k.split("_")
        return parts[0] + "".join(p.capitalize() for p in parts[1:])
    return repr({to_camel(k): v for k, v in data.items()})

{'first_name': 'Alice', 'last_name': 'Smith'}

{'firstName': 'Alice', 'lastName': 'Smith'}

Parse a Python dict literal with snake_case keys and return a new dict literal (as its repr) with camelCase keys, same values.


Submission D29KJ9

import ast

def flatten(lst):
    result = []
    for item in lst:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

def transform(text):
    data = ast.literal_eval(text)
    return repr(flatten(data))

Parse a Python list literal that may contain nested lists and return a fully flattened list (as its repr).


Submission YN9W3T

def transform(text):
    result = {}
    for line in text.strip().split("\n"):
        k, v = line.split("=", 1)
        if v == "true":
            v = True
        elif v == "false":
            v = False
        elif v.isdigit():
            v = int(v)
        result[k] = v
    return repr(result)

{'host': 'localhost', 'port': 8080, 'debug': True}

Parse simple 'key=value' lines into a dict, converting 'true'/'false' to booleans and numeric strings to ints, and return the dict's repr.


Submission LNE3ZD

import ast

def transform(text):
    data = ast.literal_eval(text)
    result = {"even": [], "odd": []}
    for n in data:
        if n % 2 == 0:
            result["even"].append(n)
        else:
            result["odd"].append(n)
    return repr(result)

Parse a Python list literal of integers and bucket them into a dict with keys 'even' and 'odd', each mapping to a list of the matching numbers in original order, returned as repr.


Submission P80KHB

import ast

def transform(text):
    data = ast.literal_eval(text)
    if not data:
        return repr([])
    result = []
    prev = data[0]
    count = 1
    for item in data[1:]:
        if item == prev:
            count += 1
        else:
            result.append((prev, count))
            prev = item
            count = 1
    result.append((prev, count))
    return repr(result)

Parse a Python list literal and run-length-encode consecutive duplicates into a list of (value, count) tuples, returned as repr.


Submission VUEEB9

import re

def transform(text):
    return re.sub(r"\d+", lambda m: "X" * len(m.group()), text)

Card ending in 4242, call 555-1234 today

Card ending in XXXX, call XXX-XXXX today

Replace every maximal run of digits in the text with the same number of 'X' characters, leaving everything else unchanged.


Submission K2LG22

import ast

def transform(text):
    data = ast.literal_eval(text)
    ordered = sorted(data, key=lambda t: (-t[1], t[0]))
    lines = [f"{i+1}. {name} - {score}" for i, (name, score) in enumerate(ordered)]
    return "\n".join(lines)

Parse a list of (name, score) tuples and produce leaderboard text, one line per entry as "rank. name - score", sorted by score descending then name ascending, numbering rows sequentially (no shared ranks for ties).


Submission GSV66Y

def transform(text):
    parts = [p.strip() for p in text.split(",")]
    out = []
    for p in parts:
        count_str, noun = p.split(" ", 1)
        count = int(count_str)
        if count != 1:
            noun = noun + "s"
        out.append(f"{count} {noun}")
    return ", ".join(out)

Parse a comma-separated 'count noun' list and return a comma-separated string where nouns with count != 1 get an 's' appended (simple pluralization).


Submission M3LH5X

import re

def transform(text):
    m = re.match(r"(\d+)h(\d+)m", text)
    hours, minutes = int(m.group(1)), int(m.group(2))
    return hours * 60 + minutes

Parse a duration string in the form '<hours>h<minutes>m' (both parts always present) and return the total number of minutes as an int.


Submission GRF3PX

import json

def transform(text):
    data = json.loads(text)
    keys = list(data[0].keys())
    lines = [",".join(keys)]
    for item in data:
        lines.append(",".join(str(item[k]) for k in keys))
    return "\n".join(lines)

Parse a JSON array of objects with the same keys and return CSV text: header row from keys (in first-seen order), then one row per object, comma-separated.


Submission KG80RY

import ast

def transform(text):
    data = ast.literal_eval(text)
    ranges = sorted(data, key=lambda t: t[0])
    merged = []
    for start, end in ranges:
        if merged and start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append((start, end))
    return repr(merged)

Parse a list of (start, end) integer range tuples and merge any overlapping or touching ranges (touching means end of one equals start of next), returning the merged list of tuples sorted by start, as repr.


Submission RUA6H7

def transform(text):
    small = {"of", "the", "and", "a"}
    words = text.split()
    result = []
    for i, w in enumerate(words):
        if i > 0 and w in small:
            result.append(w)
        else:
            result.append(w.capitalize())
    return " ".join(result)

the lord of the rings and a tale of two cities

The Lord of the Rings and a Tale of Two Cities

Title-case the given sentence, but keep the small words 'of', 'the', 'and', 'a' lowercase unless they are the first word.


Submission ZO76HX

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

[server]
host=localhost
port=8080

[client]
timeout=30

{'server': {'host': 'localhost', 'port': '8080'}, 'client': {'timeout': '30'}}

Parse a simple INI-style config (sections in brackets, key=value lines) into a nested dict and return its repr.


Submission QJOQJ0

import ast

def transform(text):
    list_part, n_part = text.split('|')
    data = ast.literal_eval(list_part)
    n = int(n_part) % len(data)
    return repr(data[n:] + data[:n])

Parse 'LIST|N' where LIST is a Python list literal and N is an int; rotate the list left by N positions and return its repr.


Submission TBSF97

import re

def transform(text):
    items = re.findall(r'<item>(.*?)</item>', text)
    return ','.join(items)

Extract the text content of every <item> tag and return a comma-separated string.


Submission Z0RPVZ

def transform(text):
    words = text.split()
    return ' '.join(w[::-1] for w in words)

Reverse the characters within each word but keep the words in their original order, joined by spaces.


Submission 5S64NL

def transform(text):
    parts = text.split(',')
    return ','.join(p.replace('_', '-') for p in parts)

Convert a comma-separated list of snake_case identifiers into kebab-case (underscores to hyphens).


Submission 4LSO96

import re

def roman_to_int(s):
    vals = {'I': 1, 'V': 5, 'X': 10}
    total = 0
    for i in range(len(s)):
        v = vals[s[i]]
        if i + 1 < len(s) and v < vals[s[i + 1]]:
            total -= v
        else:
            total += v
    return total

def transform(text):
    tokens = re.findall(r'\b[IVX]+\b', text)
    return sum(roman_to_int(t) for t in tokens)

Chapter IV covers section II and III, but not I.

Extract all standalone Roman numerals (I, II, III, IV, uppercase, word-bounded) from the text and return their sum as an int, converting each properly.


Submission 2BTHZG

def transform(text):
    fs = [float(x) for x in text.split(',')]
    ks = [round((f - 32) * 5 / 9 + 273.15, 2) for f in fs]
    return ','.join(str(k) for k in ks)

Parse a comma-separated list of Fahrenheit temperatures and return a comma-separated list of Kelvin equivalents rounded to 2 decimals.


Submission 4V2S5U

def transform(text):
    rows = [[int(x) for x in line.split(',')] for line in text.strip().split('\n')]
    cols = list(zip(*rows))
    return '\n'.join(','.join(str(x) for x in col) for col in cols)

Parse comma-separated rows of numbers (one row per line) and return the transposed matrix in the same comma/newline format.


Submission BJNWFA

def transform(text):
    vowels = set('aeiouAEIOU')
    words = text.split()
    return repr({w: sum(1 for c in w if c in vowels) for w in words})

Split text into words and count vowels (a, e, i, o, u, case-insensitive) in each word, returning a dict of word to vowel count as repr.


Submission FK1NSL

import re

def transform(text):
    parts = text.split(',')
    def conv(s):
        return re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower()
    return ','.join(conv(p) for p in parts)

Convert a comma-separated list of camelCase identifiers into snake_case.


Submission BRH3GK

import json

def flatten(d, prefix=''):
    result = {}
    for k, v in d.items():
        key = f'{prefix}.{k}' if prefix else k
        if isinstance(v, dict):
            result.update(flatten(v, key))
        else:
            result[key] = v
    return result

def transform(text):
    data = json.loads(text)
    return repr(flatten(data))

Parse a nested JSON object and flatten it into a single-level dict with dot-notation keys, returned as its repr.


Submission XQSZTK

import ast

def transform(text):
    data = ast.literal_eval(text)
    lines = ['name,age']
    for name, age in data:
        lines.append(f'{name},{age}')
    return '\n'.join(lines)

Parse a Python list of (name, age) tuples and return CSV text with header 'name,age' then one row per tuple.


Submission YJEB2P

def transform(text):
    nums = [int(x) for x in text.split(',')]
    return sum(nums)

Parse a comma-separated list of zero-padded number strings and return their sum as an int.


Submission SO2MSR

import re

def transform(text):
    amounts = [float(m) for m in re.findall(r'\$(\d+\.\d{2})', text)]
    return round(sum(amounts), 2)

Item A costs $12.50, Item B costs $7.25, and shipping is $3.00.

Extract all dollar amounts (format $X.XX) from the text and return their total as a float rounded to 2 decimals.


Submission E9YJQ0

def transform(text):
    result = {}
    for pair in text.split(';'):
        k, v = pair.split(':', 1)
        result[k] = v
    return repr(result)

Parse a semicolon-separated list of key:value pairs into a dict and return its repr.


Submission E5H4ZL

def transform(text):
    stopwords = {'the', 'a', 'and', 'over'}
    words = text.split()
    return sum(1 for w in words if w not in stopwords)

the quick brown fox jumps over the lazy dog and a cat

Count words in the text excluding a small stopword list ('the', 'a', 'and', 'over'), returning the count as an int.


Submission ZY6Z1I

def transform(text):
    result = {'letters': 0, 'digits': 0, 'other': 0}
    for ch in text:
        if ch.isalpha():
            result['letters'] += 1
        elif ch.isdigit():
            result['digits'] += 1
        else:
            result['other'] += 1
    return repr(result)

{'letters': 10, 'digits': 6, 'other': 3}

Count how many characters in the text are letters, digits, or 'other' (neither), returning a dict repr with keys 'letters', 'digits', 'other'.


Submission H1HFV9

def transform(text):
    emails = text.split(',')
    domains = []
    seen = set()
    for e in emails:
        d = e.split('@')[1]
        if d not in seen:
            seen.add(d)
            domains.append(d)
    return ','.join(domains)

Parse a comma-separated list of email addresses and return a comma-separated list of unique domains in first-seen order.


Submission KJ78QZ

def transform(text):
    words = text.split()
    lines = []
    current = ''
    for w in words:
        candidate = (current + ' ' + w).strip()
        if len(candidate) <= 15:
            current = candidate
        else:
            if current:
                lines.append(current)
            current = w
    if current:
        lines.append(current)
    return '\n'.join(lines)

the quick brown fox jumps over the lazy dog

Wrap the text into lines of at most 15 characters, breaking only on word boundaries, joined by newlines.


Submission O3Q8BO

def transform(text):
    lines = text.strip().split('\n')
    result = []
    i = 0
    while i < len(lines):
        j = i
        while j < len(lines) and lines[j] == lines[i]:
            j += 1
        count = j - i
        if count == 1:
            result.append(lines[i])
        else:
            result.append(f'{lines[i]} x{count}')
        i = j
    return '\n'.join(result)

Given lines of text, collapse consecutive duplicate lines into 'line xN' format (omit xN if count is 1), one per output line.


Submission 687FGH

import json

def transform(text):
    return json.dumps(text.split(','))

Parse a single comma-separated line and return it as a JSON array string.


Submission U9AS4Q

def transform(text):
    counts = {}
    for ch in text:
        if not ch.isalnum() and not ch.isspace():
            counts[ch] = counts.get(ch, 0) + 1
    return repr(counts)

Hello, world! How are you? Fine; thanks.

Count each punctuation character (non-alphanumeric, non-space) occurrence, return dict repr.


Submission MGEKC1

def transform(text):
    nums = [int(x) for x in text.split(',')]
    return sum(n * n for n in nums)

Parse a comma-separated list of integers and return the sum of their squares.


Submission 0U2K7P

def transform(text):
    filename = text.rsplit('/', 1)[-1]
    return filename.rsplit('.', 1)[0]

Given a file path, extract just the filename without its final extension.


Submission 37NLS8

def transform(text):
    vals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total = 0
    for i in range(len(text)):
        v = vals[text[i]]
        if i + 1 < len(text) and v < vals[text[i + 1]]:
            total -= v
        else:
            total += v
    return total

Convert a single standalone Roman numeral string into its integer value.


Submission QROFE9

def transform(text):
    nums = [int(x) for x in text.split(',')]
    running = []
    total = 0
    for n in nums:
        total += n
        running.append(total)
    return ','.join(str(x) for x in running)

Parse a comma-separated list of integers and return the running cumulative sum, comma-separated.


Submission 364VVA

import re

def transform(text):
    nums = [int(x) for x in re.findall(r'\d+', text)]
    return round(sum(nums) / len(nums), 2)

Order 12 items at 3 dollars, plus 7 more at 5 dollars

Extract all integers from the text and return their average rounded to 2 decimals.


Submission 32P4NN

def transform(text):
    return ' '.join(w.capitalize() for w in text.split())

Convert each word in the sentence to title case (first letter uppercase).


Submission XA4GDX

def transform(text):
    return ' '.join(reversed(text.split()))

Reverse the order of words in the sentence (characters within words stay the same).


Submission STHTWL

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

Parse a pipe-delimited table (first line is header) into a list of dicts, return its repr.


Submission GZNB69

def transform(text):
    cs = [float(x) for x in text.split(',')]
    fs = [round(c * 9 / 5 + 32, 1) for c in cs]
    return ','.join(str(f) for f in fs)

Parse a comma-separated list of Celsius temperatures and return Fahrenheit equivalents, comma-separated, rounded to 1 decimal.


Submission Q3RBJF

def transform(text):
    result = {}
    for pair in text.split('&'):
        k, v = pair.split('=')
        result[k] = v
    return repr(result)

Parse a URL query string (key=value pairs joined by &) into a dict, return its repr.


Submission VF81OU

def transform(text):
    return ''.join(ch for ch in text if ch.lower() not in 'aeiou')

Remove all vowels (a, e, i, o, u, case-insensitive) from the text.


Submission EJRMF9

import re

def transform(text):
    return ','.join(re.findall(r'\b[A-Z][a-zA-Z]*\b', text))

Alice went to Paris with Bob and saw the Eiffel Tower

Extract all capitalized words (starting with an uppercase letter) from the text, comma-separated in order.


Submission QV86QA

def transform(text):
    parts = text.split(',')
    def conv(s):
        words = s.split('-')
        return words[0] + ''.join(w.capitalize() for w in words[1:])
    return ','.join(conv(p) for p in parts)

Convert a comma-separated list of kebab-case identifiers into camelCase.


Submission 08C7KW

import re

def transform(text):
    return ','.join(re.findall(r'#\w+', text))

Loving the #sunset and #beach vibes today! #travel

Extract all hashtags from the text and return them comma-separated in order of appearance.


Submission YGNEYL

def transform(text):
    result = {}
    for group in text.split(';'):
        k, v = group.split(',')
        result[k] = v
    return repr(result)

Parse a semicolon-separated list of comma-separated key,value pairs into a dict, return its repr.


Submission D0P43D

def transform(text):
    return ' '.join(w[:4] for w in text.split())

Truncate each word in the text to a maximum of 4 characters, keeping words joined by spaces.


Submission VZFJRB

def transform(text):
    nums = [str(int(b, 2)) for b in text.split(',')]
    return ','.join(nums)

Parse a comma-separated list of binary number strings and return their decimal equivalents, comma-separated.


Submission F328U8

import re

def transform(text):
    parts = re.split(r'[.!?]', text)
    return sum(1 for p in parts if p.strip())

Hello world. How are you? I am fine! Great.

Count the number of sentences in the text (split on '.', '!', '?', ignoring empty fragments).


Submission OISD0I

def transform(text):
    lines = text.split('\n')
    return '\n'.join(l[::-1] for l in lines)

Reverse the characters of each line in the text, keeping the line order unchanged, joined by newlines.


Submission HRU9LX

import json

def transform(text):
    matrix = json.loads(text)
    return sum(matrix[i][i] for i in range(len(matrix)))

Parse a JSON matrix (list of lists) and return the sum of its main diagonal.


Submission JX3LWK

def transform(text):
    parts = text.split(',')
    def conv(s):
        return ''.join(w.capitalize() for w in s.split('_'))
    return ','.join(conv(p) for p in parts)

Convert a comma-separated list of snake_case identifiers into PascalCase.


Submission S3D99S

def transform(text):
    return sum(1 for w in text.split() if len(w) > 5)

the quick brown fox jumps over lazy elephant

Count how many words in the text have more than 5 characters.


Submission 7E6TEN

def transform(text):
    ranges = []
    for part in text.split(','):
        a, b = part.split('-')
        ranges.append([int(a), int(b)])
    ranges.sort(key=lambda r: r[0])
    merged = [ranges[0]]
    for start, end in ranges[1:]:
        if start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return ','.join(f'{a}-{b}' for a, b in merged)

Parse a comma-separated list of N-M numeric ranges, merge overlapping ones, and return the merged ranges as N-M pairs comma-separated.


Submission UB7SWA

def transform(text):
    total = 0.0
    for part in text.split(','):
        count, price = part.split('x')
        total += int(count) * float(price)
    return total

Parse a comma-separated list of 'COUNTxPRICE' entries and return the total cost as a float.


Submission SMCML9

import re

def transform(text):
    urls = text.split(',')
    domains = [re.match(r'https?://([^/]+)', u).group(1) for u in urls]
    return ','.join(domains)

Parse a comma-separated list of URLs and return their domain names (host part, without scheme or path), comma-separated.


Submission NM6QCJ

import re

def transform(text):
    return re.sub(r'\d{3}-\d{3}-\d{4}', 'XXX-XXX-XXXX', text)

Call me at XXX-XXX-XXXX or XXX-XXX-XXXX anytime.

Find all phone numbers (format XXX-XXX-XXXX) in the text and replace their digits with X, keeping hyphens.


Submission C0KT7N

def transform(text):
    return ''.join(w[0].upper() for w in text.split())

National Aeronautics and Space Administration

Convert a phrase into an acronym using the first letter of each word, uppercase, no separators.


Submission SJ3QMW

def transform(text):
    ks = [float(x) for x in text.split(',')]
    cs = [round(k - 273.15, 2) for k in ks]
    return ','.join(str(c) for c in cs)

Parse a comma-separated list of Kelvin temperatures and return Celsius equivalents, comma-separated, rounded to 2 decimals.


Submission LW568U

from collections import Counter

def transform(text):
    words = text.split()
    return Counter(words).most_common(1)[0][0]

Find the most frequently occurring word in the text and return it.


Submission 02SPN7

import re

def transform(text):
    return ','.join(re.findall(r'\(([^)]*)\)', text))

The result (computed carefully) was correct (finally)

Extract all text found inside parentheses and return them comma-separated in order.


Submission TENU3L

def transform(text):
    scores = [int(x) for x in text.split(',')]
    def grade(s):
        if s >= 90:
            return 'A'
        if s >= 80:
            return 'B'
        if s >= 70:
            return 'C'
        if s >= 60:
            return 'D'
        return 'F'
    return ','.join(grade(s) for s in scores)

Parse a comma-separated list of numeric scores (0-100) and convert each to a letter grade (A:90+, B:80+, C:70+, D:60+, F:below 60), comma-separated.


Submission K4H609

import re

def transform(text):
    pairs = re.findall(r'"([^"]*)"|\'([^\']*)\'', text)
    return ','.join(a if a else b for a, b in pairs)

She said "hello" and then 'goodbye' quickly

Extract all substrings enclosed in single or double quotes, comma-separated in order.


Submission I01551

def transform(text):
    nums = [int(x) for x in text.split(',')]
    evens = [n for n in nums if n % 2 == 0]
    return ','.join(str(n) for n in evens)

Parse a comma-separated list of integers and return only the even ones, comma-separated.


Submission KF0CO2

def transform(text):
    n = int(text)
    ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
    tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
    def below_100(n):
        if n < 20:
            return ones[n]
        return tens[n // 10] + (' ' + ones[n % 10] if n % 10 else '')
    if n < 100:
        return below_100(n)
    hundreds = n // 100
    rest = n % 100
    result = ones[hundreds] + ' hundred'
    if rest:
        result += ' ' + below_100(rest)
    return result

Convert an integer (0-999) into its English words representation, space-separated, lowercase.


Submission 76F0GS

def transform(text):
    names = text.split(',')
    sorted_names = sorted(names, key=lambda n: n.split()[-1])
    return ','.join(sorted_names)

John Smith,Alice Adams,Bob Zephyr,Carol Brown

Alice Adams,Carol Brown,John Smith,Bob Zephyr

Parse a comma-separated list of 'First Last' names and sort them by last name, returning the sorted 'First Last' list comma-separated.


Submission 8M38WX

def transform(text):
    colors = text.split(',')
    sums = []
    for c in colors:
        c = c.lstrip('#')
        r, g, b = int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)
        sums.append(str(r + g + b))
    return ','.join(sums)

Parse a comma-separated list of 6-digit hex color codes and return the sum of R+G+B components for each, comma-separated.


Submission 1KCIEQ

def transform(text):
    seen = set()
    result = []
    for w in text.split():
        if w not in seen:
            seen.add(w)
            result.append(w)
    return ' '.join(result)

the cat sat on the mat and the cat slept

Remove duplicate words from the text, keeping only the first occurrence of each, preserving order, space-separated.


Submission Q1QEON

def transform(text):
    return sum(ord(ch) for ch in text) % 256

Compute a simple checksum by summing the ASCII codes of all characters in the text, modulo 256.


Submission RS66GO

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    result = []
    for line in lines:
        last, first = line.split(', ')
        result.append(f'{first} {last}')
    return '\n'.join(result)

Given lines in 'Last, First' format, convert each to 'First Last' format, one name per line.


Submission WBZ2XF

import json

def transform(text):
    data = json.loads(text)
    values = data['values']
    result = {
        'min': min(values),
        'max': max(values),
        'avg': round(sum(values) / len(values), 2)
    }
    return json.dumps(result)

Given a JSON object with a 'values' array of numbers, compute the min, max, and average, returning a JSON object with keys min, max, avg (avg rounded to 2 decimals).


Submission 1K0AZG

import re

def transform(text):
    return re.sub(r'\d+', lambda m: 'X' * len(m.group()), text)

Card ending in 1234, order #56789 confirmed.

Card ending in XXXX, order #XXXXX confirmed.

Replace every run of digits in the text with the same number of 'X' characters, keeping everything else unchanged.


Submission LEYZ56

import csv, json, io

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()), delimiter='\t')
    return json.dumps(list(reader))

Parse a TSV (tab-separated) file with a header row into a JSON array of objects.


Submission FVCCBN

import json

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    counts = [len(l.split()) for l in lines]
    return json.dumps(counts)

the quick brown fox
jumped over
the lazy dog here

For each line in the input, count the number of words, and return a JSON array of the counts in order.


Submission FLQCOB

import re

def transform(text):
    return re.sub(r'\s+', ' ', text).strip()

Collapse all runs of whitespace into a single space and strip leading/trailing whitespace.


Submission BJWALJ

import re, json

def transform(text):
    tags = re.findall(r'#(\w+)', text)
    return json.dumps(sorted(set(tags)))

Loving the #sunset and #beach vibes today! #sunset again.

Extract all unique hashtags from the text, sort them alphabetically, and return as a JSON array of strings (without the # symbol).


Submission K1FE15

import json

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

[server]
host=localhost
port=8080
[client]
timeout=30

Parse a simple INI-style config (with [section] headers and key=value lines) into a JSON object mapping section names to their key-value pairs.


Submission QH28YT

import re
def transform(input):
    parts = [p.strip() for p in input.split(',')]
    out = []
    for p in parts:
        h_match = re.search(r'(\d+)h', p)
        m_match = re.search(r'(\d+)m', p)
        h = int(h_match.group(1)) if h_match else 0
        m = int(m_match.group(1)) if m_match else 0
        out.append(h*60 + m)
    return out

Convert a comma-separated list of duration strings (format '<H>h <M>m', either part optional) into a JSON array of total minutes.


Submission HMSIYJ

def transform(text):
    words = text.split()
    return max(words, key=len)

the quick brown fox jumps over extraordinarily

Find and return the longest word in the text (first one if there is a tie).


Submission M5R4X7

def transform(text):
    words = text.split()
    def pig(w):
        return w[1:] + w[0] + 'ay'
    return ' '.join(pig(w) for w in words)

Translate each word of the text to Pig Latin: move the first consonant cluster (or just first letter here, simplified to first letter) to the end and append 'ay'.


Submission UUKBWO

import json
from collections import Counter

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

Return a JSON object mapping each distinct word to its frequency count in the text.


Submission FP0S5S

import json

def transform(text):
    lines = text.split(chr(10))
    headers = lines[0].split(',')
    values = lines[1].split(',')
    return json.dumps(dict(zip(headers, values)))

Parse a two-line CSV (header + one data row) and return a JSON object mapping header to value.


Submission ZXOG7H

def transform(text):
    fs = [float(x) for x in text.split(',')]
    cs = [round((f - 32) * 5 / 9, 2) for f in fs]
    return ','.join(str(c) for c in cs)

Parse a comma-separated list of Fahrenheit temperatures and return Celsius equivalents, comma-separated, rounded to 2 decimals.


Submission DF02L0

def transform(text):
    return ' '.join(w.capitalize() for w in text.split())

Convert text to title case, capitalizing the first letter of every word.


Submission HO2N4U

import json

def transform(text):
    vowels = sum(1 for ch in text if ch.lower() in 'aeiou')
    consonants = sum(1 for ch in text if ch.isalpha() and ch.lower() not in 'aeiou')
    return json.dumps({"vowels": vowels, "consonants": consonants})

Count the number of vowels and consonants (letters only) in the text and return as a JSON object.


Submission SIF19M

def transform(text):
    return ''.join(ch for ch in text if ch.lower() not in 'aeiou')

Remove all vowels (a, e, i, o, u, both cases) from the text.


Submission 3VHA9P

import re

def transform(text):
    nums = [int(n) for n in re.findall(r'\d+', text)]
    return sum(nums)

I have 3 apples, 15 oranges, and 7 bananas, total 25 fruits

Extract all integers from the text and return their sum.


Submission UEJOVA

import json

def transform(text):
    pairs = text.split(';')
    result = {}
    for p in pairs:
        k, v = p.split('=')
        result[k] = v
    return json.dumps(result)

Parse a semicolon-separated list of key=value pairs into a JSON object.


Submission I1DOVY

def transform(text):
    return ' '.join(reversed(text.split()))

Reverse the order of words in the sentence, keeping each word's spelling unchanged, space-separated.


Submission XGYMZ8

def transform(text):
    if not text:
        return ''
    result = []
    prev = text[0]
    count = 1
    for ch in text[1:]:
        if ch == prev:
            count += 1
        else:
            result.append(f'{count}{prev}')
            prev = ch
            count = 1
    result.append(f'{count}{prev}')
    return ''.join(result)

Compress a string using run-length encoding, representing each run as <count><char>.


Submission QIX6G5

def transform(text):
    bins = text.split()
    return ','.join(str(int(b, 2)) for b in bins)

Parse a space-separated list of binary strings and return their decimal equivalents, comma-separated.


Submission CMFPWX

def transform(text):
    nums = [int(x) for x in text.split(',')]
    return ','.join(format(n, 'X') for n in nums)

Parse a comma-separated list of decimal integers and return their uppercase hexadecimal equivalents (no 0x prefix), comma-separated.


Submission 6F3KYZ

import re

def transform(text):
    pairs = re.findall(r'(\d+)(\D)', text)
    return ''.join(ch * int(count) for count, ch in pairs)

Decompress a run-length-encoded string of the form <count><char> repeated.


Submission BY6PF2

def transform(text):
    emails = text.split(',')
    domains = [e.split('@')[1] for e in emails]
    return ','.join(domains)

Parse a comma-separated list of email addresses and return their domain portions (after the @), comma-separated.


Submission RK3I96

def transform(text):
    sentences = [s.strip() for s in text.split('.') if s.strip()]
    capitalized = [s[0].upper() + s[1:] for s in sentences]
    return '. '.join(capitalized) + '.'

Split the text into sentences on periods and capitalize the first letter of each, rejoining with '. '.


Submission 60BRYN

def transform(text):
    cs = [float(x) for x in text.split(',')]
    fs = [round(c * 9 / 5 + 32, 2) for c in cs]
    return ','.join(str(f) for f in fs)

Parse a comma-separated list of Celsius temperatures and return Fahrenheit equivalents, comma-separated, rounded to 2 decimals.


Submission 8OOZJG

def transform(text):
    return '*' * (len(text) - 4) + text[-4:]

Mask a credit card number, replacing all but the last 4 digits with asterisks.


Submission 0F0OYB

def transform(text):
    pairs = text.split(',')
    total = sum(int(p.split(':')[1]) for p in pairs)
    return total

Parse a comma-separated list of key:value numeric pairs and return the sum of all the values.


Submission ZW9D4L

import json

def transform(text):
    pairs = text.split(',')
    people = []
    for p in pairs:
        name, age = p.split(':')
        people.append({"name": name, "age": int(age)})
    people.sort(key=lambda p: p["age"])
    return json.dumps(people)

Parse a comma-separated list of name:age pairs and return a JSON list of objects sorted by age ascending.


Submission 2MT0J7

import re

def transform(text):
    return re.sub(r'<[^>]+>', '', text)

Remove all HTML tags from the text, keeping only the visible text content.


Submission GKZBNF

def transform(text):
    dates = text.split(',')
    converted = []
    for d in dates:
        day, month, year = d.split('/')
        converted.append(f'{year}-{month}-{day}')
    return ','.join(converted)

Parse a comma-separated list of dates in DD/MM/YYYY format and return them in YYYY-MM-DD format, comma-separated.


Submission 1AME0V

def transform(text):
    words = text.split()
    return sum(1 for w in words if w == w[::-1])

level noon hello world madam racecar test

Count how many words in the text are palindromes (read the same forwards and backwards).


Submission CGMSF6

def transform(text):
    words = text.split()
    return ' '.join(w[:5] for w in words)

Truncate each word in the text to a maximum of 5 characters, space-separated.


Submission R35HBU

import math

def transform(text):
    points = []
    for p in text.split(';'):
        x, y = p.split(',')
        points.append((float(x), float(y)))
    total = 0.0
    for i in range(1, len(points)):
        x1, y1 = points[i - 1]
        x2, y2 = points[i]
        total += math.hypot(x2 - x1, y2 - y1)
    return round(total, 2)

Parse a semicolon-separated list of x,y coordinate pairs and return the total Euclidean distance traveled across consecutive points, rounded to 2 decimals.


Submission 5MQ1BT

import json

def transform(text):
    result = {}
    current_section = None
    for raw_line in text.split("\n"):
        line = raw_line.strip()
        if not line or line.startswith("#") or line.startswith(";"):
            continue
        if line.startswith("[") and line.endswith("]"):
            current_section = line[1:-1].strip()
            result.setdefault(current_section, {})
            continue
        if "=" not in line:
            continue
        key, _, value = line.partition("=")
        key = key.strip()
        value = value.strip()
        if value.startswith('"') and value.endswith('"'):
            value = value[1:-1]
        if current_section is None:
            result.setdefault("_global", {})[key] = value
        else:
            result[current_section][key] = value
    return json.dumps(result)

; global settings
timeout = 30

[database]
host = localhost
port = 5432
name = "my app db"

# logging section
[logging]
level = DEBUG
path = /var/log/app.log

Parse an INI-style config text (with `[section]` headers, `key = value` lines, and `#`/`;` comment lines) into a nested JSON object mapping each section name to its own key/value object; keys found before any section header go under a `_global` section. Quoted values have their surrounding double quotes stripped.


Submission QAX2TR

def transform(input):
    parts = [p.strip() for p in input.split(',')]
    celsius = sorted(round((float(p) - 32) * 5/9, 1) for p in parts)
    return celsius

Convert a comma-separated list of Fahrenheit temperatures into a JSON array of Celsius temperatures, each rounded to 1 decimal place, sorted in ascending numeric order.


Submission AAL15V

import re
def transform(input):
    tuples = re.findall(r'\(([^)]+)\)', input)
    hexes = []
    for t in tuples:
        r, g, b = [int(x.strip()) for x in t.split(',')]
        hexes.append('#{:02X}{:02X}{:02X}'.format(r, g, b))
    return ', '.join(hexes)

Parse a comma-separated list of RGB tuples written as '(R, G, B)' and convert each to its uppercase 6-digit hex color code, joined by ', '.


Submission UIU3Y4

import json
import re

def transform(text):
    result = {}
    for line in text.strip().split("\n"):
        line = line.strip()
        if not line.startswith("export "):
            continue
        rest = line[len("export "):]
        key, _, value = rest.partition("=")
        value = value.strip()
        if value.startswith('"') and value.endswith('"'):
            value = value[1:-1]
        elif value.startswith("'") and value.endswith("'"):
            value = value[1:-1]
        result[key] = value
    return json.dumps(result)

export DB_HOST=localhost
export DB_PORT=5432
export APP_NAME="My Service"
export DEBUG=true

Parse a shell script of `export KEY=value` lines (values optionally single- or double-quoted) into a JSON object mapping each key to its unquoted string value.


Submission OXPMYL

import json

def transform(text):
    text = text.lower()
    counts = {v: text.count(v) for v in 'aeiou'}
    return json.dumps(counts)

The rain in Spain falls mainly on the plain

Count vowels (a,e,i,o,u case-insensitive) in the text and return a JSON object mapping each vowel to its count, including zero counts.


Submission 0KINTL

import json

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    balance = 0.0
    out = []
    for line in lines:
        date, amt = line.split(',')
        balance += float(amt)
        out.append({"date": date, "balance": round(balance, 2)})
    return json.dumps(out)

Given daily transaction amounts as date,amount CSV lines, compute the running balance after each day and return as a JSON array of {date, balance}.


Submission 2GJPE8

def transform(text):
    lines = text.strip().split('\n')
    result = []
    for line in lines:
        snake = '_'.join(line.lower().split())
        result.append(snake)
    return ';'.join(result)

The Quick Brown Fox
Jumps Over The Lazy Dog

Convert each line from Title Case to snake_case, joining lines with a semicolon.


Submission 0YKA6L

import csv, io

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

Convert CSV rows with first_name,last_name headers into a list of full names joined by ' ', one per line, sorted alphabetically by last name.


Submission DYY5N3

import json

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

key1=value1;key2=value2 with spaces;key3=another value

Parse a semicolon-separated list of key=value pairs (values may contain spaces) into a JSON object.


Submission GXNT5F

import json
from collections import defaultdict

def transform(text):
    totals = defaultdict(int)
    for pair in text.strip().split(','):
        name, count = pair.split(':')
        totals[name.strip()] += int(count)
    return json.dumps(dict(sorted(totals.items())))

Parse a comma-separated list of item:count pairs and sum counts per item, returning a JSON object sorted by item name.


Submission 603ZSI

import csv, io, json

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    rows = []
    for row in reader:
        out = {}
        for k, v in row.items():
            try:
                out[k] = int(v)
            except ValueError:
                out[k] = v
        rows.append(out)
    return json.dumps(rows)

Name,Age,City
Alice,30,NYC
Bob,25,LA
Carol,35,SF

Convert a CSV string with a header row into a JSON array of objects, keeping numeric-looking fields as integers.


Submission GNN331

import json, re

def transform(text):
    matches = re.findall(r'<item id="(\d+)">(.*?)</item>', text)
    result = {int(k): v for k, v in matches}
    return json.dumps(result)

Parse simple XML with <item id="N">text</item> children and return a JSON object mapping id to text.


Submission 9ZDL9Y

import json, re

def transform(text):
    text = text.strip()
    letters = ''.join(re.findall(r'[a-zA-Z]', text))
    digits = ''.join(re.findall(r'\d', text))
    return json.dumps({"letters": letters, "digits": digits})

Extract all letters and all digits from an alphanumeric string separately, returning them as JSON with keys 'letters' and 'digits'.


Submission 6KWKF6

import json
import operator

def transform(text):
    ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
    lines = [l for l in text.strip().split('\n') if l]
    results = []
    for line in lines:
        parts = line.split()
        a, op, b = int(parts[0]), parts[1], int(parts[2])
        results.append(ops[op](a, b))
    return json.dumps(results)

Evaluate each simple arithmetic expression line (operators + - * /, two integer operands) and return a JSON array of results (as numbers, division results as floats).


Submission WG6I0R

import json

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    best = None
    for line in lines:
        item, price, qty = line.split(',')
        total = float(price) * int(qty)
        if best is None or total > best['total']:
            best = {"item": item, "total": total}
    return json.dumps(best)

Given lines of item,price,quantity, compute total cost per item (price*quantity) and return the item with the highest total cost as a JSON object {item, total}.


Submission 2336SG

import json
from collections import defaultdict

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    fails = defaultdict(int)
    for line in lines:
        tokens = dict(tok.split(':') for tok in line.split())
        if tokens.get('action') == 'login' and tokens.get('status') == 'fail':
            fails[tokens['user_id']] += 1
    return json.dumps(dict(fails))

user_id:1001 action:login status:success
user_id:1002 action:login status:fail
user_id:1001 action:logout status:success
user_id:1003 action:login status:fail

Parse space-separated key:value tokens per line and count how many 'login' actions had status 'fail' per user_id, returning a JSON object mapping user_id to fail count (only users with at least one fail).


Submission 6DJ21R

import json
from datetime import datetime

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    durations = []
    start_time = None
    for line in lines:
        ts, event = line.split(',')
        t = datetime.fromisoformat(ts)
        if event == 'START':
            start_time = t
        elif event == 'STOP' and start_time:
            durations.append((t - start_time).total_seconds() / 60)
            start_time = None
    return json.dumps(durations)

Given alternating START/STOP timestamp events, compute the duration in minutes of each START-STOP pair and return a JSON array of durations.


Submission 34FBPX

import json

def transform(text):
    data = json.loads(text)
    lines = []
    for user in data['users']:
        for role in user['roles']:
            lines.append(f"{user['id']}:{role}")
    return '\n'.join(lines)

Flatten a JSON object with a users list of {id, roles} into a list of 'id:role' strings, one per role, newline separated.


Submission 1U460C

import re, json

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    result = []
    for line in lines:
        m = re.match(r'^(\S+).*"\s*(\d{3})$', line)
        if m:
            result.append([m.group(1), m.group(2)])
    return json.dumps(result)

Extract just the IP address and HTTP status code from each Apache-style log line, returning a JSON array of [ip, status] pairs.


Submission 7TDUR3

import json
from collections import Counter

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

Given a comma-separated list of integers, return a JSON object with min, max, mean (rounded to 2 decimals), and the mode (most frequent value; if tie, smallest).


Submission JAUAT9

import json

def transform(text):
    grid = [[int(x) for x in line.split()] for line in text.strip().split('\n')]
    row_sums = [sum(row) for row in grid]
    col_sums = [sum(col) for col in zip(*grid)]
    return json.dumps({"row_sums": row_sums, "col_sums": col_sums})

Given a whitespace-separated grid of integers (rows on separate lines), return the sum of each row and the sum of each column as JSON with keys 'row_sums' and 'col_sums'.


Submission 68Y9CF

import json

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    result = []
    for line in lines:
        uid, status = line.split(',')
        if status.strip() == 'active':
            result.append(uid.strip())
    return json.dumps(result)

Parse lines of uuid,status and return only the active UUIDs as a JSON array, preserving order.


Submission KY4O9Z

import re

def transform(text):
    lines = text.strip().split('\n')
    out = []
    for line in lines:
        line = re.sub(r'^#+\s*', '', line)
        line = re.sub(r'\*\*(.*?)\*\*', r'\1', line)
        line = re.sub(r'\*(.*?)\*', r'\1', line)
        line = re.sub(r'`(.*?)`', r'\1', line)
        out.append(line)
    return '\n'.join(out)

# Header
Some **bold** text and *italic* text here.
Another line with `code`.

Header
Some bold text and italic text here.
Another line with code.

Strip common Markdown formatting (headers, bold **, italic *, inline code backticks) leaving plain text, preserving line breaks.


Submission 78071N

import json
from urllib.parse import parse_qsl

def transform(text):
    pairs = parse_qsl(text.strip(), keep_blank_values=True)
    items = []
    current = {}
    for k, v in pairs:
        if k in current:
            items.append(current)
            current = {}
        current[k] = v
    if current:
        items.append(current)
    for item in items:
        item['qty'] = int(item['qty'])
        item['price'] = float(item['price'])
    return json.dumps(items)

Parse a query string where product/qty/price fields repeat in groups of 3 in order, grouping them into a JSON array of objects.


Submission P03SZA

from decimal import Decimal, ROUND_HALF_UP

def transform(text):
    groups = []
    current = {"name": "(root)", "verts": 0, "faces": 0, "tri": 0, "quad": 0, "ngon": 0}
    groups.append(current)
    xs, ys, zs = [], [], []
    refs = 0
    maxindex = 0

    for raw in text.split("\n"):
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        parts = line.split()
        key = parts[0]
        if key == "o":
            current = {"name": " ".join(parts[1:]), "verts": 0, "faces": 0,
                       "tri": 0, "quad": 0, "ngon": 0}
            groups.append(current)
        elif key == "v":
            current["verts"] += 1
            xs.append(Decimal(parts[1]))
            ys.append(Decimal(parts[2]))
            zs.append(Decimal(parts[3]))
        elif key == "f":
            tokens = parts[1:]
            current["faces"] += 1
            n = len(tokens)
            if n == 3:
                current["tri"] += 1
            elif n == 4:
                current["quad"] += 1
            elif n >= 5:
                current["ngon"] += 1
            for tok in tokens:
                idx = int(tok.split("/")[0])
                refs += 1
                if idx > maxindex:
                    maxindex = idx

    def fmt(value):
        return str(Decimal(value).quantize(Decimal("0.001"), rounding=ROUND_HALF_UP))

    out = []
    for g in groups:
        if g["name"] == "(root)" and g["verts"] == 0 and g["faces"] == 0:
            continue
        out.append("name=%s verts=%d faces=%d tri=%d quad=%d ngon=%d" % (
            g["name"], g["verts"], g["faces"], g["tri"], g["quad"], g["ngon"]))
    if xs:
        out.append("min=%s/%s/%s" % (fmt(min(xs)), fmt(min(ys)), fmt(min(zs))))
        out.append("max=%s/%s/%s" % (fmt(max(xs)), fmt(max(ys)), fmt(max(zs))))
    else:
        out.append("min=none")
        out.append("max=none")
    out.append("refs=%d maxindex=%d" % (refs, maxindex))
    return "\n".join(out)

name=(root) verts=1 faces=0 tri=0 quad=0 ngon=0
name=LeftPanel verts=3 faces=1 tri=1 quad=0 ngon=0
name=RightPanel verts=2 faces=2 tri=0 quad=1 ngon=1
name=LeftPanel verts=1 faces=1 tri=1 quad=0 ngon=0
min=-1.500/-2.000/0.000
max=4.500/2.500/3.250
refs=15 maxindex=7

Summarize a Wavefront OBJ mesh. Rules:
1. Ignore blank lines and lines whose first non-space character is '#'.
2. Split each remaining line on whitespace; the first token is the keyword.
3. 'o NAME' opens a new object group. Any geometry appearing before the first 'o' belongs to a group named '(root)'; if no vertex and no face appears before the first 'o', the '(root)' group is not reported at all. If the same name is opened twice, treat each 'o' line as a separate group in file order.
4. 'v x y z' declares a vertex; the three coordinates are decimal numbers.
5. 'f' declares a face; each following whitespace-separated token is a vertex reference of the form 'v', 'v/vt', 'v//vn' or 'v/vt/vn'. The vertex index is the integer before the first '/'. Indices are positive and 1-based over all 'v' lines in the whole file.
6. Every other keyword (mtllib, usemtl, vn, vt, s, g, ...) is ignored.
7. For each group, in the order it was opened, emit one line:
   name=<NAME> verts=<V> faces=<F> tri=<T> quad=<Q> ngon=<N>
   where V counts the 'v' lines inside that group, F counts its 'f' lines, and T, Q and N count faces with exactly 3, exactly 4 and 5 or more vertex references.
8. Then emit one line 'min=<x>/<y>/<z>' and one line 'max=<x>/<y>/<z>' giving the axis-aligned bounding box over every vertex in the file. Format each coordinate with exactly 3 decimal places, rounding half-up. If the file has no vertices, emit 'min=none' and 'max=none' instead.
9. Then emit a final line 'refs=<R> maxindex=<M>' where R is the total number of vertex references across all faces and M is the largest vertex index referenced (0 if there are none).
10. Join the lines with '\n' and return them with no trailing newline.


Submission Q5CBBA

def transform(text):
    disc_title = None
    disc_performer = None
    tracks = []
    current = None

    def quoted(line):
        first = line.find('"')
        last = line.rfind('"')
        if first == -1 or last <= first:
            return line.split(None, 1)[1].strip() if " " in line else ""
        return line[first + 1:last]

    for raw in text.split("\n"):
        line = raw.strip()
        if not line:
            continue
        upper = line.upper()
        if upper.startswith("TRACK "):
            parts = line.split()
            current = {"num": parts[1], "type": parts[2] if len(parts) > 2 else "",
                       "title": None, "performer": None, "start": None}
            tracks.append(current)
        elif upper.startswith("TITLE "):
            if current is None:
                disc_title = quoted(line)
            else:
                current["title"] = quoted(line)
        elif upper.startswith("PERFORMER "):
            if current is None:
                disc_performer = quoted(line)
            else:
                current["performer"] = quoted(line)
        elif upper.startswith("INDEX "):
            parts = line.split()
            if current is not None and parts[1] == "01":
                mm, ss, ff = parts[2].split(":")
                current["start"] = (int(mm) * 60 + int(ss)) * 75 + int(ff)

    playable = [t for t in tracks if t["type"] == "AUDIO" and t["start"] is not None]
    ordered = [t for t in tracks if t["start"] is not None]

    def stamp(frames):
        minutes, rest = divmod(frames, 60 * 75)
        seconds, ff = divmod(rest, 75)
        return "%02d:%02d:%02d" % (minutes, seconds, ff)

    out = []
    total = 0
    for track in playable:
        later = [t["start"] for t in ordered if t["start"] > track["start"]]
        if later:
            duration = stamp(min(later) - track["start"])
            total += min(later) - track["start"]
        else:
            duration = "--:--:--"
        title = track["title"] or disc_title or "Unknown"
        performer = track["performer"] or disc_performer or "Unknown"
        out.append("%s|%s|%s|%s - %s" % (
            track["num"], stamp(track["start"]), duration, performer, title))
    out.append("tracks=%d playable=%s" % (len(playable), stamp(total)))
    return "\n".join(out)

REM GENRE Ambient
REM DATE 2019
PERFORMER "Marsh Collective"
TITLE "Tidal Fields"
FILE "album.wav" WAVE
  TRACK 01 AUDIO
    TITLE "Opening Silt"
    INDEX 01 00:00:00
  TRACK 02 AUDIO
    TITLE "Second Light"
    PERFORMER "Marsh Collective feat. Ilse"
    INDEX 00 03:12:30
    INDEX 01 03:14:00
  TRACK 03 MODE1/2352
    TITLE "Data Blob"
    INDEX 01 06:00:00
  TRACK 04 AUDIO
    INDEX 01 07:00:74
  TRACK 05 AUDIO
    TITLE "Closing Silt"
    INDEX 01 11:45:37

01|00:00:00|03:14:00|Marsh Collective - Opening Silt
02|03:14:00|02:46:00|Marsh Collective feat. Ilse - Second Light
04|07:00:74|04:44:38|Marsh Collective - Tidal Fields
05|11:45:37|--:--:--|Marsh Collective - Closing Silt
tracks=4 playable=10:44:38

Turn a CD cue sheet into a track listing. Rules:
1. Consider only lines whose stripped form starts with 'TRACK ', 'TITLE ', 'PERFORMER ', 'INDEX ' or 'FILE '. Ignore every other line, including REM lines.
2. A 'TRACK NN AUDIO' line opens a new track; NN is a two-digit number. Only tracks with type 'AUDIO' are listed; a track of any other type is skipped together with all of its own TITLE, PERFORMER and INDEX lines.
3. Inside a track, 'TITLE "..."' and 'PERFORMER "..."' set that track's title and performer; the value is the text between the first and last double quote. A TITLE or PERFORMER appearing before the first TRACK is the disc-level value. A track with no TITLE uses the disc title; a track with no PERFORMER uses the disc performer; if neither exists use 'Unknown'.
4. 'INDEX 01 MM:SS:FF' gives the track start. 'INDEX 00' is a pregap and is ignored. Timestamps are minutes, seconds and frames with 75 frames per second.
5. A track's duration is the earliest start greater than its own, taken over every TRACK in the sheet including the ones that are skipped for not being AUDIO, minus its own start. A track with no later start has no known end, so its duration is '--:--:--'.
6. Emit one line per track: '<NN>|<start>|<duration>|<performer> - <title>' where NN is the two-digit track number as written and start and duration use MM:SS:FF with two-digit minutes, two-digit seconds and two-digit frames.
7. Finally emit 'tracks=<count> playable=<MM:SS:FF>' where playable is the sum of all known durations.
8. Join the lines with '\n' and return them with no trailing newline.


Submission 2CXHBK

from decimal import Decimal, ROUND_HALF_UP, InvalidOperation

UNITS = {"K": 1024, "M": 1024 ** 2, "G": 1024 ** 3, "T": 1024 ** 4}

def transform(text):
    skipped = []
    rows = []
    for raw in text.split("\n"):
        if not raw.strip():
            continue
        if "\t" not in raw:
            skipped.append("SKIP " + raw.strip())
            continue
        size_part, path = raw.split("\t", 1)
        size_part = size_part.strip()
        path = path.rstrip()
        suffix = size_part[-1:].upper()
        if suffix in UNITS:
            number, factor = size_part[:-1], UNITS[suffix]
        else:
            number, factor = size_part, 1
        try:
            value = Decimal(number)
        except InvalidOperation:
            skipped.append("SKIP " + raw.strip())
            continue
        total = (value * factor).quantize(Decimal("1"), rounding=ROUND_HALF_UP)
        rows.append((int(total), path))

    def human(nbytes):
        steps = [("TiB", 1024 ** 4), ("GiB", 1024 ** 3), ("MiB", 1024 ** 2), ("KiB", 1024)]
        for label, factor in steps:
            if nbytes >= factor:
                scaled = (Decimal(nbytes) / Decimal(factor)).quantize(
                    Decimal("0.01"), rounding=ROUND_HALF_UP)
                return "%s %s" % (scaled, label)
        return "%d B" % nbytes

    rows.sort(key=lambda r: (-r[0], r[1]))
    out = list(skipped)
    for nbytes, path in rows:
        out.append("%d|%s|%s" % (nbytes, path, human(nbytes)))
    out.append("entries=%d total=%d" % (len(rows), sum(r[0] for r in rows)))
    return "\n".join(out)

4.0K	./src/utils
12M	./src
1.5G	./data/raw
900	./data/tmp
2.3G	./data
128K	./docs
0	./empty
17X	./weird
nosizehere ./broken
1.0T	./

Convert 'du -h' style output into exact byte counts.
1. Each non-blank line holds a size, then a TAB, then a path. Strip trailing whitespace from the path.
2. A size is a decimal number optionally followed by one unit letter: K, M, G or T, case-insensitive, meaning multiplication by 1024, 1024**2, 1024**3 and 1024**4. No letter means bytes. Compute the exact byte count with decimal arithmetic and round half-up to a whole number.
3. If a line has no TAB, or the size does not parse, emit 'SKIP <the stripped line>' and continue.
4. Emit one line per parsed entry: '<bytes>|<path>|<human>'. The human column re-renders the byte count using the largest of B, KiB, MiB, GiB, TiB for which the value is at least 1 (bytes below 1024 use B). Show B with no decimals and every other unit with exactly two decimals, rounding half-up.
5. Parsed entries are sorted by byte count descending, ties broken by path ascending. SKIP lines come first, in input order.
6. Finally emit 'entries=<parsed count> total=<sum of bytes>'.
7. Join the lines with '\n' and return them with no trailing newline.