Task 1: Five Weekends
Write a script to display months from the year 1900 to 2019 where you find 5 weekends i.e. 5 Friday, 5 Saturday and 5 Sunday.
Logic
A month has exactly 5 weekends (5 Fridays, 5 Saturdays, and 5 Sundays) if and only if it has 31 days and the 1st of the month is a Friday. This means the 29th is Friday, 30th is Saturday, and 31st is Sunday.
Perl Solution
ch-1.pl
use Date::Calc qw/Day_of_Week Days_in_Month/;
sub has_5_weekends {
my ( $year, $month ) = @_;
my $days = Days_in_Month( $year, $month );
my %wdays;
for my $day ( 1 .. $days ) {
$wdays{ Day_of_Week( $year, $month, $day ) }++;
}
return 1 if ( $wdays{5} == 5 ) and ( $wdays{6} == 5 ) and ( $wdays{7} == 5 );
return 0;
}
Python Solution
ch-1.py
import datetime
def has_five_weekends(year: int, month: int) -> bool:
if month not in [1, 3, 5, 7, 8, 10, 12]:
return False
return datetime.date(year, month, 31).weekday() == 6
Task 2: Greedy Text Wrapping
Write a script that can wrap the given paragraph at a specified column using the greedy algorithm.
Logic
The greedy algorithm processes one word at a time, appending it to the current line with a space separator if it fits within the column width limit. If the word plus a space exceeds the remaining space on the line, we output the line and start a new one with the current word.
Perl Solution
ch-2.pl
my ( $width, @words ) = @ARGV;
my $space_left = $width;
for my $word (@words) {
my $len = length($word);
if ( $len + 1 > $space_left ) {
print "\n";
$space_left = $width - $len;
}
else {
$space_left -= $len;
}
print "$word ";
}
Python Solution
ch-2.py
def wrap_text(text: str, column: int = 72) -> str:
if not text:
return ""
words = text.split()
result_lines = []
current_line = []
current_length = 0
for word in words:
word_length = len(word)
if current_length == 0:
current_line.append(word)
current_length = word_length
elif current_length + 1 + word_length <= column:
current_line.append(word)
current_length += 1 + word_length
else:
result_lines.append(" ".join(current_line))
current_line = [word]
current_length = word_length
if current_line:
result_lines.append(" ".join(current_line))
return "\n".join(result_lines)