Weekly Challenge 220
This is the second consecutive week I’ve done the task and written the blog
40,000+ feet in the air.
Task 1: Common Characters
You are given a list of words.
Write a script to return the list of common characters (sorted alphabetically) found in every word of the given list.
These are the steps I took.
From a list (array in
words, I create a list called
set_list. Each item is a
Perl) of the lower case letters that occur in each word. In
Pythonthis is achieved using set(word) as strings are an iterable. In
PerlI have a function called
word_to_hashas it seemed like a bit too much to stuff into a single
I take off the first word from the
set_listand assign it to the
I loop through each letter in the first word alphabetically.
I check that the letter is indeed a letter from the English alphabet and that it appears in all the words in the
set_listlist. If it is, I append it to the
Finally, I print items in the letters list.
$ ./ch-1.py Perl Raku Rust
$ ./ch-1.py love live leave
e, l, v
Task 2: Squareful
You are given an array of integers, @ints.
An array is squareful if the sum of every pair of adjacent elements is a perfect square.
Write a script to find all the permutations of the given array that are squareful.
Rather than reinventing some perfectly good wheels, I use the permutation function from
Python's itertools and
Perl's Algorithm::Combinatorics to work through all possible permutations. If we already have a solution with these numbers (e.g. a duplicate number), we skip to the next permutation.
I then have an inner loop from 1 to one less than the number of integers we have. I check that the value at that position and the previous position makes up a perfect square. This is done by calculating the square root of the sum of the two numbers, and checking it is equals to an integer.
$ ./ch-2.py 1 17 8
(1, 8, 17), (17, 8, 1)
$ ./ch-2.py 2 2 2
(2, 2, 2)
If you have any suggestion then please do share with us firstname.lastname@example.org.