Submission E7VMRV

import json

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    result = {}
    for line in lines:
        group, pairs_str = line.split(':', 1)
        pairs = pairs_str.split(',')
        total_weighted = 0.0
        total_weight = 0.0
        for pair in pairs:
            score_str, weight_str = pair.split(';')
            score, weight = float(score_str), float(weight_str)
            total_weighted += score * weight
            total_weight += weight
        avg = round(total_weighted / total_weight, 2) if total_weight else 0
        result[group] = avg
    return json.dumps(result, indent=2, ensure_ascii=False)

Each line has a group name, a colon, then comma-separated 'score;weight' pairs. Compute the weighted average score per group as sum(score*weight)/sum(weight), rounded to 2 decimals. Return a JSON object mapping group name to its weighted average, serialized with indent=2, preserving input order.


Submission R2YVLJ

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    header = lines[0]
    out = [header]
    last_region = None
    for line in lines[1:]:
        cols = line.split(',')
        region = cols[0]
        if region.strip() == '"':
            region = last_region
        else:
            last_region = region
        cols[0] = region
        out.append(','.join(cols))
    return '\n'.join(out)

Region,Product,Sales
West,Widget,100
",Gadget,150
",Gizmo,90
East,Widget,80
",Gadget,60
North,Widget,40

Region,Product,Sales
West,Widget,100
West,Gadget,150
West,Gizmo,90
East,Widget,80
East,Gadget,60
North,Widget,40

This CSV uses a ditto mark (a lone double-quote character) in the Region column to mean 'same as the row above'. Fill down the Region column: whenever a row's first field is exactly a single double-quote character, replace it with the most recent actual region value seen above it. Leave other columns untouched. Return the corrected CSV text (comma-separated, newline-joined, no trailing newline), including the header.


Submission 95K6YP

import json

def hex_to_rgb(hex_code):
    hex_code = hex_code.lstrip('#')
    return [int(hex_code[i:i + 2], 16) for i in (0, 2, 4)]

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    groups = {}
    for line in lines:
        name, hex_code = line.split(':')
        name = name.strip()
        hex_code = hex_code.strip()
        prefix = name.split('-')[0]
        rgb = hex_to_rgb(hex_code)
        groups.setdefault(prefix, []).append({'name': name, 'rgb': rgb})
    return json.dumps(groups, indent=2, ensure_ascii=False)

brand-primary: #1A73E8
brand-secondary: #34A853
brand-accent: #FBBC05
alert-error: #EA4335
alert-warning: #FF6D01
neutral-100: #F5F5F5
neutral-900: #212121

Each line is 'name: #HEXCODE'. Group entries by the prefix before the first hyphen in the name. Convert each hex code to an [R, G, B] integer list. Return a JSON object mapping each prefix to a list of {name, rgb} objects in original order, serialized with indent=2.


Submission ZQ6N21

import re
import json

def dms_to_decimal(dms_str):
    m = re.match(r"(\d+)°(\d+)'([\d.]+)\"([NSEW])", dms_str)
    deg, minutes, seconds, direction = m.groups()
    value = float(deg) + float(minutes) / 60 + float(seconds) / 3600
    if direction in ('S', 'W'):
        value = -value
    return round(value, 6)

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    result = []
    for line in lines:
        lat_str, lon_str = line.split(' ')
        result.append({
            'lat': dms_to_decimal(lat_str),
            'lon': dms_to_decimal(lon_str)
        })
    return json.dumps(result, indent=2, ensure_ascii=False)

Each line has a latitude and longitude in degrees-minutes-seconds format like 41°24'12.2"N, separated by a space. Convert each to decimal degrees using degrees + minutes/60 + seconds/3600, negating the value if the direction is S or W, rounded to 6 decimal places. Return a JSON array of {lat, lon} objects in order, serialized with indent=2.


Submission UR2K78

import re
import json

def transform(text):
    messages = re.split(r'\n(?=From )', text.strip('\n'))
    result = []
    for msg in messages:
        lines = msg.split('\n')
        headers = {}
        for line in lines[1:]:
            if not line.strip():
                break
            if ':' in line:
                key, val = line.split(':', 1)
                headers[key.strip()] = val.strip()
        to_list = [t.strip() for t in headers.get('To', '').split(',') if t.strip()]
        result.append({
            'from': headers.get('From', ''),
            'to': to_list,
            'subject': headers.get('Subject', ''),
            'date': headers.get('Date', '')
        })
    return json.dumps(result, indent=2, ensure_ascii=False)

From alice@example.com Mon Aug 10 10:00:00 2026
From: Alice <alice@example.com>
To: bob@example.com
Subject: Meeting Tomorrow
Date: Mon, 10 Aug 2026 10:00:00 +0000

Let's meet at 10am.

From bob@example.com Mon Aug 10 11:00:00 2026
From: Bob <bob@example.com>
To: alice@example.com, carol@example.com
Subject: Re: Meeting Tomorrow
Date: Mon, 10 Aug 2026 11:00:00 +0000

Sounds good, see you then.

Meeting Tomorrow

Re: Meeting Tomorrow

This is mbox-style text: each message begins with an envelope line starting with 'From ' followed by header lines (From, To, Subject, Date) then a blank line then the body. Split on message boundaries (lines starting with 'From ' that are not preceded by other content on the same message), parse the From, To, Subject, Date headers for each message, splitting the To header on commas into a list of trimmed addresses. Return a JSON array of {from, to, subject, date} objects in order, serialized with indent=2.


Submission 2Z5C9Z

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    header = lines[0]
    out = [header]
    for line in lines[1:]:
        id_, value, checksum = line.split(',')
        expected = sum(ord(c) for c in id_ + value) % 97
        if expected == int(checksum):
            out.append(line)
    return '\n'.join(out)

id,value,checksum
A1,apple,62
A2,banana,45
A3,cherry,91
A4,date,46

id,value,checksum
A1,apple,62
A2,banana,45
A4,date,46

This CSV has columns id,value,checksum. The correct checksum for a row is defined as sum(ord(c) for c in id + value) % 97. Recompute the checksum for every row and keep only the rows where the stored checksum matches the recomputed value; discard rows whose stored checksum is wrong. Return the filtered CSV text (comma-separated, newline-joined, no trailing newline), keeping the header and original row order.


Submission GOBMI5

import re
import json

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    result = []
    for line in lines:
        main = re.split(r'ext', line, flags=re.IGNORECASE)[0]
        digits = re.sub(r'\D', '', main)
        if len(digits) == 10:
            normalized = '+1' + digits
        elif len(digits) == 11 and digits.startswith('1'):
            normalized = '+' + digits
        else:
            normalized = None
        result.append({'original': line, 'e164': normalized})
    return json.dumps(result, indent=2, ensure_ascii=False)

Each line is a US phone number in a different format, possibly with a trailing extension like 'ext 12'. Strip any extension first (everything from 'ext', case insensitive, onward), then extract the digits. If there are exactly 10 digits, normalize to '+1' followed by the digits. If there are 11 digits starting with '1', normalize to '+' followed by the digits. Otherwise, the normalized value is null. Return a JSON array of {original, e164} objects in order, serialized with indent=2.


Submission V8RF03

import re
import json

def parse_duration(s):
    pattern = re.findall(r'(\d+)([hms])', s)
    total = 0
    for value, unit in pattern:
        value = int(value)
        if unit == 'h':
            total += value * 3600
        elif unit == 'm':
            total += value * 60
        elif unit == 's':
            total += value
    return total

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    totals = {}
    for line in lines:
        task, dur = line.split(':', 1)
        totals[task] = totals.get(task, 0) + parse_duration(dur)
    return json.dumps(totals, indent=2, ensure_ascii=False)

build:1h30m
build:45m
test:90s
test:2m30s
deploy:5m
build:20m

Each line is 'task:duration' where duration is composed of optional h/m/s components like '1h30m', '45m', '90s', '2m30s'. Parse each duration to total seconds and sum by task. Return a JSON object mapping task name to total seconds (integer), serialized with indent=2, preserving first-appearance order of tasks.


Submission VNYC4U

import json

SCALE = {
    'Strongly Disagree': 1,
    'Disagree': 2,
    'Neutral': 3,
    'Agree': 4,
    'Strongly Agree': 5
}

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    header = lines[0].split(',')
    questions = header[1:]
    sums = {q: 0 for q in questions}
    count = 0
    responses = []
    for line in lines[1:]:
        cols = line.split(',')
        respondent = cols[0]
        answers = cols[1:]
        numeric = {questions[i]: SCALE[answers[i]] for i in range(len(questions))}
        responses.append({'respondent': respondent, 'scores': numeric})
        for q in questions:
            sums[q] += numeric[q]
        count += 1
    averages = {q: round(sums[q] / count, 2) for q in questions}
    result = {'responses': responses, 'averages': averages}
    return json.dumps(result, indent=2, ensure_ascii=False)

respondent,q1,q2,q3
R1,Strongly Agree,Agree,Neutral
R2,Disagree,Strongly Agree,Agree
R3,Neutral,Disagree,Strongly Disagree
R4,Strongly Disagree,Neutral,Strongly Agree

This CSV has a respondent column followed by question columns with Likert-scale text answers. Map answers to numbers: 'Strongly Disagree'=1, 'Disagree'=2, 'Neutral'=3, 'Agree'=4, 'Strongly Agree'=5. Build a JSON object with 'responses': a list of {respondent, scores: {question: number, ...}} in row order, and 'averages': a mapping of each question column to the mean of its numeric scores across all respondents, rounded to 2 decimals. Serialize with indent=2.


Submission H4L1TG

import re
import json

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    header = lines[0]
    m = re.match(r'rows=(\d+)\s+cols=(\d+)', header)
    rows, cols = int(m.group(1)), int(m.group(2))
    grid = [[0] * cols for _ in range(rows)]
    for line in lines[1:]:
        r, c, v = line.split(',')
        grid[int(r)][int(c)] = int(v)
    return json.dumps(grid, indent=2, ensure_ascii=False)

The first line declares grid dimensions as 'rows=R cols=C'. Each following line is 'row,col,value' for a non-zero cell in sparse coordinate format. Build the dense R x C grid (all other cells 0) and return it as a JSON 2D array (list of row lists) serialized with indent=2.


Submission I6HUDF

import re
import json
from collections import Counter

STOPWORDS = {'the', 'a', 'an', 'at', 'but', 'over', 'is', 'in', 'on', 'and', 'to', 'of'}

def transform(text):
    words = re.findall(r"[a-zA-Z']+", text.lower())
    words = [w for w in words if w not in STOPWORDS]
    counts = Counter(words)
    result = sorted(counts.items(), key=lambda x: (-x[1], x[0]))
    return json.dumps(result, indent=2, ensure_ascii=False)

The quick brown fox jumps over the lazy dog. The dog barks at the fox, but the fox runs away quickly. A quick fox is a smart fox.

Lower-case the text and extract alphabetic word tokens (letters and apostrophes only). Remove any token in this stopword set: {the, a, an, at, but, over, is, in, on, and, to, of}. Count the frequency of remaining words and return a JSON array of [word, count] pairs sorted by count descending, then alphabetically ascending for ties, serialized with indent=2.


Submission B56OSJ

import json

def transform(text):
    lines = [l for l in text.strip('\n').split('\n') if l.strip()]
    result = {}
    current_id = None
    seq = ''

    def flush():
        if current_id:
            gc = seq.count('G') + seq.count('C')
            pct = round(gc / len(seq) * 100, 2) if seq else 0
            result[current_id] = pct

    for line in lines:
        if line.startswith('>'):
            flush()
            current_id = line[1:].strip()
            seq = ''
        else:
            seq += line.strip()
    flush()
    return json.dumps(result, indent=2, ensure_ascii=False)

>seq1
ATGCGCTAGCTAGCTAGCGCGATCG
>seq2
ATATATATATCGCGCG
>seq3
GGGGCCCCAATT

This is FASTA-format text: lines starting with '>' introduce a sequence id, followed by one or more lines of nucleotide letters belonging to that sequence (concatenate them). For each sequence compute the GC content percentage: (count of 'G' + count of 'C') / total length * 100, rounded to 2 decimals. Return a JSON object mapping each sequence id to its GC percentage, serialized with indent=2, in order of first appearance.


Submission PVM84J

from datetime import datetime
def transform(input):
 d={}
 for l in input.splitlines():
  t,v=l.split(',');h=datetime.fromisoformat(t.replace('Z','+00:00')).strftime('%Y-%m-%dT%H');d[h]=d.get(h,0)+int(v)
 return '\n'.join(f'{k},{d[k]}' for k in sorted(d))

Parse timestamp,value rows and aggregate values by UTC hour, returning sorted hour,total lines.


Submission IVHEPM

def transform(input):
 lines=[l.split() for l in input.splitlines() if l.strip()];v=sorted({x for l in lines for x in l});m={x:i for i,x in enumerate(v)};return 'vocab='+','.join(v)+'\n'+'\n'.join(' '.join(str(m[x]) for x in l) for l in lines)

Create an alphabetical vocabulary and encode each input line as space-separated vocabulary indices, returning vocabulary then encoded lines.


Submission MZWWK4

import json
def transform(input):
 a=json.loads(input);p=None
 for x in a:
  x['previous_v']=p;x['delta']=None if p is None else x['v']-p;p=x['v']
 return json.dumps(a,separators=(',',':'))

Parse JSON records, add previous_v and delta fields relative to the preceding record; first record uses nulls; return compact JSON.


Submission NSH9B1

import json
def transform(input):
 d={}
 for l in input.splitlines():
  x=json.loads(l)
  for k,v in x.items():d[k]=d.get(k,0)+v
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Parse JSON Lines and return compact JSON mapping each key to the sum of numeric values across all records.


Submission WKFOQ8

import json
def transform(input):
 s=[sum(map(int,l.split())) for l in input.splitlines() if l.strip()];return json.dumps({'row_sums':s,'total':sum(s)},separators=(',',':'))

Parse whitespace-delimited integer rows of varying length and return compact JSON with each row sum plus a grand total.


Submission H5WNSF

import csv,io
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input)):d.setdefault(r['dept'],[]).append(int(r['salary']))
 a=[(k,sum(v)/len(v)) for k,v in d.items()];a.sort(key=lambda x:(-x[1],x[0]));return '\n'.join(f'{k}={v:.1f}' for k,v in a)

Parse CSV, compute average salary by department, and return departments ordered by descending average then name as dept=avg.


Submission 955446

import csv,io,json
def transform(input):
 r=csv.DictReader(io.StringIO(input));d={k:0 for k in r.fieldnames}
 for x in r:
  for k,v in x.items():d[k]+=bool(v)
 return json.dumps(d,separators=(',',':'))

Parse CSV and return compact JSON with per-column count of non-empty data cells, excluding the header.


Submission LS2XWC

import json
def transform(input):
 x=json.loads(input);bad=set(x['disabled']);u=[v for v in x['users'] if v['id'] not in bad];u.sort(key=lambda z:z['id']);return json.dumps(u,separators=(',',':'))

Parse JSON, remove users whose id appears in disabled, sort remaining users by id, and return compact JSON array.


Submission I3X99B

import csv,io,json
def transform(input):
 r=csv.DictReader(io.StringIO(input));d={}
 for x in r:
  if x['active']!='yes': continue
  a=d.setdefault(x['team'],{'count':0,'total':0});a['count']+=1;a['total']+=int(x['score'])
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

id,team,score,active
1,red,8,yes
2,blue,5,no
3,red,12,yes
4,blue,9,yes

Parse CSV, keep active rows, group by team, and return compact JSON with count and total score per team sorted by team.


Submission 5FPEV7

import urllib.parse,json
def transform(input):
 q=urllib.parse.parse_qs(input,keep_blank_values=True);r={k:(v[0] if len(v)==1 else v) for k,v in q.items()};return json.dumps(dict(sorted(r.items())),separators=(',',':'))

Parse a query string preserving repeated values and blank values; flatten single values only; return compact JSON with keys sorted.


Submission GKXM70

import csv,io,json
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input),delimiter='|'):
  a=d.setdefault(r['sku'],[0,0.0]);q=int(r['qty']);a[0]+=q;a[1]+=q*float(r['price'])
 o={k:{'qty':v[0],'revenue':round(v[1],2)} for k,v in sorted(d.items())};return json.dumps(o,separators=(',',':'))

Parse pipe-delimited rows, aggregate quantity and extended revenue by SKU, and return sorted compact JSON rounding revenue to 2 decimals.


Submission 2U522A

def transform(input):
 vals=[]
 for l in input.splitlines():
  d,v=l.split(',',1)
  try:vals.append((d,float(v)))
  except:pass
 out=['date,delta']
 for i in range(1,len(vals)):out.append(f'{vals[i][0]},{vals[i][1]-vals[i-1][1]:g}')
 return '\n'.join(out)

Parse date,value lines, skip non-numeric values, compute deltas between consecutive valid readings, and return CSV.


Submission LLGFR6

import json,csv,io
def transform(input):
 rows=[]
 for x in json.loads(input):
  for t in x['tags']:rows.append((x['id'],t))
 rows.sort();o=io.StringIO();w=csv.writer(o,lineterminator='\n');w.writerow(['id','tag']);w.writerows(rows);return o.getvalue().strip()

Expand each JSON object into one row per tag, skip objects with no tags, and return CSV sorted by id then tag.


Submission 0H61G5

import json
def transform(input):
 d={}
 for l in input.splitlines():
  level,svc,_=l.split('|');d.setdefault(svc,{})[level]=d.setdefault(svc,{}).get(level,0)+1
 return json.dumps({k:dict(sorted(v.items())) for k,v in sorted(d.items())},separators=(',',':'))

INFO|api|10
WARN|web|20
ERROR|api|30
ERROR|web|40
WARN|api|50

Parse pipe records and return compact JSON per service with counts by level, omitting zero-count levels.


Submission OQZS3B

import json
def transform(input):
 a=json.loads(input)['items'];g=0
 for x in a:x['line_total']=x['price']*x['qty'];g+=x['line_total']
 a.append({'grand_total':g});return json.dumps(a,separators=(',',':'))

Parse JSON items, add line_total=price*qty to each item and append a final summary object with grand_total, returning compact JSON.


Submission 2F47ZT

import csv,io,json
def transform(input):
 a=sorted((int(r['start']),int(r['end'])) for r in csv.DictReader(io.StringIO(input)));m=[]
 for s,e in a:
  if not m or s>m[-1][1]:m.append([s,e])
  else:m[-1][1]=max(m[-1][1],e)
 return json.dumps(m,separators=(',',':'))

Parse intervals from CSV, merge overlapping intervals, and return compact JSON array of merged [start,end] pairs.


Submission FVTWNZ

import json
def transform(input):
 a=json.loads(input)['matrix'];t=[list(x) for x in zip(*a)] if a else [];return json.dumps({'matrix':t},separators=(',',':'))

Transpose the rectangular matrix in JSON and return compact JSON under key matrix.


Submission C0BDRA

import csv,io,json
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input)):
  a=d.setdefault(r['host'],{'total':0,'errors':0});a['total']+=1;a['errors']+=int(r['status'])>=500
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

host,status
api,200
web,500
api,503
web,200
api,200

Parse CSV and return compact JSON per host with total requests and error count where status >= 500.


Submission DNFIR9

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

Parse semicolon-delimited key=value pairs splitting only on the first '=', preserve empty values, and return sorted compact JSON.


Submission 7530VZ

import csv,io,json
def transform(input):
 a=[{'path':r['path'],'size':int(r['size'])} for r in csv.DictReader(io.StringIO(input))];a.sort(key=lambda x:(-x['size'],x['path']));return json.dumps(a[:2],separators=(',',':'))

Parse CSV and return the two largest files as compact JSON sorted by size descending then path ascending.


Submission CJIT0S

import csv,io,json
def transform(input):
 a=list(csv.DictReader(io.StringIO(input)));ids={r['id'] for r in a};d={}
 for r in a:
  p=r['parent']
  if p and p in ids:d.setdefault(p,[]).append(int(r['id']))
 return json.dumps({k:sorted(v) for k,v in sorted(d.items(),key=lambda x:int(x[0]))},separators=(',',':'))

Parse CSV parent relations; return compact JSON mapping each existing parent id to sorted child ids, ignoring references to missing parents.


Submission 71GFPT

import json
def transform(input):
 r={}
 for l in input.splitlines():
  k,v=[x.strip() for x in l.split(':',1)]
  if v=='true':z=True
  elif v=='false':z=False
  elif v=='null':z=None
  else:
   try:z=int(v)
   except:z=v
  r[k]=z
 return json.dumps(r,separators=(',',':'))

alpha: 1
beta: true
gamma: null
delta: text

Parse simple key: value lines and coerce integers, true/false, and null to native JSON types while leaving other values as strings.


Submission NF4O8P

import json
def transform(input):
 x=json.loads(input);r={str(v):k for k,vs in x.items() for v in vs};return json.dumps(dict(sorted(r.items(),key=lambda z:int(z[0]))),separators=(',',':'))

Invert a JSON mapping of group -> values into value-string -> group, skipping empty lists, and return compact JSON sorted numerically by value.


Submission A0L4KY

def transform(input):
 d={}
 for l in input.splitlines():
  k,v,s=l.split(',')
  if s=='ok':d.setdefault(k,[]).append(float(v))
 return '\n'.join(f'{k}={sum(v)/len(v):.1f}' for k,v in sorted(d.items()))

Parse comma rows without header, keep status ok, compute average numeric value per key, and return sorted key=average lines with one decimal.


Submission M1XGSE

import csv,io
def transform(input):
 d={r['id']:r['value'] for r in csv.DictReader(io.StringIO(input))};return 'id,value\n'+'\n'.join(f'{k},{d[k]}' for k in sorted(d,key=int))

Parse CSV, keep the last row for each id, then emit CSV sorted numerically by id.


Submission HZQZS9

import json
def transform(input):
 d={}
 for l in input.splitlines():
  g,vs=l.split('|',1)
  for v in filter(None,vs.split(',')):d.setdefault(v,[]).append(g)
 return json.dumps({k:sorted(v) for k,v in sorted(d.items())},separators=(',',':'))

Parse group|comma-values rows and return compact JSON mapping each value to sorted groups containing it.


Submission 1KDUED

import json,statistics
def transform(input):
 a=json.loads(input);a.remove(min(a));a.remove(max(a));a.sort();return json.dumps({'values':a,'median':statistics.median(a)},separators=(',',':'))

Parse numeric JSON array, remove min and max values once each, then return compact JSON with remaining sorted values and their median.


Submission CJT8YO

from collections import Counter
def transform(input):
 c=Counter()
 for l in input.splitlines():
  p=l.split()
  if len(p)>=4 and p[1]=='ERROR': c[p[2]]+=1
 return '\n'.join(f'{k}={v}' for k,v in sorted(c.items(),key=lambda x:(-x[1],x[0])))

Parse space-separated logs, count ERROR events per service, sort by descending count then service, and return lines 'service=count'.


Submission 9MBFBA

import json
def transform(input):
 a=json.loads(input);seen=set();u=[]
 for x in a:
  if x not in seen:seen.add(x);u.append(x)
 s=0;c=[]
 for x in u:s+=x;c.append(s)
 return json.dumps({'values':u,'cumulative':c},separators=(',',':'))

Parse a JSON integer array, remove duplicates while preserving first occurrence, then return compact JSON containing values and their cumulative sums.


Submission B6C06V

def transform(input):
 d={}
 for l in input.splitlines():
  l=l.strip()
  if not l or l.startswith('#') or ':' not in l:continue
  k,v=l.split(':',1);d[k]=int(v)
 return '\n'.join(f'{k}={d[k]}' for k in sorted(d))

Parse key:value lines ignoring comments; for duplicate keys keep the last integer value and return sorted key=value lines.


Submission N62B6Z

import csv,io,json
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input)):d.setdefault(r['user'],[]).append(r['event'])
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

user,event
u1,login
u2,login
u1,click
u1,logout
u2,click

Parse CSV and build per-user ordered event histories, returning compact JSON sorted by user id.


Submission B0LFIT

import csv,io
def transform(input):
 a=list(csv.DictReader(io.StringIO(input)));scores=sorted({int(x['score']) for x in a},reverse=True);rank={s:1+sum(1 for x in a if int(x['score'])>s) for s in scores};a.sort(key=lambda x:(rank[int(x['score'])],x['name']));return 'name,score,rank\n'+'\n'.join(f"{x['name']},{x['score']},{rank[int(x['score'])]}" for x in a)

name,score
Alice,90
Bob,75
Cara,90
Dan,60

name,score,rank
Alice,90,1
Cara,90,1
Bob,75,3
Dan,60,4

Parse CSV, assign rank by descending score with equal scores sharing a rank and gaps after ties, then return CSV sorted by rank then name.


Submission QHSZVI

import json
def transform(input):
 x=json.loads(input);r={}
 for k,v in x.items():
  if isinstance(v,dict):
   for q,z in v.items():r[f'{k}.{q}']=z
  else:r[k]=v
 return json.dumps(dict(sorted(r.items())),separators=(',',':'))

Flatten a nested JSON object one level using dot-separated keys, preserving scalar top-level values, and return compact JSON with sorted keys.


Submission NUKSMW

import csv,io
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input)):d[r['category']]=d.get(r['category'],0)+float(r['amount'])
 return '\n'.join(f'{k}={v:.2f}' for k,v in sorted(d.items(),key=lambda x:(-x[1],x[0])))

category,amount
food,10.5
travel,20
food,-2.5
travel,5

Parse CSV, sum amounts by category including negatives, sort categories by descending total then name, and return lines category=total with 2 decimals.


Submission TDH8GQ

import json
def transform(input):
 d={}
 for x in json.loads(input):d.setdefault(x['k'],[]).append(x['v'])
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Parse records and pivot them into key -> list of values preserving input order, returning compact sorted-key JSON.


Submission 86MRBT

import json
def transform(input):
 a=json.loads(input);a.sort(key=lambda x:(x['ts'],x['id']));return json.dumps(a,separators=(',',':'))

Sort JSON records by timestamp ascending and then id ascending, returning compact JSON.


Submission 7NB5SA

import json
def transform(input):
 d={}
 for l in input.splitlines():
  if '=' not in l:continue
  k,v=l.split('=',1)
  try:d[k]=d.get(k,0)+int(v)
  except:pass
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Parse key=value integer records, ignore malformed lines, sum repeated keys rather than overwrite, and return sorted compact JSON.


Submission 1IRQ7R

import json
from collections import Counter
def transform(input):
 c=Counter(input.split());a=sorted(c.items(),key=lambda x:(-x[1],x[0]))[:2];return json.dumps([{'word':k,'count':v} for k,v in a],separators=(',',':'))

apple apple banana
banana carrot apple
carrot carrot

Tokenize whitespace-separated words, count frequencies, and return the top 2 as compact JSON objects sorted by count desc then word asc.


Submission J7WACP

import json
def transform(input):
 x=json.loads(input)['rows'];r=[a for a in x if 'v' in a and a['v'] is not None];r.sort(key=lambda z:z['id']);return json.dumps(r,separators=(',',':'))

Parse JSON, keep rows where v exists and is not null, retain zero, and return compact JSON sorted by id.


Submission GFM86B

from collections import Counter
def transform(input):
 c=Counter()
 for l in input.splitlines():
  level,svc,_=l.split('|',2)
  if level=='ERROR': c[svc]+=1
 return '\n'.join(f'{k}={v}' for k,v in sorted(c.items(),key=lambda x:(-x[1],x[0])))

INFO|api|start
ERROR|api|fail
WARN|web|slow
ERROR|web|bad
ERROR|api|retry

Parse pipe-delimited logs, count ERROR events by service, and return lines service=count sorted by descending count then service.


Submission PPB38G

def transform(input):
 lines=[l.split() for l in input.splitlines() if l.strip()]; vocab=sorted({x for line in lines for x in line}); idx={x:i for i,x in enumerate(vocab)}
 return 'vocab='+','.join(vocab)+'\n'+'\n'.join(' '.join(str(idx[x]) for x in line) for line in lines)

Build an alphabetical vocabulary from all tokens and encode each input line as space-separated vocabulary indices, returning vocabulary then encoded lines.


Submission YJGEJO

import csv,io,json
def transform(input):
 rows=list(csv.DictReader(io.StringIO(input))); ids={r['id'] for r in rows}; d={}
 for r in rows:
  p=r['parent']
  if p and p in ids: d.setdefault(p,[]).append(int(r['id']))
 return json.dumps({k:sorted(v) for k,v in sorted(d.items(),key=lambda x:int(x[0]))},separators=(',',':'))

Parse parent-child CSV, ignore children whose parent id does not exist, and return compact JSON mapping each existing parent to sorted child ids.


Submission 1JQTSH

import csv,io,json
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input)):
  q=int(r['qty']); p=float(r['price']); a=d.setdefault(r['sku'],{'qty':0,'revenue':0.0}); a['qty']+=q; a['revenue']+=q*p
 for a in d.values(): a['revenue']=round(a['revenue'],2)
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Parse CSV, aggregate quantity and revenue by SKU, round revenue to 2 decimals, and return compact JSON sorted by SKU.


Submission QQRXGT

import json
def transform(input):
 x=json.loads(input); bad=set(x['blocked']); d={}
 for u in x['users']:
  if u['id'] in bad: continue
  d.setdefault(u['role'],[]).append(u['id'])
 return json.dumps({k:sorted(v) for k,v in sorted(d.items())},separators=(',',':'))

Parse JSON, exclude blocked user ids, group remaining ids by role, sort ids within each role, and return compact JSON sorted by role.


Submission XO0VO0

import json
def transform(input):
 a=json.loads(input); a.sort(key=lambda x:(-x['size'],x['path'])); return json.dumps(a[:2],separators=(',',':'))

Parse JSON file records, keep the two largest files sorted by size descending then path ascending, and return compact JSON.


Submission J79KSU

import json
def transform(input):
 a=json.loads(input)['rows']; r=[x for x in a if 'v' in x and x['v'] is not None]; r.sort(key=lambda x:x['id']); return json.dumps(r,separators=(',',':'))

Parse JSON rows, keep those where v exists and is not null while preserving zero, sort by id, and return compact JSON.


Submission 7ZW82I

import csv,io
def transform(input):
 a=list(csv.DictReader(io.StringIO(input))); scores=sorted({int(r['score']) for r in a},reverse=True); rank={s:1+sum(1 for r in a if int(r['score'])>s) for s in scores}; a.sort(key=lambda r:(rank[int(r['score'])],r['name']))
 return 'name,score,rank\n'+'\n'.join(f"{r['name']},{r['score']},{rank[int(r['score'])]}" for r in a)

name,score,rank
Ada,90,1
Cara,90,1
Bob,75,3
Dan,60,4

Parse CSV, assign competition ranks by score descending with gaps after ties, then return CSV sorted by rank then name.


Submission 8GVFAU

import csv,io
def transform(input):
 vals=[]
 for r in csv.DictReader(io.StringIO(input)):
  try: vals.append((r['date'],float(r['value'])))
  except: pass
 out=['date,delta']
 for i in range(1,len(vals)): out.append(f'{vals[i][0]},{vals[i][1]-vals[i-1][1]:g}')
 return '\n'.join(out)

Parse CSV, skip rows whose value is not numeric, compute deltas between consecutive valid readings, and return CSV with date,delta.


Submission 4BDI5W

import json,statistics
def transform(input):
 a=json.loads(input)['values']; a.remove(min(a)); a.remove(max(a)); a.sort(); return json.dumps({'values':a,'median':statistics.median(a)},separators=(',',':'))

Parse numeric JSON array, remove one occurrence each of the minimum and maximum, sort remaining values, and return compact JSON with values plus median.


Submission L3JCKF

import csv,io
def transform(input):
 d={r['id']:r['value'] for r in csv.DictReader(io.StringIO(input))}
 return 'id,value\n'+'\n'.join(f'{k},{d[k]}' for k in sorted(d,key=int))

Parse CSV, keep the last row for each id, then emit CSV sorted numerically by id.


Submission C7IM5C

import json
def transform(input):
 d={}
 for e in json.loads(input)['events']:
  a=d.setdefault(e['type'],{'count':0,'total':0}); a['count']+=1; a['total']+=e['value']
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Group JSON events by type and return compact JSON with count and total value per type, sorted by type.


Submission 3CH8CH

import csv,io,json
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input)):
  a=d.setdefault(r['host'],{'total':0,'errors':0}); a['total']+=1; a['errors']+=int(r['status'])>=500
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Parse CSV and return compact JSON per host with total request count and error count where status >= 500, sorted by host.


Submission MFSXY4

import json
def transform(input):
 a=[x for x in json.loads(input)['records'] if x['score']>=7]; a.sort(key=lambda x:(-x['score'],x['id'])); return json.dumps([x['id'] for x in a],separators=(',',':'))

Parse JSON records, keep those with score at least 7, sort by score descending then id ascending, and return compact JSON array of ids.


Submission LGF62W

import csv,io,json
def transform(input):
 d={}
 for r in csv.DictReader(io.StringIO(input)):
  if r['status']!='ok': continue
  d[r['region']]=d.get(r['region'],0)+int(r['amount'])
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

user,region,amount,status
u1,us,10,ok
u2,eu,20,fail
u3,us,15,ok
u4,eu,5,ok

Parse CSV, keep only status=ok rows, aggregate amount by region, and return compact JSON sorted by region.


Submission WI1N0G

import json,csv,io
def transform(input):
 rows=[]
 for o in json.loads(input):
  for t in o['tags']: rows.append((t,o['name']))
 rows.sort()
 s=io.StringIO(); w=csv.writer(s,lineterminator='\n'); w.writerow(['tag','name']); w.writerows(rows)
 return s.getvalue().strip()

Expand each object into one row per tag, omit empty tag lists, and return CSV sorted by tag then name.


Submission AP7ACY

import json
def transform(input):
 a=json.loads(input)['items']; total=0
 for x in a: x['line_total']=x['price']*x['qty']; total+=x['line_total']
 a.append({'grand_total':total}); return json.dumps(a,separators=(',',':'))

Parse JSON items, add line_total=price*qty to each item, append a final grand_total object, and return compact JSON.


Submission WTDPCG

import json
def transform(input):
 a=json.loads(input)['matrix']; r=[list(x) for x in zip(*a[::-1])] if a else []
 return json.dumps({'matrix':r},separators=(',',':'))

Parse JSON matrix, rotate it 90 degrees clockwise, and return compact JSON under key matrix.


Submission QXGSAC

import json
def transform(input):
 x=json.loads(input)['orders']
 a=[o for o in x if o['paid']]
 a.sort(key=lambda o:(-o['total'],o['id']))
 return json.dumps([o['id'] for o in a],separators=(',',':'))

Parse JSON orders, keep paid orders, sort by total descending then id ascending, and return compact JSON array of ids only.


Submission VPJV6E

def transform(input):
 d={}
 for l in input.splitlines():
  l=l.strip()
  if not l or l.startswith('#') or '=' not in l: continue
  k,v=l.split('=',1); d[k]=d.get(k,0)+int(v)
 return '\n'.join(f'{k}={d[k]}' for k in sorted(d))

alpha=1
beta=2
alpha=4
# ignored
gamma=3

Parse key=value lines ignoring comments and blanks, sum repeated integer keys, and return sorted key=value lines.


Submission GWM2OI

import json
from datetime import datetime
def transform(input):
 d={}
 for l in input.splitlines():
  t,s,v=l.split(','); h=datetime.fromisoformat(t.replace('Z','+00:00')).strftime('%Y-%m-%dT%H'); k=h+'|'+s; d[k]=d.get(k,0)+int(v)
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Parse timestamp,service,value rows, aggregate values by UTC hour and service, and return compact JSON with keys hour|service sorted lexicographically.


Submission S4ZWJM

import json
def transform(input):
 d={}
 for l in input.splitlines():
  g,vals=l.split('|',1)
  for v in filter(None,vals.split(',')): d.setdefault(v,[]).append(g)
 return json.dumps({k:sorted(v) for k,v in sorted(d.items())},separators=(',',':'))

Parse group|comma-values rows and invert them into value -> sorted groups, returning compact JSON sorted by value.


Submission GEGCW1

import json
def transform(input):
 a=json.loads(input); prev=None
 for x in a:
  x['previous_v']=prev; x['delta']=None if prev is None else x['v']-prev; prev=x['v']
 return json.dumps(a,separators=(',',':'))

Parse JSON records and add previous_v plus delta relative to the preceding record; first record uses nulls. Return compact JSON.


Submission E0BQPU

def transform(input):
 d={}
 for l in input.splitlines():
  k,v,s=l.split(',')
  if s=='ok': d.setdefault(k,[]).append(float(v))
 return '\n'.join(f'{k}={sum(v)/len(v):.1f}' for k,v in sorted(d.items()))

Parse key,value,status rows without header, keep status ok, compute average value per key, and return sorted key=average lines with one decimal.


Submission J9497Y

import json
def transform(input):
 x=json.loads(input)['groups']; r={str(v):k for k,vals in x.items() for v in vals}; return json.dumps(dict(sorted(r.items(),key=lambda p:int(p[0]))),separators=(',',':'))

Invert JSON mapping group -> integer list into integer-string -> group, skip empty lists, and return compact JSON sorted numerically by key.


Submission M6K1L9

import json
def transform(input):
 d={}
 for x in json.loads(input)['rows']: d.setdefault(x['k'],[]).append(x['v'])
 return json.dumps(dict(sorted(d.items())),separators=(',',':'))

Pivot JSON records into key -> list of values preserving original order, and return compact JSON sorted by key.


Submission Z7M4CK

import csv,io,json
def transform(input):
 r=csv.DictReader(io.StringIO(input)); d={k:0 for k in r.fieldnames}
 for row in r:
  for k,v in row.items(): d[k]+=bool(v)
 return json.dumps(d,separators=(',',':'))

Parse CSV and return compact JSON containing the count of non-empty data cells per column.


Submission 57F2NE

import csv,io,json
def transform(input):
 a=sorted((int(r['start']),int(r['end'])) for r in csv.DictReader(io.StringIO(input))); m=[]
 for s,e in a:
  if not m or s>m[-1][1]: m.append([s,e])
  else: m[-1][1]=max(m[-1][1],e)
 return json.dumps(m,separators=(',',':'))

Parse intervals from CSV, merge overlaps, and return compact JSON array of merged [start,end] pairs.


Submission 2CUWCZ

import json
def transform(input):
 r={}
 for l in input.splitlines():
  k,v=[x.strip() for x in l.split(':',1)]
  if v=='true': z=True
  elif v=='false': z=False
  elif v=='null': z=None
  else:
   try: z=int(v)
   except: z=v
  r[k]=z
 return json.dumps(r,separators=(',',':'))

Parse simple key: value lines and coerce integers, true/false, and null to native JSON types; leave other values as strings.


Submission 0O76OB

import json
def transform(input):
 x=json.loads(input); r={}
 for k,v in x.items():
  if isinstance(v,dict):
   for q,z in v.items(): r[f'{k}.{q}']=z
  else: r[k]=v
 return json.dumps(dict(sorted(r.items())),separators=(',',':'))

Flatten a JSON object one level using dot-separated keys, preserve scalar top-level values, and return compact JSON with sorted keys.


Submission NEOAQQ

import json

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

[server]
host=localhost
port=8080

[db]
name=voicemart
user=admin

Convert an INI-style config text (sections in [brackets], key=value lines) into a nested JSON object.


Submission U2X8AV

import csv, io, json

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    result = {row['key']: row['value'] for row in reader}
    return json.dumps(result)

key,value
hostname,voicemart-01
region,us-east
tier,production

Merge two equal-length CSV columns (keys, values) given as a single CSV with headers 'key,value' into a single-line JSON object.


Submission O5M06S

import csv, io, json

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    credits = debits = 0.0
    for row in reader:
        amt = float(row['amount'])
        if amt >= 0:
            credits += amt
        else:
            debits += amt
    return json.dumps({
        "total_credits": round(credits, 2),
        "total_debits": round(debits, 2),
        "net_balance": round(credits + debits, 2)
    })

Given a CSV of transactions (date,amount) where amount can be negative, output a JSON object with total_credits, total_debits, and net_balance (all rounded to 2 decimals).


Submission 5QERYE

import json

def transform(text):
    data = json.loads(text)
    for d in data:
        d['tags'] = [t.strip() for t in d['tags'].split(',') if t.strip()]
    return json.dumps(data)

Given a JSON array of objects with a 'tags' field (comma-separated string), split tags into a list and return the transformed JSON array.


Submission POUFHQ

import json
from collections import defaultdict

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    result = defaultdict(list)
    for l in lines:
        k, v = l.split('=', 1)
        result[k.strip()].append(v.strip())
    return json.dumps(dict(result))

tag=urgent
tag=backend
owner=alice
tag=bug
owner=bob

Given lines of 'key=value' pairs where some keys repeat, collect all values for each key into a JSON object mapping key to a list of values.


Submission GWORUB

import csv, io, json

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    result = []
    for row in reader:
        scores = [float(row['math']), float(row['science']), float(row['english'])]
        avg = round(sum(scores) / len(scores), 1)
        result.append({"name": row['name'], "average": avg})
    return json.dumps(result)

Given a CSV of student scores across subjects (name,math,science,english), compute each student's average score rounded to 1 decimal and output as JSON array of {name, average}.


Submission XSD0KF

import csv, io, json

def infer_type(values):
    def is_int(v):
        try:
            int(v)
            return True
        except ValueError:
            return False
    def is_float(v):
        try:
            float(v)
            return True
        except ValueError:
            return False
    if all(is_int(v) for v in values):
        return "int"
    if all(is_float(v) for v in values):
        return "float"
    return "str"

def transform(text):
    reader = csv.reader(io.StringIO(text.strip()))
    rows = list(reader)
    header = rows[0]
    cols = list(zip(*rows[1:]))
    types = {header[i]: infer_type(cols[i]) for i in range(len(header))}
    return json.dumps(types)

Given a plain CSV, output a JSON object reporting each column's name and its inferred type ('int', 'float', or 'str') based on scanning all rows.


Submission DY24D5

import json, re

def transform(text):
    pattern = r'[\w.+-]+@[\w-]+\.[\w.-]+'
    found = re.findall(pattern, text)
    seen = []
    for f in found:
        if f not in seen:
            seen.append(f)
    return json.dumps(seen)

Contact alice@example.com or bob@example.org for details. Cc: alice@example.com always.

Given a block of text containing email addresses scattered among other words, extract all valid email addresses into a JSON array, preserving order and removing duplicates.


Submission GWMT0C

import json

def transform(text):
    data = json.loads(text)
    subtotal = sum(item['price'] * item['qty'] for item in data['items'])
    tax = round(subtotal * 0.08, 2)
    subtotal = round(subtotal, 2)
    total = round(subtotal + tax, 2)
    return json.dumps({"subtotal": subtotal, "tax": tax, "total": total})

Given a JSON object representing a shopping cart ({items: [{name, price, qty}]}), compute the subtotal, a flat 8% tax, and the total, each rounded to 2 decimals, and return as JSON.


Submission 7B7USE

import json
from collections import defaultdict

def transform(text):
    data = json.loads(text)
    totals = defaultdict(int)
    for d in data:
        totals[d['sku']] += d['quantity']
    return json.dumps(dict(totals))

Given a JSON array of {sku, warehouse, quantity} records, produce a JSON object mapping sku to total quantity summed across all warehouses.


Submission IYC1DK

import json

def transform(text):
    data = json.loads(text)
    pairs = sorted(data.items(), key=lambda kv: kv[1])
    return json.dumps([list(p) for p in pairs])

Given a JSON object mapping product names to prices, return a JSON array of [name, price] pairs sorted by price ascending.


Submission K1GZ1E

import json

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

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

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


Submission O1ZK5T

import csv, io, json
from collections import defaultdict

def transform(text):
    reader = csv.reader(io.StringIO(text.strip()))
    rows = list(reader)[1:]
    sums = defaultdict(float)
    for cat, amt in rows:
        sums[cat] += float(amt)
    return json.dumps({k: round(v, 2) for k, v in sums.items()})

category,amount
food,12.50
travel,45.00
food,7.25
utilities,60.00
travel,15.75

Group a CSV of (category,amount) rows by category and output JSON mapping category to the sum of amounts.


Submission Q4YQMO

import csv, io

def transform(text):
    reader = csv.reader(io.StringIO(text.strip()))
    rows = list(reader)
    header = rows[0]
    age_idx = header.index('age')
    filtered = [r for r in rows[1:] if int(r[age_idx]) >= 18]
    out = io.StringIO()
    writer = csv.writer(out, lineterminator='\n')
    writer.writerow(header)
    writer.writerows(filtered)
    return out.getvalue().strip()

name,age
Tom,15
Jerry,22
Spike,17
Tyke,19

Filter rows of a CSV to only those where the 'age' column is 18 or older, keeping the header, and output as CSV.


Submission H4MLJL

import json, csv, io
from collections import defaultdict

def transform(text):
    data = json.loads(text)
    regions = sorted(set(d['region'] for d in data))
    products = sorted(set(d['product'] for d in data))
    table = defaultdict(lambda: defaultdict(int))
    for d in data:
        table[d['region']][d['product']] += d['sales']
    out = io.StringIO()
    writer = csv.writer(out, lineterminator='\n')
    writer.writerow(['region'] + products)
    for r in regions:
        writer.writerow([r] + [table[r][p] for p in products])
    return out.getvalue().strip()

Convert a JSON array of objects into a pivoted CSV: rows are unique 'region' values, columns are unique 'product' values, cells are 'sales' totals.


Submission BL1UZU

import json
from urllib.parse import urlparse, parse_qs

def transform(text):
    p = urlparse(text.strip())
    query = {k: v[0] if len(v) == 1 else v for k, v in parse_qs(p.query).items()}
    return json.dumps({
        "scheme": p.scheme,
        "netloc": p.netloc,
        "path": p.path,
        "query": query
    })

Parse a full URL into its components (scheme, netloc, path, query params as a JSON object) and return as JSON.


Submission 59HLU0

import json

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    rows = []
    for l in lines:
        fields = {}
        for pair in l.split(';'):
            k, v = pair.split(':', 1)
            fields[k.strip()] = v.strip()
        rows.append(fields)
    return json.dumps(rows)

Convert semicolon-separated key:value pairs on each line into a JSON array of objects.


Submission SELWAJ

import json

def transform(text):
    nums = json.loads(text)
    return json.dumps({
        "min": min(nums),
        "max": max(nums),
        "mean": round(sum(nums) / len(nums), 2),
        "count": len(nums)
    })

Given a JSON array of numbers, return a JSON object with min, max, mean (rounded to 2 decimals), and count.


Submission 530E6R

import json, re
from collections import Counter

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    levels = []
    for l in lines:
        m = re.match(r'\[(\w+)\]', l)
        if m:
            levels.append(m.group(1))
    return json.dumps(dict(Counter(levels)))

[INFO] server started
[ERROR] connection failed
[INFO] retrying
[WARN] slow response
[ERROR] timeout

Parse a block of log lines like '[LEVEL] message' and return a JSON object counting occurrences of each level.


Submission B1CIFU

import json
from collections import Counter

def transform(text):
    words = json.loads(text)
    counts = Counter(w.lower() for w in words)
    return json.dumps(dict(counts))

Convert a JSON array of word strings into a JSON object mapping each unique word (lowercased) to its frequency count.


Submission 6W1TQL

import json

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

Alice     30   Chicago
Bob       45   Denver
Cara      27   Miami

Convert a fixed-width text table (columns: name 10 chars, age 5 chars, city 10 chars) into JSON array of objects.


Submission ORSV6F

import csv, io

def transform(text):
    reader = csv.reader(io.StringIO(text.strip()))
    rows = list(reader)
    header, body = rows[0], rows[1:]
    seen = set()
    unique = []
    for r in body:
        key = tuple(r)
        if key not in seen:
            seen.add(key)
            unique.append(r)
    out = io.StringIO()
    writer = csv.writer(out, lineterminator='\n')
    writer.writerow(header)
    writer.writerows(unique)
    return out.getvalue().strip()

Remove duplicate rows from a CSV (matching on all columns), keeping only the first occurrence, output as CSV.


Submission WW1CGE

import json, re

def to_snake(name):
    return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()

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

Convert JSON object keys from camelCase to snake_case, preserving values, for a flat JSON object.


Submission SIEKAC

import json, re

def transform(text):
    lines = [l.strip() for l in text.strip().split('\n') if l.strip()]
    name, street, last = lines[0], lines[1], lines[2]
    m = re.match(r'(.+),\s*(\w{2})\s+(\d{5})', last)
    city, state, zip_code = m.group(1), m.group(2), m.group(3)
    return json.dumps({
        "name": name, "street": street,
        "city": city, "state": state, "zip": zip_code
    })

Jane Doe
123 Maple St
Springfield, IL 62704

Parse a multi-line US-style address block (name, street, 'city, state zip') into a structured JSON object.


Submission 0CL37B

import json
from datetime import datetime

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    result = []
    for l in lines:
        dt = datetime.fromisoformat(l.replace('Z', '+00:00'))
        if 9 <= dt.hour < 17:
            result.append(l)
    return json.dumps(result)

Given a block of ISO 8601 timestamps (one per line), filter to only those between 09:00 and 17:00 UTC and return as a JSON array of the original strings.


Submission 72SVNH

import csv, io

def transform(text):
    reader = csv.DictReader(io.StringIO(text.strip()))
    rows = []
    for row in reader:
        first, last = row['full_name'].split(' ', 1)
        rows.append({'first_name': first, 'last_name': last, 'email': row['email']})
    out = io.StringIO()
    writer = csv.DictWriter(out, fieldnames=['first_name', 'last_name', 'email'], lineterminator='\n')
    writer.writeheader()
    writer.writerows(rows)
    return out.getvalue().strip()

full_name,email
John Smith,john@example.com
Mary Ann Lee,mary@example.com

first_name,last_name,email
John,Smith,john@example.com
Mary,Ann Lee,mary@example.com

Given a CSV with a 'full_name' column, split it into 'first_name' and 'last_name' columns and output the modified CSV (dropping full_name).


Submission X3T7JM

import json

def transform(text):
    data = json.loads(text)
    leaves = []
    def walk(node):
        children = node.get('children') or []
        if not children:
            leaves.append(node['name'])
        else:
            for c in children:
                walk(c)
    for root in data:
        walk(root)
    return json.dumps(leaves)

Given a JSON array of nested category trees ({name, children:[...]}), return a JSON array of all leaf node names (nodes with no children).


Submission MBNNOJ

import json
from datetime import datetime

def transform(text):
    data = json.loads(text)
    data.sort(key=lambda d: datetime.fromisoformat(d['timestamp'].replace('Z', '+00:00')))
    return json.dumps(data)

Given a JSON array of log event objects with 'timestamp' (ISO 8601) and 'event', sort them chronologically and return the sorted JSON array.


Submission NJ9H88

import json
from collections import Counter

def transform(text):
    lines = [l for l in text.strip().split('\n') if l]
    statuses = []
    for l in lines:
        parts = l.split()
        statuses.append(parts[-1])
    return json.dumps(dict(Counter(statuses)))

Given lines of 'IP - method path status' access-log entries, return a JSON object mapping each HTTP status code (as string) to the number of occurrences.


Submission XDAHEB

import csv, io

def transform(text):
    reader = csv.reader(io.StringIO(text.strip()))
    rows = list(reader)
    header = rows[0]
    lines = ['| ' + ' | '.join(header) + ' |']
    lines.append('| ' + ' | '.join(['---'] * len(header)) + ' |')
    for row in rows[1:]:
        lines.append('| ' + ' | '.join(row) + ' |')
    return '\n'.join(lines)

Convert a CSV table into a Markdown table string with a header separator row.


Submission P6HW5R

import json

def transform(input):
    lines = input.strip().splitlines()
    import re
    stats = {}
    for line in lines:
        m = re.search(r'service=(\w+) path=(\S+) status=(\d+) latency_ms=(\d+)', line)
        if not m or m.group(2) == '/health':
            continue
        service, status, latency = m.group(1), int(m.group(3)), int(m.group(4))
        bucket = stats.setdefault(service, {'requests': 0, 'errors': 0, 'latencies': []})
        bucket['requests'] += 1
        bucket['errors'] += status >= 500
        bucket['latencies'].append(latency)
    result = {k: {'error_rate_pct': round(v['errors'] * 100 / v['requests'], 1), 'avg_latency_ms': round(sum(v['latencies']) / len(v['latencies']), 1)} for k, v in sorted(stats.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

2026-08-18T10:00:01Z service=auth path=/login status=200 latency_ms=84
2026-08-18T10:00:02Z service=auth path=/login status=503 latency_ms=420
2026-08-18T10:00:03Z service=payments path=/charge status=201 latency_ms=190
2026-08-18T10:00:04Z service=payments path=/charge status=500 latency_ms=610
2026-08-18T10:00:05Z service=auth path=/health status=500 latency_ms=2
2026-08-18T10:00:06Z service=payments path=/charge status=200 latency_ms=155

Parse the supplied raw log text and compute error rate and latency by service, excluding health checks. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission XF0RFY

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: [0, 0])
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split())
        key = (f['service'], f['phase']); d[key][0] += 1; d[key][1] += int(f['status']) >= 500
    services = sorted({k[0] for k in d})
    result = {}
    for service in services:
        before = d[(service, 'before')]; after = d[(service, 'after')]
        b = before[1] / before[0]; a = after[1] / after[0]
        result[service] = {'before_error_pct': round(b * 100, 1), 'after_error_pct': round(a * 100, 1), 'delta_points': round((a - b) * 100, 1)}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

phase=before status=200 service=api
phase=before status=200 service=api
phase=before status=500 service=api
phase=after status=200 service=api
phase=after status=500 service=api
phase=after status=503 service=api
phase=before status=200 service=worker
phase=after status=200 service=worker

Parse the supplied raw log text and compute deployment error regression compared with pre-deploy traffic. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 5PFPDJ

import json

def transform(input):
    lines = input.strip().splitlines()
    from datetime import datetime
    open_at = {}; totals = {}; episodes = {}
    for line in lines:
        stamp, cfield, sfield = line.split(); c = cfield.split('=')[1]; state = sfield.split('=')[1]
        t = datetime.fromisoformat(stamp.replace('Z', '+00:00'))
        if state == 'OPEN' and c not in open_at: open_at[c] = t
        elif state == 'CLOSED' and c in open_at:
            totals[c] = totals.get(c, 0) + int((t - open_at.pop(c)).total_seconds()); episodes[c] = episodes.get(c, 0) + 1
    result = {c: {'open_episodes': episodes[c], 'total_open_seconds': totals[c]} for c in sorted(totals)}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

2026-08-18T13:00:00Z circuit=payments state=CLOSED
2026-08-18T13:01:10Z circuit=payments state=OPEN
2026-08-18T13:02:00Z circuit=payments state=HALF_OPEN
2026-08-18T13:02:20Z circuit=payments state=CLOSED
2026-08-18T13:05:00Z circuit=search state=OPEN
2026-08-18T13:07:30Z circuit=search state=CLOSED

Parse the supplied raw log text and compute circuit breaker open intervals and total outage seconds. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission U3ZOVM

import json

def transform(input):
    lines = input.strip().splitlines()
    import os
    from collections import defaultdict
    groups = {'.jpg':'image','.png':'image','.js':'script','.html':'document'}
    d = defaultdict(lambda: {'served': 0, 'client_error': 0})
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); kind = groups.get(os.path.splitext(f['path'])[1], 'other'); status = int(f['status']); size = int(f['bytes'])
        if 200 <= status < 300: d[kind]['served'] += size
        elif 400 <= status < 500: d[kind]['client_error'] += size
    result = dict(sorted(d.items()))
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

path=/img/a.jpg status=200 bytes=4000
path=/img/b.png status=404 bytes=220
path=/app/main.js status=200 bytes=9000
path=/app/old.js status=404 bytes=310
path=/docs/readme.html status=200 bytes=1500
path=/img/c.jpg status=206 bytes=1800

Parse the supplied raw log text and compute cDN bandwidth by content type and 4xx waste. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission AER95N

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    seen = defaultdict(lambda: {'active': set(), 'buyers': set(), 'purchases': 0})
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); row = seen[f['campaign']]
        row['active'].add(f['user'])
        if f['event'] == 'buy': row['buyers'].add(f['user']); row['purchases'] += 1
    result = {c: {'unique_users': len(v['active']), 'buyer_conversion_pct': round(100 * len(v['buyers']) / len(v['active']), 1), 'purchases': v['purchases']} for c, v in sorted(seen.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

campaign=spring user=u1 event=view
campaign=spring user=u1 event=buy
campaign=spring user=u2 event=view
campaign=spring user=u3 event=buy
campaign=summer user=u4 event=view
campaign=summer user=u5 event=view
campaign=summer user=u5 event=buy
campaign=summer user=u5 event=buy

Parse the supplied raw log text and compute unique active users and conversion rate by campaign. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission ED32FD

import json

def transform(input):
    lines = input.strip().splitlines()
    import math
    from collections import defaultdict
    lat = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split())
        if int(f['status']) < 500:
            lat[f['endpoint']].append(int(f['latency_ms']))
    result = {}
    for endpoint, values in sorted(lat.items()):
        values.sort(); idx = max(0, math.ceil(0.95 * len(values)) - 1)
        result[endpoint] = {'p95_ms': values[idx], 'over_500ms': sum(x > 500 for x in values)}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

endpoint=/search latency_ms=90 status=200
endpoint=/search latency_ms=120 status=200
endpoint=/search latency_ms=410 status=200
endpoint=/search latency_ms=230 status=504
endpoint=/export latency_ms=800 status=200
endpoint=/export latency_ms=1200 status=200
endpoint=/export latency_ms=950 status=500
endpoint=/export latency_ms=700 status=200

Parse the supplied raw log text and compute per-endpoint p95 and slow-request count. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission CTCGKF

import json

def transform(input):
    lines = input.strip().splitlines()
    from datetime import datetime
    sessions = {}
    for line in lines:
        stamp, sfield, efield = line.split()
        sid = sfield.split('=', 1)[1]; event = efield.split('=', 1)[1]
        row = sessions.setdefault(sid, {'events': 0})
        row['events'] += 1
        if event in ('start', 'end'): row[event] = datetime.fromisoformat(stamp.replace('Z', '+00:00'))
    result = {sid: {'duration_seconds': int((v['end'] - v['start']).total_seconds()), 'events': v['events']} for sid, v in sorted(sessions.items()) if 'start' in v and 'end' in v}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

Parse the supplied raw log text and compute session duration and event count, excluding incomplete sessions. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 1HQUZM

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: [0, 0])
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split())
        if f['maintenance'] == 'true': continue
        d[f['zone']][0] += 1; d[f['zone']][1] += f['result'] == 'ok'
    result = {z: {'eligible_checks': v[0], 'availability_pct': round(v[1] * 100 / v[0], 2)} for z, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

zone=a result=ok maintenance=false
zone=a result=fail maintenance=false
zone=a result=fail maintenance=true
zone=a result=ok maintenance=false
zone=b result=ok maintenance=false
zone=b result=ok maintenance=false
zone=b result=fail maintenance=false

Parse the supplied raw log text and compute availability by zone with maintenance excluded. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission AVEF7B

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(dict)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['token']][f['event']] = int(f['ts'])
    lifetimes = []; revoked = []
    for events in d.values():
        end = events.get('revoked', events.get('expired'))
        if end is not None: lifetimes.append(end - events['issued'])
        if 'revoked' in events: revoked.append(events['revoked'] - events['issued'])
    result = {'tokens_completed': len(lifetimes), 'median_lifetime_s': __import__('statistics').median(lifetimes), 'max_revocation_lag_s': max(revoked)}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

token=a event=issued ts=100
token=a event=revoked ts=460
token=b event=issued ts=200
token=b event=expired ts=800
token=c event=issued ts=300
token=c event=revoked ts=320

Parse the supplied raw log text and compute token issuance lifetime and revocation lag. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 5D25U9

import json

def transform(input):
    lines = input.strip().splitlines()
    import re
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        m = re.match(r'duration=(\d+)ms rows=(\d+) sql="(.+)"', line)
        duration, sql = int(m.group(1)), m.group(3)
        fingerprint = re.sub(r'=\d+', '=?', sql)
        d[fingerprint].append(duration)
    result = {q: {'calls': len(v), 'slow_calls': sum(x >= 300 for x in v), 'max_ms': max(v)} for q, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

duration=42ms rows=1 sql="SELECT * FROM users WHERE id=17"
duration=380ms rows=1 sql="SELECT * FROM users WHERE id=22"
duration=510ms rows=80 sql="SELECT * FROM orders WHERE account_id=9"
duration=620ms rows=65 sql="SELECT * FROM orders WHERE account_id=14"
duration=75ms rows=1 sql="SELECT * FROM users WHERE id=31"

Parse the supplied raw log text and compute database slow-query summary by normalized statement fingerprint. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 5FLE0T

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['request_id']].append((int(f['status']), f['host']))
    dupes = {rid: rows for rid, rows in d.items() if len(rows) > 1}
    result = {'duplicate_ids': sorted(dupes), 'conflicting_ids': sorted(rid for rid, rows in dupes.items() if len({x[0] for x in rows}) > 1), 'duplicate_log_lines': sum(len(v) - 1 for v in dupes.values())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

request_id=r1 status=200 host=a
request_id=r2 status=500 host=a
request_id=r1 status=200 host=b
request_id=r3 status=201 host=b
request_id=r2 status=200 host=c
request_id=r4 status=404 host=a
request_id=r4 status=404 host=b

Parse the supplied raw log text and compute detect duplicate request IDs and conflicting outcomes. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 7T2N81

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[int(f['partition'])].append(int(f['lag']))
    result = {str(p): {'peak_lag': max(v), 'net_change': v[-1] - v[0], 'recovered_pct': round(max(0, v[0] - v[-1]) * 100 / v[0], 1) if v[0] else 0.0} for p, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

time=1 partition=0 lag=120
time=2 partition=0 lag=90
time=3 partition=0 lag=40
time=1 partition=1 lag=20
time=2 partition=1 lag=85
time=3 partition=1 lag=60
time=1 partition=2 lag=0
time=2 partition=2 lag=0

Parse the supplied raw log text and compute consumer lag recovery and peak by partition. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission KDVOO1

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import Counter
    first = {}
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split())
        if f['payment'] not in first or int(f['attempt']) < int(first[f['payment']]['attempt']): first[f['payment']] = f
    reasons = Counter(v['reason'] for v in first.values() if v['outcome'] == 'decline')
    declines = sum(reasons.values())
    result = {'first_attempt_declines': declines, 'reason_share_pct': {k: round(v * 100 / declines, 1) for k, v in sorted(reasons.items())}}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

payment=p1 attempt=1 outcome=decline reason=insufficient_funds
payment=p1 attempt=2 outcome=approved reason=none
payment=p2 attempt=1 outcome=decline reason=expired_card
payment=p3 attempt=1 outcome=approved reason=none
payment=p4 attempt=1 outcome=decline reason=insufficient_funds
payment=p4 attempt=2 outcome=decline reason=insufficient_funds

Parse the supplied raw log text and compute payment authorization decline reason share, excluding retries. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 0YZ0R5

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: {'total': 0, 'malformed': 0, 'valid_bytes': 0})
    for line in lines:
        parts = [x.split('=', 1) for x in line.split() if '=' in x]; f = dict(parts); row = d.get(f.get('source'))
        if row is None: continue
        row['total'] += 1
        try: row['valid_bytes'] += int(f['bytes'])
        except (KeyError, ValueError): row['malformed'] += 1
    result = {s: {'malformed_pct': round(v['malformed'] * 100 / v['total'], 1), 'valid_bytes': v['valid_bytes']} for s, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

source=app bytes=120 level=INFO
source=app bytes=oops level=ERROR
source=worker bytes=80 level=INFO
source=worker level=WARN
source=app bytes=220 level=ERROR
source=worker bytes=140 level=INFO

Parse the supplied raw log text and compute log ingestion malformed-rate and valid byte totals by source. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission GHSHH3

import json

def transform(input):
    lines = input.strip().splitlines()
    import statistics
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['priority']].append(int(f['delivered']) - int(f['promised']))
    result = {p: {'median_delay': statistics.median(v), 'late_pct': round(sum(x > 0 for x in v) * 100 / len(v), 1), 'worst_delay': max(v)} for p, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

priority=high promised=100 delivered=95
priority=high promised=110 delivered=125
priority=high promised=120 delivered=145
priority=low promised=200 delivered=230
priority=low promised=220 delivered=210
priority=low promised=240 delivered=260

Parse the supplied raw log text and compute median delivery delay and late share by priority. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission EMXPWP

import json

def transform(input):
    lines = input.strip().splitlines()
    from datetime import datetime
    breach = {}; delays = {}
    for line in lines:
        stamp, s, cpu, action = line.split(); service = s.split('=')[1]; value = int(cpu.split('=')[1]); act = action.split('=')[1]
        t = datetime.fromisoformat(stamp.replace('Z', '+00:00'))
        if value >= 80 and service not in breach: breach[service] = t
        if act == 'scale_out' and service in breach: delays[service] = int((t - breach[service]).total_seconds())
    result = {'delay_seconds': dict(sorted(delays.items())), 'slowest_service': max(delays, key=lambda k: delays[k])}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

2026-08-18T14:00:00Z service=api cpu=72 action=none
2026-08-18T14:00:30Z service=api cpu=86 action=none
2026-08-18T14:01:10Z service=api cpu=91 action=scale_out
2026-08-18T14:02:00Z service=worker cpu=83 action=none
2026-08-18T14:03:45Z service=worker cpu=88 action=scale_out

Parse the supplied raw log text and compute autoscaling response delay from threshold breach to scale action. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission GA7ALL

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['queue']].append((f['id'], int(f['now']) - int(f['enqueued'])))
    result = {}
    for q, rows in sorted(d.items()):
        buckets = {'under_60s': 0, '60_to_299s': 0, '300s_plus': 0}
        for _, age in rows: buckets['under_60s' if age < 60 else '60_to_299s' if age < 300 else '300s_plus'] += 1
        oldest = max(rows, key=lambda x: x[1])
        result[q] = {'age_buckets': buckets, 'oldest_id': oldest[0], 'oldest_age_s': oldest[1]}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

now=1000 queue=orders id=a enqueued=990
now=1000 queue=orders id=b enqueued=920
now=1000 queue=orders id=c enqueued=600
now=1000 queue=users id=d enqueued=970
now=1000 queue=users id=e enqueued=850

Parse the supplied raw log text and compute dead-letter queue age buckets and oldest message. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission K9DVI6

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: [0, 0, 0])
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split())
        if int(f['status']) != 200: continue
        row = d[f['encoding']]; row[0] += int(f['raw']); row[1] += int(f['sent']); row[2] += 1
    result = {e: {'responses': v[2], 'bytes_saved': v[0] - v[1], 'reduction_pct': round((v[0] - v[1]) * 100 / v[0], 1)} for e, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

encoding=gzip raw=10000 sent=3200 status=200
encoding=gzip raw=8000 sent=2800 status=200
encoding=br raw=12000 sent=3000 status=200
encoding=br raw=5000 sent=0 status=304
encoding=identity raw=2000 sent=2000 status=200

Parse the supplied raw log text and compute compression savings by encoding. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission PI61XU

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['pool']].append((int(f['used']), int(f['max'])))
    result = {}
    for pool, rows in sorted(d.items()):
        saturated = [used >= maximum for used, maximum in rows]
        episodes = sum(flag and (i == 0 or not saturated[i-1]) for i, flag in enumerate(saturated))
        result[pool] = {'peak_utilization_pct': round(max(u/m for u,m in rows) * 100, 1), 'saturation_samples': sum(saturated), 'episodes': episodes}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

pool=main used=7 max=10
pool=main used=9 max=10
pool=main used=10 max=10
pool=main used=8 max=10
pool=analytics used=4 max=5
pool=analytics used=5 max=5
pool=analytics used=5 max=5

Parse the supplied raw log text and compute connection pool saturation episodes. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 5N2QCX

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    weights = {'express': 2, 'standard': 1}; d = defaultdict(lambda: {'shipments': 0, 'breaches': 0, 'weighted_delay': 0})
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); delay = max(0, int(f['actual']) - int(f['promised'])); r = d[f['carrier']]
        r['shipments'] += 1; r['breaches'] += delay > 0; r['weighted_delay'] += delay * weights[f['tier']]
    result = {c: {'breach_pct': round(v['breaches'] * 100 / v['shipments'], 1), 'weighted_delay_days': v['weighted_delay']} for c, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

carrier=x tier=express promised=2 actual=3
carrier=x tier=standard promised=5 actual=5
carrier=x tier=express promised=2 actual=6
carrier=y tier=express promised=2 actual=2
carrier=y tier=standard promised=5 actual=7

Parse the supplied raw log text and compute shipping SLA breach by carrier and weighted delay. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission K3JYUH

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: {'lags': [], 'missing': 0, 'total': 0})
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); r = d[f['region']]; r['total'] += 1
        if f['replica'] == '-': r['missing'] += 1
        else: r['lags'].append(int(f['replica']) - int(f['primary']))
    result = {region: {'max_lag': max(v['lags'], default=None), 'avg_lag': round(sum(v['lags']) / len(v['lags']), 1) if v['lags'] else None, 'missing_ack_pct': round(v['missing'] * 100 / v['total'], 1)} for region, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

tx=t1 primary=100 replica=108 region=east
tx=t2 primary=120 replica=155 region=east
tx=t3 primary=140 replica=- region=east
tx=t4 primary=200 replica=212 region=west
tx=t5 primary=220 replica=225 region=west

Parse the supplied raw log text and compute replication latency with missing acknowledgements. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission YWF7V4

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    minutes = defaultdict(dict)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); minutes[int(f['minute'])][f['region']] = (int(f['requests']), int(f['errors']))
    result = {}
    for minute, regions in sorted(minutes.items()):
        total = sum(x[0] for x in regions.values()); secondary = regions['secondary']
        result[str(minute)] = {'secondary_traffic_pct': round(secondary[0] * 100 / total, 1), 'secondary_error_pct': round(secondary[1] * 100 / secondary[0], 1)}
    result['shift_points'] = result['3']['secondary_traffic_pct'] - result['1']['secondary_traffic_pct']
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

minute=1 region=primary requests=900 errors=9
minute=1 region=secondary requests=100 errors=1
minute=2 region=primary requests=500 errors=20
minute=2 region=secondary requests=500 errors=5
minute=3 region=primary requests=100 errors=8
minute=3 region=secondary requests=900 errors=9

Parse the supplied raw log text and compute regional failover traffic shift. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission ALLC2Z

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: {'tp': 0, 'fp': 0, 'fn': 0})
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); r = d[f['rule']]
        r['tp'] += f['decision'] == 'block' and f['review'] == 'fraud'; r['fp'] += f['decision'] == 'block' and f['review'] == 'legit'; r['fn'] += f['decision'] == 'allow' and f['review'] == 'fraud'
    result = {rule: {'precision_pct': round(v['tp'] * 100 / (v['tp'] + v['fp']), 1), 'recall_pct': round(v['tp'] * 100 / (v['tp'] + v['fn']), 1)} for rule, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

rule=velocity decision=block review=fraud
rule=velocity decision=block review=legit
rule=velocity decision=allow review=fraud
rule=geo decision=block review=fraud
rule=geo decision=block review=fraud
rule=geo decision=allow review=legit

Parse the supplied raw log text and compute fraud rule precision on reviewed decisions. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission L9M7GZ

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); event = (int(f['term']), f['leader'])
        if not d[f['cluster']] or d[f['cluster']][-1] != event: d[f['cluster']].append(event)
    result = {c: {'elections': len(v) - 1, 'unique_leaders': len({x[1] for x in v}), 'latest_term': v[-1][0]} for c, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

cluster=c1 term=7 leader=n1
cluster=c1 term=8 leader=n2
cluster=c1 term=9 leader=n1
cluster=c2 term=3 leader=n4
cluster=c2 term=3 leader=n4
cluster=c2 term=4 leader=n5

Parse the supplied raw log text and compute leader election instability by cluster. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission SGE1S1

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['user']].append(f['event'])
    locked = [u for u, e in d.items() if 'lock' in e]
    post_lock_attempts = sum(len(e[e.index('lock')+1:]) for e in d.values() if 'lock' in e)
    post_lock_successes = sum('success' in e[e.index('lock')+1:] for e in d.values() if 'lock' in e)
    result = {'locked_users': sorted(locked), 'post_lock_attempts': post_lock_attempts, 'post_lock_successes': post_lock_successes}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

user=a event=fail ip=1.1.1.1
user=a event=fail ip=1.1.1.1
user=a event=lock ip=1.1.1.1
user=a event=fail ip=1.1.1.1
user=b event=fail ip=2.2.2.2
user=b event=success ip=2.2.2.2
user=c event=lock ip=3.3.3.3
user=c event=success ip=3.3.3.3

Parse the supplied raw log text and compute authentication lockout effectiveness. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission P5VV6Y

import json

def transform(input):
    lines = input.strip().splitlines()
    import re
    from collections import defaultdict
    d = defaultdict(lambda: {'total': 0, 'zero': 0, 'lat': []})
    for line in lines:
        m = re.match(r'query="([^"]+)" results=(\d+) latency=(\d+)', line); words = len(m.group(1).split()); bucket = 'short' if words <= 2 else 'long'; r = d[bucket]
        r['total'] += 1; r['zero'] += int(m.group(2)) == 0; r['lat'].append(int(m.group(3)))
    result = {b: {'zero_result_pct': round(v['zero'] * 100 / v['total'], 1), 'avg_latency_ms': round(sum(v['lat']) / len(v['lat']), 1)} for b, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

query="red shoes" results=12 latency=50
query="red hat" results=0 latency=40
query="wireless noise cancelling headphones" results=4 latency=120
query="very specific antique brass fixture" results=0 latency=150
query="pen" results=0 latency=15

Parse the supplied raw log text and compute search zero-result rate by normalized query length bucket. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 42YB73

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: {'play': 0, 'stall': 0, 'sessions': 0, 'bad': 0})
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); r = d[f['device']]; play = int(f['play_ms']); stall = int(f['stall_ms'])
        r['play'] += play; r['stall'] += stall; r['sessions'] += 1; r['bad'] += stall / play >= 0.08
    result = {device: {'stall_ratio_pct': round(v['stall'] * 100 / v['play'], 2), 'bad_sessions': v['bad'], 'sessions': v['sessions']} for device, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

device=mobile session=s1 play_ms=60000 stall_ms=3000
device=mobile session=s2 play_ms=30000 stall_ms=0
device=tv session=s3 play_ms=120000 stall_ms=12000
device=tv session=s4 play_ms=90000 stall_ms=4500

Parse the supplied raw log text and compute video playback stall ratio by device. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission KLNCGG

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    order = {'compile': 0, 'test': 1, 'deploy': 2}; d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['build']].append(f)
    result = {}
    for build, rows in sorted(d.items()):
        rows.sort(key=lambda x: order[x['stage']]); failed = next((r['stage'] for r in rows if r['outcome'] == 'fail'), None)
        result[build] = {'completed_duration': sum(int(r['duration']) for r in rows if r['outcome'] != 'skipped'), 'first_failed_stage': failed, 'success': failed is None}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

build=b1 stage=compile duration=40 outcome=ok
build=b1 stage=test duration=80 outcome=fail
build=b1 stage=deploy duration=0 outcome=skipped
build=b2 stage=compile duration=35 outcome=ok
build=b2 stage=test duration=70 outcome=ok
build=b2 stage=deploy duration=25 outcome=ok

Parse the supplied raw log text and compute build pipeline critical failure stage. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission GTIERN

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: {'hits': 0, 'total': 0, 'saved': 0})
    for line in lines:
        fields = dict(token.split('=', 1) for token in line.split())
        r = fields['region']; hit = fields['cache'] == 'HIT'
        d[r]['total'] += 1; d[r]['hits'] += hit
        if hit: d[r]['saved'] += int(fields['origin_bytes'])
    result = {r: {'hit_ratio': round(v['hits'] / v['total'], 3), 'origin_bytes_saved': v['saved']} for r, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

ts=10:01 region=us-east cache=HIT bytes=8400 origin_bytes=8400
ts=10:02 region=us-east cache=MISS bytes=1200 origin_bytes=1200
ts=10:03 region=eu-west cache=HIT bytes=5100 origin_bytes=5100
ts=10:04 region=eu-west cache=HIT bytes=3200 origin_bytes=3200
ts=10:05 region=eu-west cache=MISS bytes=700 origin_bytes=700
ts=10:06 region=us-east cache=HIT bytes=2500 origin_bytes=2500

Parse the supplied raw log text and compute cache hit ratio and bytes saved per region. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission OZCXMU

import json

def transform(input):
    lines = input.strip().splitlines()
    requests = {}
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split())
        row = requests.setdefault(f['rid'], {'op': f['op'], 'attempts': 0, 'done': False})
        row['attempts'] += 1
        row['done'] = row['done'] or f['outcome'] == 'ok'
    ops = {}
    for row in requests.values():
        if not row['done']: continue
        v = ops.setdefault(row['op'], {'completed': 0, 'attempts': 0})
        v['completed'] += 1; v['attempts'] += row['attempts']
    result = {op: {'completed': v['completed'], 'retry_amplification': round(v['attempts'] / v['completed'], 2)} for op, v in sorted(ops.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

rid=a1 op=read attempt=1 outcome=retry
rid=a1 op=read attempt=2 outcome=ok
rid=b2 op=write attempt=1 outcome=retry
rid=b2 op=write attempt=2 outcome=retry
rid=b2 op=write attempt=3 outcome=ok
rid=c3 op=read attempt=1 outcome=ok
rid=d4 op=write attempt=1 outcome=retry

Parse the supplied raw log text and compute retry amplification by operation, counting only completed request ids. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission RZIEE5

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import Counter
    counts = Counter(line[:16] for line in lines)
    peak = max(counts.values())
    result = {'busiest_minute': min(k for k, v in counts.items() if v == peak), 'requests': peak, 'minutes_observed': len(counts)}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

Parse the supplied raw log text and compute peak requests/minute and busiest minute with tie broken chronologically. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission 161S98

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    series = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split())
        series[f['queue']].append((int(f['depth']), int(f['limit'])))
    result = {}
    for q, values in sorted(series.items()):
        longest = current = 0
        for depth, limit in values:
            current = current + 1 if depth > limit else 0; longest = max(longest, current)
        result[q] = {'net_growth': values[-1][0] - values[0][0], 'longest_breach_streak': longest}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

time=12:00 queue=email depth=40 limit=100
time=12:01 queue=email depth=115 limit=100
time=12:02 queue=email depth=130 limit=100
time=12:03 queue=email depth=90 limit=100
time=12:00 queue=video depth=210 limit=200
time=12:01 queue=video depth=260 limit=200
time=12:02 queue=video depth=310 limit=200

Parse the supplied raw log text and compute queue backlog growth and breach streak. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission N5FVNN

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list); max_uptime = 0
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); max_uptime = max(max_uptime, int(f['uptime_ms']))
        d[f['collector']].append(int(f['pause_ms']))
    result = {k: {'events': len(v), 'max_pause_ms': max(v), 'uptime_share_pct': round(sum(v) * 100 / max_uptime, 3)} for k, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

uptime_ms=10000 collector=young pause_ms=12
uptime_ms=20000 collector=young pause_ms=18
uptime_ms=30000 collector=full pause_ms=240
uptime_ms=40000 collector=young pause_ms=15
uptime_ms=50000 collector=full pause_ms=310

Parse the supplied raw log text and compute gC pause share and maximum pause by collector. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission G5GGYF

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(lambda: {'total': 0, 'classes': defaultdict(int), 'success_bytes': 0})
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); row = d[f['method']]; status = int(f['status'])
        row['total'] += 1; row['classes'][f'{status // 100}xx'] += 1
        if 200 <= status < 300: row['success_bytes'] += int(f['bytes'])
    result = {m: {'class_counts': dict(sorted(v['classes'].items())), 'success_bytes': v['success_bytes']} for m, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

method=GET status=200 bytes=400
method=GET status=304 bytes=0
method=GET status=404 bytes=120
method=POST status=201 bytes=80
method=POST status=400 bytes=90
method=POST status=503 bytes=40

Parse the supplied raw log text and compute status-class distribution and success-weighted bytes. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission NYPZGT

import json

def transform(input):
    lines = input.strip().splitlines()
    import re
    from collections import defaultdict
    d = defaultdict(lambda: {'count': 0, 'hosts': set()})
    for line in lines:
        if 'level=ERROR' not in line: continue
        host = re.search(r'host=(\w+)', line).group(1); message = re.search(r'error="([^"]+)"', line).group(1)
        fingerprint = re.sub(r'\d+', '#', message)
        d[fingerprint]['count'] += 1; d[fingerprint]['hosts'].add(host)
    result = {k: {'count': v['count'], 'hosts': sorted(v['hosts'])} for k, v in sorted(d.items())}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

host=web1 level=ERROR error="Timeout after 120ms" trace=t1
host=web2 level=ERROR error="Timeout after 450ms" trace=t2
host=web1 level=INFO msg="ready"
host=web3 level=ERROR error="KeyError user_184" trace=t3
host=web2 level=ERROR error="KeyError user_992" trace=t4

Parse the supplied raw log text and compute exception fingerprints with affected hosts. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission ZOG9N3

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['pid']].append(int(f['rss_mb']))
    result = {}
    for pid, values in sorted(d.items()):
        deltas = [b - a for a, b in zip(values, values[1:])]
        result[pid] = {'high_water_mb': max(values), 'largest_increase_mb': max(deltas, default=0), 'net_change_mb': values[-1] - values[0]}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

t=1 pid=api rss_mb=220
t=2 pid=worker rss_mb=310
t=3 pid=api rss_mb=245
t=4 pid=worker rss_mb=295
t=5 pid=api rss_mb=330
t=6 pid=worker rss_mb=410

Parse the supplied raw log text and compute memory high-water mark and largest positive delta by process. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.


Submission VX605P

import json

def transform(input):
    lines = input.strip().splitlines()
    from collections import defaultdict
    d = defaultdict(list)
    for line in lines:
        f = dict(x.split('=', 1) for x in line.split()); d[f['tenant']].append((int(f['minute']), int(f['used']), int(f['limit'])))
    result = {}
    for tenant, rows in sorted(d.items()):
        rows.sort(); elapsed = rows[-1][0] - rows[0][0]; rate = (rows[-1][1] - rows[0][1]) / elapsed
        remaining_minutes = (rows[-1][2] - rows[-1][1]) / rate
        result[tenant] = {'current_pct': round(rows[-1][1] * 100 / rows[-1][2], 1), 'projected_exhaustion_minute': round(rows[-1][0] + remaining_minutes, 1)}
    return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)

minute=0 tenant=alpha used=100 limit=1000
minute=10 tenant=alpha used=240 limit=1000
minute=20 tenant=alpha used=410 limit=1000
minute=0 tenant=beta used=50 limit=500
minute=10 tenant=beta used=90 limit=500
minute=20 tenant=beta used=150 limit=500

Parse the supplied raw log text and compute aPI quota consumption and projected exhaustion. Ignore or specially handle the boundary cases encoded in the fixture, preserve deterministic ordering, and return the resulting metrics as a JSON string.