Weekly Challenge 401
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. Unless otherwise stated, Copilot (and other AI tools) have NOT been used to generate the solution. It's a great way for us all to practice some coding.
Task 1: Fractional Addition Subtraction
You are given a string representing an expression of fraction addition and subtraction.
Write a script that returns the calculation result of given expression in string format. If final result is an integer, change it to the format of fraction that has a denominator 1.
My solution
Thankfully, Python has the fractions module, while Perl has the Number::Fraction module, written by Dave Cross.
from fractions import Fraction
import re
def fractional_addition_subtraction(expr) -> str:
fractions = re.findall(r"([+-]?\d+/-?\d+)", expr)
total = sum(Fraction(f) for f in fractions)
return str(total) + ("/1" if total.denominator == 1 else "")
The Perl solution follows a similar logic. As it considers the plus in "+2/5" an error, I use a regular express to strip any plus symbols.
use Number::Fraction;
use List::Util 'sum';
sub main ($expr) {
# Extract the fractions from the string
my @fractions = ( $expr =~ /([+-]?\d+\/-?\d+)/g );
# Calculate the sum and return the result
my $total =
sum( map { Number::Fraction->new($_) } map { s/\+//r } @fractions )
->to_string();
$total .= "/1" if index( $total, "/" ) == -1;
say $total;
}
Examples
$ ./ch-1.py "1/2+3/2"
2/1
$ ./ch-1.py "-5/2-3/2"
-4/1
$ ./ch-1.py "5/3-5/3"
0/1
$ ./ch-1.py "10/10-1/10+2/5"
13/10
$ ./ch-1.py "1/6+1/6+1/6"
1/2
Task 2: Reconstruct Digits
You are given a string containing an out-of-order English representation of digits 0-9.
Write a script to return the digits in ascending order.
My solution
The trick to this solution is to identify the unique letter for each number.
- For eight, four, two, six and zero, it is the bolded letter.
- Once they have been excluded, the next set of unique letters are five, three, seven. For three, I chose the letter 'h'.
- Nine and one round out the remaining digits with unique letters.
For my Python solution, I start by defining a dataclass called WordNumber. It stores the number as a word, the unique letter and the number as an integer.
from dataclasses import dataclass
@dataclass
class WordNumber:
word: str
unique_letter: str
number: int
The main function starts by defining a list called words which has WordNumber objects in order listed above.
from collections import Counter
def reconstruct_digits(input_string: str) -> str:
words = [
# First round
WordNumber("eight", "g", 8),
WordNumber("four", "u", 4),
WordNumber("two", "w", 2),
WordNumber("six", "x", 6),
WordNumber("zero", "z", 0),
# Second round
WordNumber("five", "f", 5),
WordNumber("three", "h", 3),
WordNumber("seven", "s", 7),
# Third round
WordNumber("nine", "i", 9),
WordNumber("one", "o", 1),
]
Next I calculate the frequency of each letter with the Counter function and set the solutions variable to an empty list.
letter_freq = Counter(input_string)
solution = []
The next step is to iterate through each WordNumber object in the words list. If the unique letter appears, then I subtract the number of occurrences from the letter_freq dict.
for wn in words:
occurrences = letter_freq[wn.unique_letter]
if occurrences > 0:
solution.extend(str(wn.number) * occurrences)
for letter in wn.word:
letter_freq[letter] -= occurrences
Finally I check that there are no letters left over (a positive frequency) or letters overused (a negative frequency). I then return the string sorted numerically.
if any(letter_freq.values()):
raise ValueError(f"Cannot find solution {letter_freq}")
return "".join(sorted(solution))
The Perl solution follows the same logic. Perl does not have an equivalent of the Counter function, so I created a function called calc_freq to achieve the same results. Instead of a data class, I used a plain old hash to store the word, unique letter and number mapping.
use List::Util 'any';
sub calc_freq ($str) {
my %freq = ();
$freq{$_}++ foreach ( split //, $str );
return %freq;
}
sub main ($str) {
my @words = (
# First round
{ word => "eight", unique_letter => "g", number => 8 },
{ word => "four", unique_letter => "u", number => 4 },
{ word => "two", unique_letter => "w", number => 2 },
{ word => "six", unique_letter => "x", number => 6 },
{ word => "zero", unique_letter => "z", number => 0 },
# Second round
{ word => "five", unique_letter => "f", number => 5 },
{ word => "three", unique_letter => "h", number => 3 },
{ word => "seven", unique_letter => "s", number => 7 },
# Third round
{ word => "nine", unique_letter => "i", number => 9 },
{ word => "one", unique_letter => "o", number => 1 },
);
my %letter_freq = calc_freq($str);
my @solution = ();
foreach my $wn (@words) {
my $word = $wn->{word};
my $unique_letter = $wn->{unique_letter};
my $number = $wn->{number};
my $occurrences = $letter_freq{$unique_letter} // 0;
if ( $occurrences > 0 ) {
push @solution, $number x $occurrences;
foreach my $letter ( split //, $word ) {
$letter_freq{$letter} -= $occurrences;
}
}
}
if ( any { $_ } values(%letter_freq) ) {
my @mismatch = map { "$_ - $letter_freq{$_}" }
grep { $letter_freq{$_} != 0 } sort keys(%letter_freq);
die "Cannot find solution. Mismatched letters: " . join( ", ", @mismatch ) . "\n";
}
say join( "", sort @solution );
}
Examples
$ ./ch-2.py zroezerotwotwotwo
00222
$ ./ch-2.py sveeeinght
78
$ ./ch-2.py onenineninefive
1599
$ ./ch-2.py zeroonetwothreeeightfivesixsevenninefour
0123456789
$ ./ch-2.py ninenineninenine
9999
Top comments (0)