'What is the difference between the following seemingly same two python functions?

I'm new to data structures and algorithms, so I was kind of confused when I was writing a function to find a pair of numbers from two arrays (one from each array) that the absolute value of difference of the two numbers is the smallest. My first draft was version 2, but it did not pass all the tests. However, when I assigned arrayOne[i] to firstNum and arrayTwo[j] to secondNum, it passed all the test cases. Could anyone explain what happened exactly? Since I thought these two versions were exactly the same.

Version 1:

def smallestDifference(arrayOne, arrayTwo):
    arrayOne.sort()
    arrayTwo.sort()
    i = j = 0
    smallest = float('inf')
    current = float('inf')
    smallestPair = []

    while i < len(arrayOne) and j < len(arrayTwo):
        firstNum = arrayOne[i]
        secondNum = arrayTwo[j]
        if firstNum < secondNum:
            current = abs(firstNum - secondNum)
            i += 1
        elif firstNum > secondNum:
            current = abs(firstNum - secondNum)
            j += 1
        else:
            return [firstNum, secondNum]
        if current < smallest:
            smallest = current
            smallestPair = [firstNum, secondNum]
    return smallestPair

Version 2:

def smallestDifference(arrayOne, arrayTwo):
    arrayOne.sort()
    arrayTwo.sort()
    i = j = 0
    smallest = float('inf')
    current = float('inf')
    smallestPair = []

    while i < len(arrayOne) and j < len(arrayTwo):
        if arrayOne[i] < arrayTwo[j]:
            current = abs(arrayOne[i] - arrayTwo[j])
            i += 1
        elif arrayOne[i] > arrayTwo[j]:
            current = abs(arrayOne[i] - arrayTwo[j])
            j += 1
        else:
            return [arrayOne[i], arrayTwo[j]]
        if current < smallest:
            smallest = current
            smallestPair = [arrayOne[i], arrayTwo[j]]
    return smallestPair


Solution 1:[1]

In version 1, you are indexing arrayOne and arrayTwo for your first if,elif,else statement which is fine, however you change the value of i/j so if the program hits the if current < smallest part of the algorithm, the value of i/j has changed.

For example lets say i and j where both 0 and arrayOne[0] < arraytwo[0], you would increment i and continue on. Once you get to the bottom and you want to delclare smallestPair, you are now setting the value to [arrayOne[1], arrayTwo[0] rather than [arrayOne[0], arrayTwo[0] because you incremented i.

Version one declares the two variables and uses those declarations for the WHOLE function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wumbo