DEV Community

Simon Green
Simon Green

Posted on

2

Weekly Challenge 188

Challenge, My solution

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

  1. 0 <= i < j < len(list)
  2. list[i] + list[j] is divisible by k.

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

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

Okay