0

I'm trying to write a code which does the following:

  • In the first line, it inputs two space-separated integers, the first presents the length of the list which will be input later, and the second presents an int, called k, which will be needed later on.

  • In the second line, the list I talked about will be input

The expected output is what meets the following criteria:

number of pairs of ( i , j ), where i<j and ar[ i ]+ar[ j ] is divisible by k.

Problem: I don't know why my code ignores some pairs. I have tried it with many test cases, and it fails 90% of them, by outputting less pairs than expected. I know I am pretty close to the right result, I just don't know what I'm not doing right.

For more precise information about what I want my code to do, kindly check this link (No signup or login needed): https://www.hackerrank.com/challenges/divisible-sum-pairs/problem

Here is my code:

#https://www.hackerrank.com/challenges/divisible-sum-pairs/problem

samples_and_k = [int(x) for x in input().split()]
num_list = [int(y) for y in input().split()]
num_list.sort()
counter =0

for i in range(0, samples_and_k[0]-1):
    for j in range(i+1, samples_and_k[0]-1):
        if (num_list[i]+num_list[i+1]) % samples_and_k[1] == 0:
            counter += 1

print(counter)

Here's an example:

Input:

6 3
1 3 2 6 1 2

Expected output: 5

The output of MY code: 3

Liana
  • 314
  • 5
  • 15
  • Please add current and expected output. – Banana Oct 12 '20 at 16:24
  • @Justlearnedit I just did it. – Liana Oct 12 '20 at 17:13
  • In your own words, when you write `for i in range(0, samples_and_k[0]-1):`, what is the reason for doing `-1`? In your own words, if you wrote for example `for i in range(0, 5):`, what values would you expect `i` to take on? Now, did you *check the documentation*? Did you *try it*? Does the way that `range` works agree with your expectation? – Karl Knechtel Oct 12 '20 at 17:25

1 Answers1

1

The problem is that you subtract 1 when using range():

for i in range(0, samples_and_k[0]-1):
    for j in range(i+1, samples_and_k[0]-1):
        if (num_list[i]+num_list[i+1]) % samples_and_k[1] == 0:
            counter += 1

It should be:

for i in range(0, samples_and_k[0]):
    for j in range(i+1, samples_and_k[0]):
        if (num_list[i]+num_list[i+1]) % samples_and_k[1] == 0:
            counter += 1

It's a common misunderstanding when using range(), as range() is implemented somewhat unintuitively (in my opinion). The last number is not included in the range, so list(range(0, 6)) is equal to [0, 1, 2, 3, 4, 5].

Jesper
  • 1,611
  • 13
  • 10