Weekly Challenge 360
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: Text Justifier
Task
You are given a string and a width.
Write a script to return the string that centers the text within that width using asterisks * as padding.
My solution
If the input_string length is larger or equal to the width variable, I simply return the original string, as no padding is required.
I then create a variable called asterisks which is half the difference in length. Finally, I use the floor and ceil function to add the required number of asterisks. Doing this way ensure that if there is an odd number of asterisks required, the right side will have the additional asterisk.
from math import ceil, floor
def text_justifier(input_string: str, width: int) -> str:
string_len = len(input_string)
if string_len >= width:
return input_string
asterisks = (width-string_len) / 2
output_string = "*" * floor(asterisks) + input_string + "*" * ceil(asterisks)
return output_string
The Perl solution follows the same logic. The floor and ceil functions come from the POSIX module.
Examples
$ ./ch-1.py Hi 5
*Hi**
$ ./ch-1.py Code 10
***Code***
$ ./ch-1.py Hello 9
**Hello**
$ ./ch-1.py Perl 4
Perl
$ ./ch-1.py A 7
***A***
$ ./ch-1.py "" 5
*****
Task 2: Word Sorter
Task
You are give a sentence. Write a script to order words in the given sentence alphabetically but keeps the words themselves unchanged.
My solution
This can be achieved as a one-liner in both Python and Perl.
The Python solution is
def word_sorter(sentence: str) -> str:
return " ".join(sorted(sentence.split(), key=lambda x: x.lower()))
Breaking this down:
-
sentence.split()will split the original sentence into a list of strings. The separator is one or more white space characters. -
sorted(..., key=lambda x: x.lower())will sort the list alphabetically in a case insensitive manner. -
join(" ", ...)will turn the list into a string, separated by a single space.
The Perl solution uses the same logic, but a slightly different syntax.
sub main ($str) {
say join( " ", sort { lc($a) cmp lc($b) } split /\s+/, $str );
}
Examples
$ ./ch-2.py "The quick brown fox"
brown fox quick The
$ ./ch-2.py "Hello World! How are you?"
are Hello How World! you?
$ ./ch-2.py "Hello"
Hello
$ ./ch-2.py "Hello, World! How are you?"
are Hello, How World! you?
$ ./ch-2.py "I have 2 apples and 3 bananas!"
2 3 and apples bananas! have I
Top comments (0)