Cohort 4Register

PART 7 · PRACTICE, PREP FLOW AND REVISION

Interview set: Python coding for DE

FreeLesson 73 of 78

Mixed questions in the style of DE coding rounds. Name the pattern before you write anything; it is printed in each approach line.

Q39From events.jsonl, return each user's latest event and the device it came from.DEEASY

Approach: Dedupe, keep latest (P4): one dict keyed by user, replace when the timestamp is newer.

import json

latest = {}
for line in open("events.jsonl"):
    e = json.loads(line)
    cur = latest.get(e["user_id"])
    if cur is None or e["ts"] > cur["ts"]:
        latest[e["user_id"]] = e
for u, e in sorted(latest.items()):
    print(u, e["event"], e["props"]["device"], e["ts"][11:16])

Output

1 view desktop 14:00
2 cart desktop 10:40
3 checkout mobile 11:15
4 view tablet 12:00

Q40For each customer, the longest gap in days between two consecutive orders.DEMEDIUM

Approach: Group by customer (P3), sort dates, compare neighbours with pairwise.

import csv
from collections import defaultdict
from datetime import date
from itertools import pairwise

dates = defaultdict(list)
for r in csv.DictReader(open("orders.csv")):
    d = date.fromisoformat(r["order_date"])
    dates[r["customer_id"]].append(d)

gaps = {c: max((b - a).days for a, b in pairwise(sorted(ds)))
        for c, ds in dates.items() if len(ds) > 1}
print(dict(sorted(gaps.items(), key=lambda kv: -kv[1])))

Output

{'5': 47, '1': 46, '4': 45, '2': 43, '3': 38}

Q41Find every pair of orders whose amounts add up to exactly 2847.00.DEMEDIUM

Approach: Two-sum with a dict: for each amount, look up the complement among amounts seen so far. One pass, O(n).

import csv
from collections import defaultdict
from decimal import Decimal

TARGET = Decimal("2847.00")
seen = defaultdict(list)                 # amount -> order ids
pairs = []
for r in csv.DictReader(open("orders.csv")):
    amt = Decimal(r["amount"])
    for other in seen[TARGET - amt]:
        pairs.append((other, r["order_id"]))
    seen[amt].append(r["order_id"])
print(pairs)

Output

[('103', '105'), ('105', '113')]

Q42Unflatten {"address.city": "Pune", "address.pincode": "411001", "name": "Rohan"} back into nested JSON.DE

HARD

Approach: The reverse of P7: split each key on dots and walk down, creating dicts with setdefault.

def unflatten(flat, sep="."):
    root = {}
    for key, value in flat.items():
        *parents, leaf = key.split(sep)
        node = root
        for p in parents:
            node = node.setdefault(p, {})
        node[leaf] = value
    return root

print(unflatten({"address.city": "Pune",
                 "address.pincode": "411001", "name": "Rohan"}))

Output

{'address': {'city': 'Pune', 'pincode': '411001'}, 'name': 'Rohan'}

Practice before you move on

  1. Solve Q39 to Q42 in the Try it editor before you read the solutions, and say the complexity out loud.
  2. Pick one question and solve it a second way, then check that both give the same output.