它的来源

如何回答

一位候选人在 2016 年 10 月的 Glassdoor 评价中报告,Palantir 的电话面试要求他们“编写一个解析 CSV 文件的方法”。来源 1Palantir Technologies 前沿部署软件工程师面试问题(存档)发布方Glassdoor(由 Wayback Machine 存档)来源类型候选人的个人记录 Tangible 于 2026 年 8 月发布的带回家作业,要求对一家虚构客户的持仓 CSV 进行数据源校验和可安全重跑的导入,然后给客户的集成负责人写一封跟进邮件。来源 2带回家作业:客户持仓数据源接入发布方Tangible(GitHub 上的 tangiblemarkets)来源类型公司网站 这道题练习的是同样的工作,只是把那些混乱的行明确写了出来。

解析本身是常规操作。真正值得花时间的是客户能否信任你的输出,而这取决于一个你应该在第一分钟就说出的不变量:“输入的每一物理行最终都恰好落在一个地方:干净记录、跳过列表,或附带原因的拒绝报告。我会核对行数加起来等于文件的总行数。”

这是一道实操构建题,不是算法题。课程 What FDE coding rounds test, by the evidence 说明了哪些公司的报告指向这类构建题,哪些指向算法题。

  • 索要样本和字段约定。 哪些列是必填的、输出什么类型、出现哪些日期格式。在设计任何东西之前,先把几行最糟糕的行大声读出来。
  • 使用真正的 CSV 解析器。 Python 的 csv 模块 能按照 RFC 4180 处理带引号的逗号、转义的引号("")以及引号内的换行符。line.split(",") 会在第一个地址字段就出错。字段开头一个多余的引号会开启一个带引号的字段,它一直延伸到下一个引号字符,而后者可能在很多行之后,于是解析器会把中间的每一行都吞进同一个字段(未加引号的字段中间出现的引号会被当作字面字符保留)。跟踪物理行号,并限制一条记录最多可以跨多少行。
  • 区分噪音和坏数据。 空行和重复的表头行属于结构问题:跳过它们并计数。重复的表头意味着有人拼接了多个导出文件,所以要询问各页是否重叠,并检查重复的 ID。一行缺少 ID 或日期无法解析的数据,是客户预期会看到的数据:拒绝它并附上原因和原始文本。
  • 在边缘完成规范化。 日期通过一份明确的已知格式清单统一转换为 ISO 8601。绝不要让解析器去猜测斜杠日期是日在前还是在月前;要么为整个文件定死规则,要么把含糊的行作为歧义拒绝。经过 Excel 的导出还会带来更多问题:Windows-1252 编码的字节无法通过 UTF-8 解码(拒绝该文件并要求提供 UTF-8;绝不要用 errors="replace" 解码)、丢失前导零的 ID(00412 变成了 412,所以要把 ID 当作字符串处理,并询问源系统是否补零),以及以序列天数存储的日期,例如 2024-03-15 存为 45366。
  • 以报告及其附带说明收尾。 先按原因给出计数,然后列出每一条被拒绝的行及其行号。说明谁来读这份报告:客户方能够修复源系统的人。接着说明你会向他们提出什么问题,因为只有他们才能裁定含糊的日期或决定哪条重复记录胜出。

陷阱在于静默的

except: continue

。输出看起来很干净,而缺失的行几周后才被某个核对总数的人发现。

前沿部署软件工程师Palantir 对其 FDE 职位的称呼,内部称为 Delta;OpenAI 和 EY 也发布过 FDSE 职位,各自职责不同。

更多关于前沿部署软件工程师的内容术语表

前沿部署工程师一种软件工程师,在客户的问题和环境中构建并交付生产系统,对客户的结果负责。

更多关于前沿部署工程师的内容

追问

当你的第一个回答摆上桌面后,面试官接下来可能会问的问题。

  • 一个日期可能是日在前或月在前。你如何判断?无法判断时你会怎么做?
  • 文件大到无法全部装入内存。你的代码需要做哪些改变?
  • 下周的导出在中间多了一列。什么会出问题?你如何察觉?
  • 谁会读这份拒绝报告?他们会拿它做什么?

常见的错误回答

  • 对每一行用 try 和 except 包裹并裸 continue,导致坏行无影无踪地消失。
  • 对含糊的日期逐行猜测顺序,而不是为整个文件定死规则或将其拒绝。

两分钟内回答

写出你会大声说出的答案。计时从你说出第一个字开始。

与参考答案对比

参考答案

没有人会在现场面试中把所有这些全部写出来。分三遍写:先写

csv.reader

三个列表和行数校验;然后写日期和金额解析器;最后写引号跨度的上限——先描述它,时间允许才写代码。下面的代码是完成后的版本,供参考。

“输出是三个列表,最后的校验是它们合计覆盖文件的每一物理行。第一个任务是在不让一个坏引号吞掉整个文件的前提下,把行转换为记录。”

import csv
import re
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any

REQUIRED = ("order_id", "order_date", "amount")
DATE_FORMATS = ("%Y-%m-%d", "%Y/%m/%d", "%d %b %Y", "%b %d, %Y")
SLASH = re.compile(r"(\d{1,2})/(\d{1,2})/\d{4}$")
# Lines one record may span before its quote counts as stray
MAX_SPAN = 5


class RowError(ValueError):
    def __init__(self, code: str, detail: str):
        super().__init__(detail)
        self.code = code


@dataclass
class Chunk:
    # Physical line numbers, 1-based, inclusive
    first: int
    last: int
    # The original text, for the report
    raw: str
    # None when the lines could not be parsed
    fields: list[str] | None
    error: RowError | None = None


class _SpanTooLong(Exception):
    pass


def logical_rows(lines: list[str]) -> Iterator[Chunk]:
    """Group physical lines into records by csv's own rules,
    but cap how many lines one record may span."""
    i = first = 0

    def feed():
        nonlocal i
        while i < len(lines):
            if i - first >= MAX_SPAN:
                raise _SpanTooLong
            i += 1
            yield lines[i - 1]

    while i < len(lines):
        first = i
        try:
            for fields in csv.reader(feed(), strict=True):
                raw = "".join(lines[first:i])
                yield Chunk(first + 1, i, raw, fields)
                first = i
        except (_SpanTooLong, csv.Error) as e:
            if isinstance(e, _SpanTooLong):
                err = RowError(
                    "unbalanced quote",
                    f"quote not closed within {MAX_SPAN} lines")
            else:
                err = RowError("parse error", str(e))
            # Reject only the line the record started on,
            # then parse again from the line after it.
            yield Chunk(first + 1, first + 1, lines[first],
                        None, err)
            i = first + 1

“一个多余的引号会让

csv

吞掉直到下一个引号字符之前的所有行,超过 131072 个字符后它会抛出

csv.Error

。所以我自己逐行喂入,并在

MAX_SPAN

行后放弃带引号的片段。

strict=True

会把格式错误的引号变成

csv.Error

而不是静默合并的字段。无论哪种情况,我只拒绝记录开始的那一行,并从下一行重新解析,所以一个坏引号只损失一行,而不是文件的其余部分。未加引号的字段中间出现引号,比如

5" monitor

,会保持为字面字符并正常解析。”

def slash_order(values: Iterable[str]) -> str | None:
    """Settle day/month order for the whole file
    from the dates that prove it."""
    parts = [(int(m[1]), int(m[2]))
             for v in values if (m := SLASH.match(v))]
    # 15/03 fits only day-first; 03/15 only month-first
    day_first = any(a > 12 >= b for a, b in parts)
    month_first = any(b > 12 >= a for a, b in parts)
    if day_first and month_first:
        raise ValueError("the file mixes day-first and "
                         "month-first dates; ask the customer")
    if day_first:
        return "%d/%m/%Y"
    return "%m/%d/%Y" if month_first else None


def parse_date(s: str, slash_fmt: str | None) -> date:
    if SLASH.match(s):
        if slash_fmt is None:
            raise RowError(
                "ambiguous date",
                f"{s!r} could be day-first or month-first")
        formats: tuple[str, ...] = (slash_fmt,)
    else:
        formats = DATE_FORMATS
    for fmt in formats:
        try:
            return datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    raise RowError("bad date", f"unrecognized date {s!r}")


def parse_amount(s: str) -> Decimal:
    # Accounting style: (12.50) is negative
    negative = s.startswith("(") and s.endswith(")")
    num = (s[1:-1] if negative else s)
    num = num.replace("$", "").replace(",", "")
    try:
        d = Decimal(num)
    except InvalidOperation:
        raise RowError("bad amount",
                       f"not a number: {s!r}") from None
    # Decimal accepts "nan" and "Infinity"
    if not d.is_finite():
        raise RowError("bad amount",
                       f"not a finite number: {s!r}")
    return -d if negative else d


def clean(path: str):
    # utf-8-sig drops a byte order mark if there is one
    with open(path, newline="", encoding="utf-8-sig") as f:
        lines = f.readlines()
    chunks = list(logical_rows(lines))
    if not chunks or (head := chunks[0]).fields is None:
        raise ValueError("no readable header")
    body = chunks[1:]
    header = [h.strip().lower() for h in head.fields]
    if missing := set(REQUIRED) - set(header):
        # Stop: this is the wrong file
        raise ValueError(f"header lacks {sorted(missing)}")
    at = header.index("order_date")
    slash_fmt = slash_order(
        c.fields[at].strip() for c in body
        if c.fields and len(c.fields) == len(header))

    records, rejected = [], []
    skipped = [(head.first, head.last, "header")]
    first_seen: dict[str, int] = {}
    for c in body:
        try:
            if c.error or c.fields is None:
                raise c.error or RowError("parse error",
                                          "no fields")
            cells = [x.strip() for x in c.fields]
            if not any(cells):
                skipped.append((c.first, c.last, "blank line"))
                continue
            if [x.lower() for x in cells] == header:
                skipped.append(
                    (c.first, c.last, "repeated header"))
                continue
            if len(cells) != len(header):
                raise RowError(
                    "wrong field count",
                    f"{len(cells)} fields, "
                    f"expected {len(header)}")
            rec: dict[str, Any] = dict(zip(header, cells))
            if empty := [k for k in REQUIRED if not rec[k]]:
                raise RowError("missing field",
                               ", ".join(empty))
            if (oid := rec["order_id"]) in first_seen:
                raise RowError(
                    "duplicate id",
                    f"first seen on line {first_seen[oid]}")
            day = parse_date(rec["order_date"], slash_fmt)
            rec["order_date"] = day.isoformat()
            rec["amount"] = parse_amount(rec["amount"])
            rec["source_lines"] = (c.first, c.last)
            first_seen[oid] = c.first
            records.append(rec)
        except RowError as e:
            rejected.append(
                (c.first, c.last, e.code, str(e), c.raw))

    spans = ([r["source_lines"] for r in records]
             + [r[:2] for r in rejected]
             + [s[:2] for s in skipped])
    covered = sum(b - a + 1 for a, b in spans)
    if covered != len(lines):
        raise RuntimeError(
            f"accounted for {covered} of {len(lines)} lines")
    return records, rejected, skipped

“关于日期:

slash_order

在解析任何行之前先读取整列。第一部分大于 12 证明是“日在前”,第二部分大于 12 证明是“月在前”,但前提是另一部分可能是月份:

31/31/2024

什么也证明不了,所以一个笔误不会让整个文件停止处理;它稍后会作为无效日期被拒绝。两个证明同时出现意味着文件混合了不同来源,所以我会停下来询问。如果没有任何证据能确定,每个斜杠日期都会因歧义被拒绝,报告中的那一行就是提示客户告诉我们的依据。这里做两次遍历没问题,因为文件已经在内存中。”

“中间出现重复的表头说明有人拼接了多个导出文件,而分页导出会有重叠,所以第二次出现的

order_id

会被拒绝,并附上它首次出现的行号。如果客户说后面的导出为准,我就保留后面的行。

Decimal

接受

nan

和

Infinity

,所以金额必须是有限数,而

(12.50)

会被读作负数。去除逗号是假设美式导出;欧洲格式的 1.234,56 会解析错误,所以我会询问源文件使用哪种小数分隔符,而不是猜测。包含 Windows-1252 重音字母或弯引号的文件在

clean

读取时会因解码错误而失败,这正是我想要的:我会要求 UTF-8,而不是猜测编码。”

“唯一的

except

会捕获

RowError

,我的检查会附带原因代码抛出它,所以我代码中的 bug 仍会大声崩溃。最后的检查统计的是物理行数而不是循环次数,所以丢失行的分组 bug 会导致运行失败,而不是交付一个缺行的文件。它抛出

RuntimeError

而不是使用

assert

,因为

python -O

会把后者剥离。报告是客户的数据负责人要读的,它按每行在客户文件中的原样打印每个被拒绝的行,方便他们在源文件中找到:”

from collections import Counter


def report(records, rejected, skipped) -> str:
    out = [f"{len(records)} clean, {len(rejected)} rejected, "
           f"{len(skipped)} skipped"]
    codes = Counter(r[2] for r in rejected)
    for code, n in codes.most_common():
        out.append(f"  {n:>5}  {code}")
    for first, last, code, detail, raw in rejected:
        where = (f"line {first}" if first == last
                 else f"lines {first}-{last}")
        out.append(f"{where}: {code} ({detail})")
        out.append(f"    {raw.rstrip()}")
    return "\n".join(out)

“在一个包含空行、重复表头、重复项、

nan

金额、斜杠日期和多余引号的小样本导出上,它打印:”

8 clean, 4 rejected, 3 skipped
      1  ambiguous date
      1  duplicate id
      1  bad amount
      1  unbalanced quote
line 3: ambiguous date ('03/04/2026' could be day-first or month-first)
    1002,03/04/2026,75.50,"Lee, Ann"
line 7: duplicate id (first seen on line 4)
    1003,2026-03-05,(12.50),Acme
line 8: bad amount (not a finite number: 'nan')
    1004,2026-03-06,nan,Birch
line 9: unbalanced quote (quote not closed within 5 lines)
    1005,2026-03-06,40.00,"Oak ""West

“报告发给负责导出的人,并附上一条简短说明,只问他们能回答的问题。对管理订单系统的 Maria:‘您发送的 4,212 行中,4,190 行已加载。其余 22 行在附带的报告中,每行都标有行号和原因。只有两个问题需要您回答。12 个像

03/04/2026

这样的日期可能是“日在前”或“月在前”:您的系统写的是哪种?另外 7 个订单在导出的两页中都出现了:如果它们不同,应该以后面的为准吗?’”

“至于测试,我会从导出文件中提取最糟糕的真实行作为测试固件:BOM、中间的重复表头、重复 ID、

"Acme, Inc."

带一个带引号的逗号、一个不闭合的引号后跟一段长文件、一个斜杠格式的日期,以及一个金额

nan

。每条测试都断言该行会落入哪个列表及其原因代码。如果文件大到超出内存,

clean

就会变成一个生成器,边流式读取记录边把被拒的行写入文件。重新分组只会向前回看

MAX_SPAN

行,所以只需在一个小缓冲区上运行,而日期顺序我会从前几行的样本中确认或直接询问。”

接下来,在 Pro 中

在 Pro 中,对同一张表的两份导出做差异比对和对客户记录做模糊去重接续了这里的重复检查:找出两次导出之间发生变化的行,以及同一客户的不同拼写。