Render Payment Records as Boxed Receipt Cards
StringsAuto-graded · 20 test casesLast updated
Turn a list of parsed payment records into fixed-layout text cards, testing whitespace trimming, exact decimal rounding, and precise string formatting while preserving order.
Render Payment Records as Boxed Receipt Cards
You are given payment records that have already been read from a CSV file. Each record is a dictionary with the string keys "Merchant", "Amount", "Date" and "Status". Turn every record into a four-line text card and return all the cards as a list of strings.
Card layout
For each record, build one string made of four lines joined by a single newline character (\n), with no trailing newline:
---------------------------
| <merchant> $<amount> |
| <date> <status> |
---------------------------
- The first and last lines are each exactly 27 hyphens (
-). - The second line is
|, then the merchant, then one space, then$, then the amount, then|. - The third line is
|, then the date, then one space, then the status, then|.
Rules
- Remove leading and trailing whitespace from all four fields before using them.
- Show the amount with exactly two digits after the decimal point. Treat the amount as an exact decimal number (not a binary float). Pad with zeros when it has fewer than two decimals, and round when it has more, using the default rounding of Python's
decimalmodule (round-half-even) on the exact decimal value. - Place the minus sign of a negative amount after the dollar sign, for example
$-5.00. - Insert the fields exactly as given after trimming. If a merchant or status is empty, the surrounding spaces from the template remain, so you may see two consecutive spaces.
- Keep the output in the same order as the input records, one string per record.
- If there are no records, return an empty list.
- Every amount is a valid numeric string, so no error handling is needed.
Each returned string includes both of its own delimiter lines, so when several cards are printed in sequence, two delimiter lines appear back to back. Do not merge them.
Constraints
0 <= len(rows) <= 10^5- Every record has all four keys, and every value is a string.
- Every
Amount(after trimming) can be parsed bydecimal.Decimal. - Field values contain no newline characters.
Examples
Example 1
Input: render_receipt_cards([{'Merchant': 'Merchant', 'Amount': '10.04', 'Date': '2020-01-01', 'Status': 'pending'}])
Output: ['---------------------------\n| Merchant $10.04 |\n| 2020-01-01 pending |\n---------------------------']
Example 2
Input: render_receipt_cards([{'Merchant': ' Amazon ', 'Amount': ' 25.5 ', 'Date': ' 2023-12-31 ', 'Status': ' completed '}, {'Merchant': 'Coffee Shop', 'Amount': '0.99', 'Date': '2024-01-01', 'Status': 'failed'}])
Output: ['---------------------------\n| Amazon $25.50 |\n| 2023-12-31 completed |\n---------------------------', '---------------------------\n| Coffee Shop $0.99 |\n| 2024-01-01 failed |\n---------------------------']
Hints
Hint 1
Handle each record independently, in input order, and append one finished string per record to the result list.
Hint 2
Strip the whitespace from every field first, then parse the amount with Decimal rather than float so that values like 2.675 are formatted from their exact digits.
Hint 3
A Decimal supports the format spec `:.2f`, which both pads and rounds to two places. Build the card with an f-string, joining the four lines with `\n` and adding no trailing newline.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through the records once, in order. For each record:
- Strip leading and trailing whitespace from the merchant, amount, date and status.
- Convert the trimmed amount string to a
Decimal. - Format that
Decimalwith:.2f, which always yields exactly two fractional digits. - Assemble the card as four lines (border, merchant/amount line, date/status line, border) joined by
\n, and append it to the output list.
An empty input simply produces an empty list.
Why it is correct
- Order: a single forward loop appends one card per record, so output order equals input order.
- Trimming: every field is stripped before it is placed in the template, so stray spaces never appear in the output.
- Two decimals:
Decimalkeeps the exact digits written in the input, so there are no binary floating-point surprises (a float2.675is really slightly below 2.675 and would round differently). The:.2fformat pads values such as25.5to25.50and rounds longer ones using the default context rounding, round-half-even. - Layout: the f-string reproduces the template character for character, including the
$placed directly before the amount (so negatives appear as$-5.00) and the literal spaces, which remain even when a field is empty. - Borders: each card carries its own pair of 27-hyphen borders, so consecutive cards are not merged.
Complexity
- Time: O(N * L), where N is the number of records and L is the typical field length.
- Space: O(N * L) for the returned list. A printing script could stream each card and use only O(L) extra space.
Reference solution
from typing import List, Dict
from decimal import Decimal
def render_receipt_cards(records: List[Dict[str, str]]) -> List[str]:
cards = []
border = "-" * 27
for rec in records:
merchant = rec["Merchant"].strip()
amount = Decimal(rec["Amount"].strip())
date = rec["Date"].strip()
status = rec["Status"].strip()
cards.append(
f"{border}\n| {merchant} ${amount:.2f} |\n| {date} {status} |\n{border}"
)
return cards