Weekly Challenge 362
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: Echo Chamber
Task
You are given a string containing lowercase letters.
Write a script to transform the string based on the index position of each character (starting from 0). For each character at position i, repeat it i + 1 times.
My solution
Both of this weeks solutions are a one-liner in Python. For this task, the function is
def echo_chamber(input_string: str) -> str:
return ''.join(
letter * pos
for pos, letter in enumerate(input_string, start=1)
)
Multiplying a string (letter) by an integer (pos) will repeat the string the specified number of times.
The enumerate function in Python returns the index and the value from a iterator (in this case characters in a string). A little-used feature of this function is the start parameter which will start counting at a value other than the default of zero.
The Perl solution is a little more verbose, as I build the string a letter at a time. By using ++$cnt, the value is incremented before it is evaluated (as opposed to $cnt++). The x operator will repeat the string the required number of times.
sub main ($input_string) {
my $output_string = '';
my $cnt = 0;
foreach my $letter ( split //, $input_string ) {
$output_string .= $letter x ++$cnt;
}
say $output_string;
}
Examples
$ ./ch-1.py abca
abbcccaaaa
$ ./ch-1.py xyz
xyyzzz
$ ./ch-1.py code
coodddeeee
$ ./ch-1.py hello
heelllllllooooo
$ ./ch-1.py a
a
Task 2: Spellbound Sorting
Task
You are given an array of integers.
Write a script to return them in alphabetical order, in any language of your choosing. Default language is English.
My solution
Thankfully the perfectly round wheels have already been invented for converting integers into strings. To make this task a little easier on myself, I'm only using English.
Python has the num2words module. The sorted function has the key parameter to determine how the integers should be sorted.
from num2words import num2words
def spellbound_sorting(ints: list[int]) -> list[int]:
return sorted(ints, key=num2words)
Perl has the Lingua::EN::Numbers module. The sort function in Perl also has built in features to determine the sort order.
use Lingua::EN::Numbers 'num2en';
sub main (@ints) {
my @sorted_ints = sort { num2en($a) cmp num2en($b) } @ints;
say join( ", ", @sorted_ints );
}
Examples
$ ./ch-2.py 6 7 8 9 10
[8, 9, 7, 6, 10]
$ ./ch-2.py -3 0 1000 99
[-3, 99, 1000, 0]
$ ./ch-2.py 1 2 3 4 5
[5, 4, 1, 3, 2]
$ ./ch-2.py 0 -1 -2 -3 -4
[-4, -1, -3, -2, 0]
$ ./ch-2.py 100 101 102
[100, 101, 102]
Top comments (0)