Weekly Challenge 332
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. It's a great way for us all to practice some coding.
Task 1: Binary Date
Task
You are given a date in the format YYYY-MM-DD
.
Write a script to convert it into binary date.
My solution
For this task, I do these steps.
- Split the date from
input_string
on hyphens into thedate_parts
list (array in Perl). - Convert each part from an integer to binary value. This is stored as
binary_parts
. - Join the
binary_parts
list in a single string separated by hyphens.
Python
def binary_date(input_string: str) -> str:
date_parts = input_string.split('-')
binary_parts = [bin(int(part))[2:] for part in date_parts]
return '-'.join(binary_parts)
Perl
sub main ($input_string) {
my @date_parts = split /-/, $input_string;
my @binary_parts = map { sprintf( "%b", $_ ) } @date_parts;
say join( '-', @binary_parts );
}
Examples
$ ./ch-1.py 2025-07-26
11111101001-111-11010
$ ./ch-1.py 2000-02-02
11111010000-10-10
$ ./ch-1.py 2024-12-31
11111101000-1100-11111
Task 2: Odd Letters
Task
You are given a string.
Write a script to find out if each letter in the given string appeared odd number of times.
My solution
Python has the Counter method that will convert an iterable (like a string) and create a dictionary with the frequency of each letter. I then use the all function to check if all letters occur an odd number of times.
def odd_letters(input_string: str) -> bool:
freq = Counter(input_string)
return all(count % 2 == 1 for count in freq.values())
Perl doesn't have an equivalent of the Counter function, so I do that part by hand.
sub main ($input_string) {
my %freq = ();
for my $char ( split //, $input_string ) {
$freq{$char}++;
}
my $all_odd = all { $_ % 2 == 1 } values %freq;
say $all_odd ? "true" : "false";
}
Examples
$ ./ch-2.py weekly
False
$ ./ch-2.py perl
True
$ ./ch-2.py challenge
False
Top comments (0)