user15552191
user15552191

Reputation:

why is my for loop within a for loop causing issues?

I have the following code, where we have two lists of unique integers, nums1 and nums2; where nums1 is a subset of nums2. We want compare each element of nums1 with nums2, and append the 'output_stack' with the next biggest integer in nums2.

For example: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

def nextGreaterElement(nums1, nums2):
    nums1 = sorted(nums1)
    nums2 = sorted(nums2)


    output_stack = []
    for i in range(len(nums1)):
        for j in range(len(nums2)):
            if nums1[i] ==nums2[-1]:
                output_stack.append(-1)

            elif nums1[i] == max(nums2):
                output_stack.append(-1)

            elif nums1[i] == nums2[j]:
                output_stack.append(nums2[j+1])

            else:
                output_stack.append(-1)

        return(print(output_stack))

nextGreaterElement([2,4],[1,2,3,4])

The code above returns the wrong output [-1,3,-1,-1] and I know why- it is because I am iterating over all of nums2 with j, but this is the only way I know how to do it. Is there a way to amend the existing code.

My trouble is that if I took away the second 'for' loop, I struggled to find a way to reference the 'next' index in nums2; is there a way to do this without using a 'for' loop?

Upvotes: 2

Views: 133

Answers (2)

Tom McLean
Tom McLean

Reputation: 6305

I'm not sure why your code wasnt working, but I thought I would give a shot of making my own version. Could be cleaned up a bit but seems to be working for your two examples

def nextGreaterElement(nums1, nums2):
    results = []
    for i in range(len(nums1)):
        greater_numbers = nums2[i:][np.where(nums2[i:] > nums1[i])]
        if len(greater_numbers) > 0:
            results += [greater_numbers[0]]
        else:
            results += [-1]
    return np.array(results)
        

list1 = np.array([4, 1, 2])
list2 = np.array([1, 3, 4, 2])

nextGreater = nextGreaterElement(list1, list2)
print(nextGreater)

Here is how the code works:

First, we will need to loop through the numbers in the first list:

for i in range(len(nums1)):

Then, we want to slice the second list at the same index as the first point. I will do this example with nums1 as [4, 1, 2] and nums2 as [1, 3, 4, 2], looking at '1' in nums1.

nums2[i:]

(value 1 is at index 1, nums2[1:] returns array([3, 4, 2]))

find the position of the numbers within the sliced list that are greater than the number we are looking at

np.where(nums2[i:] > nums1[i])

(at i=1, this returns the index positions (array([0, 1, 2], dtype=int64),) as all of the numbers in [3,4,2] are greater than 1)

Then index slice the nums2 list to return the actual values

greater_numbers = nums2[i:][np.where(nums2[i:] > nums1[i])]

returns array([3, 4, 2])

We need to check that the array has any values in it, before taking the first number in the list

if len(greater_numbers) > 0:
    results += [greater_numbers[0]]
else:
    results += [-1]

Return the results as a numpy array for consistancy. I appended the results to a list originally as they are mutable. I am not sure what the best practice is for this, but its the way I do it!

return np.array(results)

Upvotes: 0

EyaS
EyaS

Reputation: 596

try to exit from the second for loop inside the else-if structure:

    for i in range(len(nums1)):
      for j in range(len(nums2)):
        if nums1[i] ==nums2[-1]:
            output_stack.append(-1)
            break
        elif nums1[i] == max(nums2):
            output_stack.append(-1)
            break
        elif nums1[i] == nums2[j]:
            output_stack.append(nums2[j+1])
            break
        else:
            output_stack.append(-1)
            break
    return(print(output_stack))

Upvotes: 1

Related Questions