Home > Net >  Python Won't Update a Variable Outside of My For Loop
Python Won't Update a Variable Outside of My For Loop

Time:08-08

I'm following another tutorial on CodeSignal, and this time it wants me to figure out what the missing numbers are in a sequence from smallest to largest in a list. I figured out how to sort the list, but the program is not working as expected.

Here's the code that I have right now:

def solution(Statuses):
    Statuses.sort()
    firstNum = 0
    print(Statuses)
    for i in range(len(Statuses) - 1):
        if Statuses[(firstNum   1)] - firstNum == 1:
            print("Yes")
        else:
            print("no")
        print(firstNum)
        firstNum  = 1
solution([6, 2, 3, 8])

Here's the output that I get with the code above:

[2, 3, 6, 8]
no
0
no
1
no
2

Here's the expected output:

[2, 3, 6, 8]
yes
0
no
1
no
2

The reason that the first yes/no... thing should say "yes" is because the 2 and 3 that you can see in the list's difference is 1, while the others are not.

What's the issue?

CodePudding user response:

If I understood correctly, what you want to do is check if the difference between two successive numbers in a list is 1. This is not what you are doing here :

if Statuses[(firstNum   1)] - firstNum == 1:

the correct code is

if Statuses[firstNum   1] - Statuses[firstNum] == 1:
  • Related