DEV Community

Simon Green
Simon Green

Posted on

Triplets and Sorting

Weekly Challenge 241

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.

Challenge, My solutions

Task 1: Arithmetic Triplets

Submitted by: Mohammad S Anwar

You are given an array (3 or more members) of integers in increasing order and a positive integer.

Write a script to find out the number of unique Arithmetic Triplets satisfying the following rules:

  1. i < j < k
  2. nums[j] - nums[i] == diff
  3. nums[k] - nums[j] == diff

My solution

This seems pretty straight forward. For any given number in the list, check if that number + diff and that number + diff × 2 are also in the list. If it is, increment the count variable by one.

for i in ints:
    if i+diff in ints and i+diff*2 in ints:
        count += 1
Enter fullscreen mode Exit fullscreen mode

My Perl solution follows the same logic. As Perl does not have an in-built in function, I first create a hash of the numbers. I could have use List::Util's any function, but that gets a bit messy for my liking. YMMV :)

my %ints = map { $_, 1 } @ints;
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 0 1 4 6 7 10 3
2

$ ./ch-1.py 4 5 6 7 8 9 2
2
Enter fullscreen mode Exit fullscreen mode

Task 2: Prime Order

Task

You are given an array of unique positive integers greater than 2.

Write a script to sort them in ascending order of the count of their prime factors, tie-breaking by ascending value.

My solution

This is very similar to the second task three weeks ago, and the second task from challenge 233. Read my original post about how I do the sorting in this task.

To determine the prime factors of a number, I created a function all count_primes. It has two variables, primes is the number of primes while count is the (possibly prime) divisor we are looking at.

I iterate until the input is 1. If the number is divisible by count, then I add one to prime. If it is not, I add one to count and loop again.

primes = 0
count = 2

while i > 1:
    if i % count == 0:
        primes += 1
        i = i / count
    else:
        count += 1

return primes
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py 11 8 27 4
(11, 4, 8, 27)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)