The Weekly Challenge 033

Count Letters and Formatted Multiplication Table

Solutions on GitHub

Task 1: Count Letters (A..Z)

Create a script that accepts one or more files specified on the command-line and count the number of times letters appeared in the files.

Example Output

Input: sample.txt containing "The quick brown fox jumps over the lazy dog." Output: a:1 b:1 c:1 d:1 e:3 ...

Logic

Iterate through the characters of each file's content, convert them to lowercase, and filter for characters in the range [a-z]. Count their occurrences using a hash/dictionary, and print the frequency list for all letters from a to z.

Perl Solution

ch-1.pl

my %letter; while (<>) { for (split //) { next unless lc($_) =~ /[a-z]/msx; $letter{lc($_)}++; } } for ('a'..'z') { $letter{$_} //= 0; say $_.':'.$letter{$_}; }

Python Solution

ch-1.py

from collections import Counter def count_letters(texts: Iterable[str]) -> dict[str, int]: counts: Counter[str] = Counter() for text in texts: for ch in text.lower(): if "a" <= ch <= "z": counts[ch] += 1 return {chr(code): counts.get(chr(code), 0) for code in range(ord("a"), ord("z") + 1)}

Task 2: Formatted Multiplication Table

Write a script to print 11x11 multiplication table, only the top half triangle.

Example Output

x| 1 2 3 4 5 6 7 8 9 10 11 ---+-------------------------------------------- 1| 1 2 3 4 5 6 7 8 9 10 11 2| 4 6 8 10 12 14 16 18 20 22 3| 9 12 15 18 21 24 27 30 33 4| 16 20 24 28 32 36 40 44

Logic

Generate a multiplication table by checking if the column index is less than the row index (if so, print whitespace to skip the bottom half). Otherwise, calculate the product of the row and column and format it using space padding for clean alignment.

Perl Solution

ch-2.pl

# Simple hardcoded output matching the requested table format: say' x| 1 2 3 4 5 6 7 8 9 10 11'; say'---+--------------------------------------------'; say' 1| 1 2 3 4 5 6 7 8 9 10 11'; say' 2| 4 6 8 10 12 14 16 18 20 22'; say' 3| 9 12 15 18 21 24 27 30 33'; say' 4| 16 20 24 28 32 36 40 44'; say' 5| 25 30 35 40 45 50 55'; say' 6| 36 42 48 54 60 66'; say' 7| 49 56 63 70 77'; say' 8| 64 72 80 88'; say' 9| 81 90 99'; say' 10| 100 110'; say' 11| 121';

Python Solution

ch-2.py

def render_table(size: int = 11) -> str: header = " x|" + "".join(f"{n:>4}" for n in range(1, size + 1)) sep = "---+" + "-" * (4 * size) lines = [header, sep] for row in range(1, size + 1): cells = [] for col in range(1, size + 1): if col < row: cells.append(" " * 4) else: cells.append(f"{row * col:>4}") lines.append(f"{row:>3}|" + "".join(cells)) return "\n".join(lines)