DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge: I sent my date a letter

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.

Challenge, My solutions

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.

  1. Split the date from input_string on hyphens into the date_parts list (array in Perl).
  2. Convert each part from an integer to binary value. This is stored as binary_parts.
  3. 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)
Enter fullscreen mode Exit fullscreen mode

Perl

sub main ($input_string) {
    my @date_parts = split /-/, $input_string;
    my @binary_parts = map { sprintf( "%b", $_ ) } @date_parts;
    say join( '-', @binary_parts );
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py weekly
False

$ ./ch-2.py perl
True

$ ./ch-2.py challenge
False
Enter fullscreen mode Exit fullscreen mode

Top comments (0)