Weekly Challenge 331
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: Last Word
Task
You are given a string.
Write a script to find the length of last word in the given string.
My solution
Sometimes I over complicate things, and this might be one of those cases. We'll start with "what is a word?". Is isn't
a word? Spoiler: it is, and it's not a one letter word.
What if the string is Perl Weekly Challenge!
. In this case, the last word is nine letters long. So for this task, I use a regular expression to look for the last letter, and any combination of letters, hyphens and apostrophes before it. I then return the length of this string or zero if it doesn't exist.
def last_word(input_string: str) -> int:
# Find the last word in the input string and return its length
match = re.search(
r"([a-z'-]*[a-z])[^a-z]*$",
input_string.strip(),
re.IGNORECASE
)
return len(match.group(1)) if match else 0
The Perl code is a little more straight forward.
sub main ($input_string) {
my ($word) = $input_string =~ /([a-z'-]*[a-z])[^a-z]*$/i;
say length($word // '');
}
Examples
$ ./ch-1.py "The Weekly Challenge"
9
$ ./ch-1.py " Hello World "
5
$ ./ch-1.py "Let's begin the fun"
3
Task 2: Buddy Strings
Task
You are given two strings, source
and target
.
Write a script to find out if the given strings are Buddy Strings.
If swapping of a letter in one string make them same as the other then they are Buddy Strings
.
My solution
For this task, I start by checking the strings are of the same length. If they are not, I return False
.
I then use the combinations function from itertools to get all unique combinations of character positions (from 0 to one less than the length of the string), assigned to the variables i
and j
. As strings are immutable in Python, I convert the source
string to a swapped
list, transpose the characters at position i
and j
and check if this is the same a the target
string. If it is, I return True
. If the loop is exhausted, I return False
.
def buddy_strings(source: str, target: str) -> bool:
if len(source) != len(target):
return False
for i, j in combinations(range(len(source)), 2):
swapped = list(source)
swapped[i], swapped[j] = swapped[j], swapped[i]
if ''.join(swapped) == target:
return True
return False
The Perl solution follows the same logic.
Examples
$ ./ch-2.py nice ncie
True
$ ./ch-2.py love love
False
$ ./ch-2.py feed feed
True
Top comments (0)