0

I am working through a challenge and I'm trying to use a nested for loop to solve it. The challenge asks in a given array of integers nums and an integer k, determine whether there are two distinct indices i and j in the array where nums[i] = nums[j] and the absolute difference between i and j is less than or equal to k.

This is my attempt:

def containsCloseNums(nums, k):

    for i in nums:
        for j in nums:
            if (nums[i] == nums[j]) and abs(i-k) <= k:
                return True
            else:
                return False

But this is the error I'm getting:

Traceback (most recent call last):
  main.py3 in the pre-written template, in getUserOutputs
    userOutput = _rundyxlc(testInputs[i])
  main.py3 in the pre-written template, in _rundyxlc
    return containsCloseNums(*_fArgs_zeutcbsrcmec)
  main.py3 in the pre-written template, in containsCloseNums
    if (nums[i] == nums[j]) and abs(i-j) <= k:
IndexError: list index out of range

I don't see a reason for why I'd be out of index because I'm not incrementing beyond the list's length.

I appreciate all help but since this is a challenge, it is more beneficial for me to know why my logic didn't work as opposed to just spitting out an answer.

Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78
  • initially you ask the absolute difference between `i` and `j` is less than or equal to `k`. whereas in the code you have written `abs(i-k) <= k` – Shreyas Moolya Jun 19 '20 at 06:24
  • `i` and `j` are the numbers in the list, not the index.Are you sure you need to use `nums[i]` or `nums[j]`? – jizhihaoSAMA Jun 19 '20 at 06:24

5 Answers5

1

In your code

for i in nums:

"i" is item in this list "nums".

You should change to:

for index_i, value_i in enumerate(nums):

Then "index_i" is the index of item while value_i is the value of the item in list "nums"

By the way I think it should be:

def containsCloseNums(nums, k):

    for i_index, i_value in enumerate(nums):
        for j_index, j_value in enumerate(nums):
            if (i_value == j_value) and abs(i_index-j_index) <= k:
                return True
            else:
                return False
Xu Qiushi
  • 1,111
  • 1
  • 5
  • 10
0

For-loop traverses values in list, not indices.

L = [1, 5, 4]
for i in L:
    print(i)

You will see:

1
5
4

There is enumerate function to get indices. It forms tuples of (indice, value) for each value in list:

for i, val in enumerate(L):
    print(i, val)

output:

0, 1
1, 5
3, 4

Also, your solution has O(n^2) complexity which is not perfect for your task. Think if you coud use sets, dicts, or maybe make some use of sorting your list.

Michail Highkhan
  • 517
  • 6
  • 18
0

You should change your for loops to:

for i in range(len(nums)):
    for j in range(len(nums)):

You are yielding elements instead of indices. There is an element in nums which is greater than the length of nums, that's why the error is throwed.

DecAngel
  • 36
  • 4
0

The problem in your code is that when you do

for i in nums

than i is an item from nums and not an index

so for comparing you can simply do

if i == j

but as you have to use indexes as well to compare with k you can do

for key, value in enumerate(nums):

where key will be the index and value will be the corresponding item.

Jack
  • 222
  • 2
  • 12
0

Right now this code nums[i] and nums[j] will try accessing the ith and jth element in the list. This is what causes the error. if nums = [10, 20] and nums[10] and nums[20] do not exist.

What you want to do is to access the index of each element in the list and use that in the for loop. To access the index you can use enumerate.

I have also edited your code so that it works now.

def containsCloseNums(nums, k):
    for idxi, i in enumerate(nums):
        for idxj, j in enumerate(nums):
            if (nums[idxi] == nums[idxj]) and abs(i-k) <= k:
                return True
            else:
                return False
Sashaank
  • 880
  • 2
  • 20
  • 54