DEV Community

Simon Green
Simon Green

Posted on

The maximum divisible

Weekly Challenge 262

Happy 6th birthday Team PWC!

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: Max Positive Negative

Task

You are given an array of integers, @ints.

Write a script to return the maximum number of either positive or negative integers in the given array.

My solution

A nice simple task to start this week. Count the number of negative integers, and store that as neg_count. I then count the number of positive integers, storing that as pos_count. Finally I return the maximum of those two values.

def max_type(ints: list) -> int:
    neg_count = pos_count = 0
    for i in ints:
        if i < 0:
            neg_count += 1
        elif i > 0:
            pos_count += 1

    return max(neg_count, pos_count)
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py -3 1 2 -1 3 -2 4
4

$ ./ch-1.py -1 -2 -3 1
3

$ ./ch-1.py 1 2
2
Enter fullscreen mode Exit fullscreen mode

Task 2: Count Equal Divisible

Task

You are given an array of integers, @ints and an integer $k.

Write a script to return the number of pairs (i, j) where

  • 0 <= i < j < size of @ints
  • ints[i] == ints[j]
  • i × j is divisible by k

My solution

In Python, this can be done in a single command, due to it's list comprehension feature. I have an outer loop i from 0 to two less than the length of the array (the second last position), and an inner loop j from i + 1 to one less than the length of array. For each value of i and j I check that the numbers at the position i and j are equal and that i × j is divisible by k.

def equal_div(ints: list, k: int) -> int:
    count = sum(1
                for i in range(len(ints)-1)
                for j in range(i+1, len(ints))
                if ints[i] == ints[j] and i * j % k == 0
                )

    return count
Enter fullscreen mode Exit fullscreen mode

If the lists were larger, I could optimize the computation by splitting the lists based the value. However, it is assumed that the number of items in ints is relatively small.

Examples

$ ./ch-2.py 3 1 2 2 2 1 3 2
4

$ ./ch-2.py 1 2 3 2
0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)