The Weekly Challenge 029

Brace Expansion & Calling a C Function

Solutions on GitHub

Task 1: Brace Expansion

Write a script to demonstrate brace expansion. For example, the script expands Perl {Daily,Weekly,Monthly,Yearly} Challenge into individual strings.

Example Output

Perl Daily Challenge Perl Weekly Challenge Perl Monthly Challenge Perl Yearly Challenge

Logic

For Perl, we utilize the module Text::Glob::Expand to parse the input pattern and generate expanded permutations. For Python, we write a recursive parser matching brace patterns using regular expressions (\{([^{}]*)\}) and generating expansions sequentially.

Perl Solution

ch-1.pl

use Text::Glob::Expand; sub expand_brace { my $words = shift; my $glob = Text::Glob::Expand->parse($words); my $permutations = $glob->explode_format(""); return $permutations; }

Python Solution

ch-1.py

def expand_braces(text: str) -> list[str]: match = BRACE_RE.search(text) if match is None: return [text] before = text[: match.start()] choices = match.group(1).split(",") after = text[match.end() :] result: list[str] = [] for choice in choices: result.extend(expand_braces(before + choice + after)) return result

Task 2: Calling a C Function

Write a script to demonstrate calling a standard C function directly from Perl and Python.

Logic

Logic

In Perl, we can write and execute C inline code using the Inline::C library. In Python, we load standard libraries using the ctypes module and map functions like strlen from the C standard library directly to Python functions.

Perl Solution

ch-2.pl

use Inline C => << 'END'; void print_c() { printf("test"); } END print_c;

Python Solution

ch-2.py

import ctypes def load_c_library() -> ctypes.CDLL: libc = ctypes.CDLL(None) libc.strlen.argtypes = [ctypes.c_char_p] libc.strlen.restype = ctypes.c_size_t return libc def c_strlen(text: str) -> int: libc = load_c_library() return int(libc.strlen(text.encode("utf-8")))