InterviewDB Question

Card Parsing: Parse and Validate a Structured Card Data Format

Question Details

Problem

You receive card data as a raw string in the following format:

<name>|<suit>|<value>

where suit is one of H, D, C, S and value is an integer 1-13 (1=Ace, 11=Jack, 12=Queen, 13=King).

Parse a list of such strings and return a list of card dicts. Reject (skip) any malformed entries and return them separately.

python
from typing import List, Tuple, Dict

def parse_cards(
    raw: List[str]
) -> Tuple[List[Dict], List[str]]:

**return** (valid_cards, rejected_strings)
    # valid card: {"name": str, "suit": str, "value": int}
    pass

Example:


**Input**: ["Ace|H|1", "King|S|13", "Joker|X|0", "Queen|D|12", "bad_data"]

Valid:    [{"name":"Ace","suit":"H","value":1}, {"name":"King","suit":"S","value":13},
           {"name":"Queen","suit":"D","value":12}]
Rejected: ["Joker|X|0", "bad_data"]

Follow-ups

  1. How would you extend this to support a multi-deck scenario where duplicate cards are valid?
  2. What error reporting format would be most useful for a downstream API consumer?
  3. How would you make the parser configurable to support different card game variants with different valid suits or value ranges?
  4. How would you write property-based tests for this parser?

Full Details

Problem

You receive card data as a raw string in the following format:

<name>|<suit>|<value>

where suit is one of H, D, C, S and value is an integer 1-13 (1=Ace, 11=Jack, 12=Queen, 13=King).

Parse a list of such strings and return a list of card dicts. Reject (skip) any malformed entries and return them separately.

python
from typing import List, Tuple, Dict

def parse_cards(
    raw: List[str]
) -> Tuple[List[Dict], List[str]]:

**return** (valid_cards, rejected_strings)
    # valid card: {"name": str, "suit": str, "value": int}
    pass

Example:


**Input**: ["Ace|H|1", "King|S|13", "Joker|X|0", "Queen|D|12", "bad_data"]

Valid:    [{"name":"Ace","suit":"H","value":1}, {"name":"King","suit":"S","value":13},
           {"name":"Queen","suit":"D","value":12}]
Rejected: ["Joker|X|0", "bad_data"]

Follow-ups

  1. How would you extend this to support a multi-deck scenario where duplicate cards are valid?
  2. What error reporting format would be most useful for a downstream API consumer?
  3. How would you make the parser configurable to support different card game variants with different valid suits or value ranges?
  4. How would you write property-based tests for this parser?
Free preview. Unlock all questions →

Topics

Coding Phone