Search code examples
pythonalgorithmfor-looprangeincrement

range() function not producing expected result


I have a program:

def num4():
    def tp(nums):
        res = []
        for i in  range(len(nums)):
            for j in  range(i+1,len(nums)):
                res.append(nums[i] + nums[j])
        return  res

    nums = [ 1, 5, 7, -2 ]
    print(tp(nums)

I walked through what it does, marked it up, and expected it to produce this result:

def tp(nums):
    res = []

    for i in  range(len(nums)):
    # startvalue = len(nums), stopvalue = 0, inc = 1

        for j in  range(i+1,len(nums)):
    # startvalue = i + 1, stopvalue = len(nums) - 1, inc = 1

            res.append(nums[i] + nums[j])

    return  res

    nums = [ 1, 5, 7, -2 ]
    print(tp(nums))

for i in range(4):
# range(4) = 1, 2, 3, 4

    i = 1:
    for j in range(i + 1, 4):
    # range(1 + 1, 4) = 2, 3
    res = [nums[1] + nums[2]] = 5 + 7 = 12
    res = [nums[1] + nums[3]] = 5 - 2 = 3

    i = 2:
    for j in range(i + 1, 4):
    # range(2+1, 4) = 3
    res = [nums[2] + nums[3]] = 7 - 2 = 5

    i = 3:
    for j in range(i + 1, 4):
    # range(3+1, 4) = n/a
    res = [nums[3] + n/a] = -2

    i = 4
    for j in range(i + 1, 4):
    # range(4+1, 4) = n/a
    res = [nums[4] + n/a] = 1

PREDICTED OUTPUT: res = [ 12, 3, 5, -2, 1 ]

Instead, when I did this in a Python interactive session:

from ExamCheck1 import num4
num4()

It produced this output: [6, 8, -1, 12, 3, 5]

I got the 12, 3, 5 right, but where did the 6, 8, -1 part come from? I'm very lost and confused.


Solution

  • The values you expect from the range function are a bit flawed. There are three possible ways you can use the range function:

    1. range(x): Generates an array with values from 0 ~ x-1. So range(4) = [0,1,2,3]
    2. range(x,y): Generates values from x ~ y-1. So range(1,4) = [1,2,3]
    3. range(x,y,z): Generating values from x~y-1 in steps of z. So range(1,10,2) = [1, 3, 5, 7, 9]

    Walk through your code with these values of range and it will make sense to you.