Home > front end >  loop giving multiple boolean values
loop giving multiple boolean values

Time:10-12

Hi i have this problem

enter image description here

this is my code

for i in range(len(nums)):
for j in range(i 1, len(nums)):
    if nums[i] == nums[j]:
       if abs(i - j) <= k:
           print(True)

i want to add freature or option that if the

if abs(i - j) <= k:
           print(True)

condition does not have any of the values true it just return false once

i tried this but it returns multiple boolean values

nums = [1,2,3,1]

k=3

for i in range(len(nums)):
   for j in range(i 1, len(nums)):
       if nums[i] == nums[j]:
          if abs(i - j) <= k:
              print(True)
   else:
       print(False)
           

CodePudding user response:

Make it a function and use return to break out of the function(both loop)

def distictIndices(nums,k):
   for i in range(len(nums)):
       for j in range(i 1, len(nums)):
           if nums[i] == nums[j] and abs(i - j) <= k:
              reutrn True
   return False

nums = [1,2,3,1]
k=3

print(distictIndices(nums,k))
           

CodePudding user response:

One better (linear) approach that also demonstrates the early return:

def func(nums, k):
    lastseen = {}
    for i, num in enumerate(nums):
        if num in lastseen and i - lastseen[num] <= k:
            return True  # ends function
        lastseen[num] = i
    return False

>>> func([1,2,3,1], 3)
True
>>> func([1,2,3,4,1], 3)
False

Or, using constant extra space:

from collections import deque

def func(nums, k):
    q = deque(maxlen=k)
    for num in nums:
        if num in q:
            return True
        q.append(num)
    return False
  • Related