The Weekly Challenge 259

Banking Day Offset & Line Parser: Calendar Date Arithmetic and Regex Syntax Parsing in Perl & Python

Lubos Kolouch March 4, 2024 Challenge Details GitHub Solutions

Task 1: Banking Day Offset

You are given a start date and offset counter. Optionally you also get a bank holiday date list.

Given a number (of days) and a start date, return the date adjusted to take into account non-banking days. In other words: convert a banking day offset to a calendar day offset.

Non-banking days are:

  1. Weekends
  2. Bank holidays

Example 1: Input: $start_date = '2018-06-28', $offset = 3, $bank_holidays = ['2018-07-03'] → Output: '2018-07-04'

Example 2: Input: $start_date = '2018-06-28', $offset = 3 → Output: '2018-07-03'

Method Explanation

The task requires advancing a cursor date by a specified number of banking days. Starting at $start_date, we iteratively add one calendar day at a time:

  1. If the current day falls on a weekend (Saturday or Sunday), we skip it.
  2. If the current day matches any date in the provided bank holiday list (tested in $O(1)$ via a hash/set lookup), we skip it.
  3. Otherwise, the day qualifies as a valid banking day, so we decrement our offset counter.
  4. When the remaining offset reaches zero, the current calendar date is returned in YYYY-MM-DD format.

Perl Solution

use v5.38;
use warnings;
use Time::Piece;
use Time::Seconds qw(ONE_DAY);
use Type::Params -sigs;
use Types::Standard qw(Str Int ArrayRef Optional);

signature_for banking_day_offset => (
    method     => 0,
    positional => [ Str, Int, Optional [ ArrayRef [Str] ] ],
);

sub banking_day_offset ( $start_date, $offset, $bank_holidays = [] ) {
    $bank_holidays //= [];
    my %holidays = map { $_ => 1 } @$bank_holidays;

    my $current = Time::Piece->strptime( "$start_date 12:00:00 UTC", "%Y-%m-%d %H:%M:%S %Z" );

    my $remaining = $offset;
    while ( $remaining > 0 ) {
        $current += ONE_DAY;
        my $ymd  = $current->strftime('%Y-%m-%d');
        my $wday = $current->wday;    # 1 = Sunday, 7 = Saturday

        next if $wday == 1 || $wday == 7;
        next if $holidays{$ymd};

        $remaining--;
    }

    return $current->strftime('%Y-%m-%d');
}

Python Solution

from datetime import datetime, timedelta


def banking_day_offset(
    start_date: str, offset: int, bank_holidays: list[str] | None = None
) -> str:
    """Calculate the target date after advancing a number of banking days."""
    holidays = set(bank_holidays or [])
    current = datetime.strptime(start_date, "%Y-%m-%d").date()

    remaining = offset
    one_day = timedelta(days=1)
    while remaining > 0:
        current += one_day
        # weekday(): Monday is 0 and Sunday is 6
        if current.weekday() >= 5:
            continue
        if current.isoformat() in holidays:
            continue
        remaining -= 1

    return current.isoformat()

Task 2: Line Parser

You are given a line like below:

{%  id   field1="value1"    field2="value2"  field3=42 %}

Where:

  1. "id" can be \w+.
  2. There can be 0 or more field-value pairs.
  3. The names of the fields are \w+.
  4. The values are either numbers (unquoted) or strings (surrounded by double quotes).

The parser should return a structure with name and fields.

It should handle edge cases such as escaped quotes (\") and escaped backslashes (\\), as well as multiline block tags ({% id ... %}\nLINES\n{% endid %}).

Method Explanation

We handle this syntax parsing cleanly with two coordinated regular expressions:

  1. Envelope Extraction: We first match the outer tag block structure. For multiline blocks, a backreference checks that the closing tag matches {% end<name> %} and captures the enclosed text lines.
  2. Attribute Tokenization: Inside the attributes string, we iteratively match key-value pairs using: (\w+)=(?:(-?\d+(?:\.\d+)?)|"((?:\\.|[^"\\])*)") Numeric values are parsed directly into integers or floats, while quoted string values undergo unescaping (converting \\(.) back to the literal character).

Perl Solution

use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);

signature_for parse_line => (
    method     => 0,
    positional => [Str],
);

sub parse_line ($input) {
    my %result;

    my ( $name, $attrs, $text );
    if ( $input =~ m/\A\s*\{%\s*(\w+)(.*?)\s*%\}(?:\r?\n([\s\S]*?)\r?\n\s*\{%\s*end\1\s*%\})?\s*\z/s ) {
        $name  = $1;
        $attrs = $2;
        $text  = $3;
    }
    else {
        ( $name, $attrs ) = ( $input =~ m/\{%\s*(\w+)(.*?)\s*%\}/s );
    }

    return {} unless defined $name;

    $result{name}   = $name;
    $result{fields} = {};

    while ( $attrs =~ m/(\w+)=(?:(-?\d+(?:\.\d+)?)|"((?:\\.|[^"\\])*)")/g ) {
        my $key     = $1;
        my $num_val = $2;
        my $str_val = $3;

        if ( defined $num_val ) {
            $result{fields}{$key} = 0 + $num_val;
        }
        else {
            $str_val =~ s/\\(.)/$1/g;
            $result{fields}{$key} = $str_val;
        }
    }

    if ( defined $text ) {
        $result{text} = $text;
    }

    return \%result;
}

Python Solution

import re
from typing import Any

TAG_PATTERN = re.compile(
    r"^\s*\{%\s*(?P<name>\w+)(?P<attrs>.*?)\s*%\}"
    r"(?:\r?\n(?P<text>[\s\S]*?)\r?\n\s*\{%\s*end(?P=name)\s*%\})?\s*$",
    re.DOTALL,
)

KV_PATTERN = re.compile(r'(\w+)=(?:(-?\d+(?:\.\d+)?)|"((?:\\.|[^"\\])*)")')


def parse_line(line: str) -> dict[str, Any]:
    """Parse a template tag string and extract tag name, fields, and optional text."""
    match = TAG_PATTERN.match(line)
    if not match:
        fallback = re.search(r"\{%\s*(\w+)(.*?)\s*%\}", line, re.DOTALL)
        if not fallback:
            return {}
        name, attrs = fallback.group(1), fallback.group(2)
        text = None
    else:
        name = match.group("name")
        attrs = match.group("attrs")
        text = match.group("text")

    fields: dict[str, Any] = {}
    for kv in KV_PATTERN.finditer(attrs):
        key = kv.group(1)
        if kv.group(2) is not None:
            num_str = kv.group(2)
            fields[key] = float(num_str) if "." in num_str else int(num_str)
        else:
            val_str = kv.group(3)
            fields[key] = re.sub(r"\\(.)", r"\1", val_str)

    result: dict[str, Any] = {"name": name, "fields": fields}
    if text is not None:
        result["text"] = text
    return result