Weekly Challenge 326
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: Day of the Year
Task
You are given a date in the format YYYY-MM-DD
.
Write a script to find day number of the year that the given date represent.
My solution
There a couple of ways to solve this challenge.
- Manually count the number of days in previous months (between January and the month previous to the month in the input) and the number of days we are looking for. This is somewhat error prone.
- Calculate the difference between the date and January 1st, and add one.
- Use the inbuilt function of the date related modules of the language to compute the day of year.
It's pretty much a no-brainer to use the last option. In Python this returns a 3 digit zero-padded string, so I need to convert it to an integer.
I also check that the input is in the expected format.
def day_of_year(input_date: str) -> int:
if not re.match(r'^\d{4}-\d\d?-\d\d?$', input_date):
raise ValueError("Input date must be in 'YYYY-MM-DD' format")
year, month, day = map(int, input_date.split('-'))
return int((date(year, month, day).strftime('%j')))
Perl has the Date::Calc CPAN module, which has a Date_of_Year function built in.
sub main ($date) {
if ($date !~ /^[0-9]{4}-[0-9][0-9]?-[0-9][0-9]?$/) {
die "Usage: $0 YYYY-MM-DD\n";
}
say Day_of_Year(split /-/, $date);
}
It should also be pointed out that neither handle the situation that happened in 2011 when Samoa skipped December 30th entirely. I do suspect this is why they did it at the end of the calendar year.
Examples
$ ./ch-1.py 2025-02-02
33
$ ./ch-1.py 2025-04-10
100
$ ./ch-1.py 2025-09-07
250
Task 2: Decompressed List
Task
You are given an array of positive integers having even elements.
Write a script to to return the decompress list. To decompress, pick adjacent pair (i, j)
and replace it with j
, i
times.
My solution
This is relatively straight forward. For this task, I have an loop i
that goes from 0 to the length of the list, incrementing by two each iteration. For each iteration I extend the results
list (array in Perl), with value
, count
times.
Using variable like count
and value
instead of i
and j
makes it easier to understand what the variables are intended to be used for.
def decompressed_list(ints: list) -> list:
result = []
for i in range(0, len(ints), 2):
count = ints[i]
value = ints[i + 1]
result.extend([value] * count)
return result
The Perl solution is a transliteration of the Python code.
Examples
$ ./ch-2.py 1 3 2 4
[3, 4, 4]
$ ./ch-2.py 1 1 2 2
[1, 2, 2]
$ ./ch-2.py 3 1 3 2
[1, 1, 1, 2, 2, 2]
Top comments (0)