DEV Community

Simon Green
Simon Green

Posted on

Common squares

Weekly Challenge 220

This is the second consecutive week I've done the task and written the blog 40,000+ feet in the air.

Challenge, My solution

Task 1: Common Characters

Task

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.

My solution

These are the steps I took.

  1. From a list (array in Perl) of words, I create a list called set_list. Each item is a set (hash in Perl) of the lower case letters that occur in each word. In Python this is achieved using set(word) as strings are an iterable. In Perl I have a function called word_to_hash as it seemed like a bit too much to stuff into a single map statement.
  2. I take off the first word from the set_list and assign it to the first_word variable.
  3. I loop through each letter in the first word alphabetically.
  4. I check that the letter is indeed a letter from the English alphabet and that it appears in all the words in the set_list list. If it is, I append it to the letters list.
  5. Finally, I print items in the letters list.

Examples

$ ./ch-1.py Perl Raku Rust
r

$ ./ch-1.py love live leave
e, l, v
Enter fullscreen mode Exit fullscreen mode

Task 2: Squareful

Task

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.

My solution

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.

Examples

$ ./ch-2.py 1 17 8
(1, 8, 17), (17, 8, 1)

$ ./ch-2.py 2 2 2
(2, 2, 2)
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay