Task 1: Divisible Pairs
Task
You are given list of integers @list
of size $n
and divisor $k
.
Write a script to find out count of pairs in the given list that satisfies the following rules.
The pair (i, j) is eligible if and only if
0 <= i < j < len(list)
-
list[i] + list[j]
is divisible byk
.
My solution
This seems relatively straight forward. As list is a reserved word in Python, I used nums
for the Python version. For this I start with the value of matches
as zero. I take the last number off the input using the pop function, and store that as k
.
For the i
iterator, I start at zero and finish at the second last number. For the j
iterator, I start at i+1
and end at the last position. I increase matches
if the numbers at the relevant position is divisible by k
. And then print the result.
I know some clever eggs are going to use map, which is probably going to be a little faster. In the case of these challenges, some times I'll make code easier to understand over speed.
Examples
$ ./ch-1.py 4 5 1 6 2
2
$ ./ch-1.py 1 2 3 4 2
2
$ ./ch-1.py 1 3 4 5 3
2
$ ./ch-1.py 5 1 2 3 4
2
$ ./ch-1.py 7 2 4 5 4
1
Task 2: Total Zero
Task
You are given two positive integers $x
and $y
.
Write a script to find out the number of operations needed to make both ZERO. Each operation is made up either of the followings:
-
$x = $x - $y
if$x >= $y
-
$y = $y - $x
if$y >= $x
(using the original value of$x
)
My solution
The hardest part of this challenge was understanding what was required. In particular 'using the original value of $x'. I took this to mean the value of $x that was provided, but it became clear that it meant $x at this particular iteration.
With that out of the way, the code become straight forward. I have a value called count
starting at 0, and a loop that continues until both x
and y
is 0.
For each iteration, I add one to the count
value. If x
is greater, I take y
of it, likewise if y
is grexater I take x
off it. If x
and y
are the same, I set them both to zero, as we know that taking the other value from each would result in this.
Examples
$ ./ch-2.py 5 4
5
$ ./ch-2.py 4 6
3
$ ./ch-2.py 2 5
4
$ ./ch-2.py 3 1
3
$ ./ch-2.py 7 4
5
Top comments (0)