Search code examples
pythonwhile-loop

Why does my code print 2 different numbers? They're supposed to be the same


The "seq" list won't have repeating numbers, and will never have a length longer than 9. I am trying to get my code to return the missing integer in a given list from 0-9. I resolved to do this by removing a number from an integer "checklist" every time the system finds a matching number. Somehow, the IF statement in line 7 manages to get called when it's technically false.

def get_missing_element(seq):
    missing = None
    i = 0
    f = 0
    checklist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    while f < len(checklist):
        if checklist[f] == seq[i]:
            checklist.remove(checklist[f])
            print("i see", seq[i])
            print("removed", checklist[f])
            i = i + 1
            f = 0
        f = f + 1
    return missing
seq = [1, 8, 2, 3, 4, 5, 0, 7, 9]
print(get_missing_element(seq))

I tried using For loops in the beginning, but I didn't know how to get a For loop to repeat itself without using a while loop. Does the root of my problem lie within the fact that I'm using a while loop here?


Solution

  • For a more general solution that doesn't rely on the elements being integers:

    def get_missing_element(it):
        # {} without : makes a set
        checkset = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
        for e in it:
            # This will throw if `e` is repeated or not in `checkset`.
            # Use `.discard(e)` to silently ignore such elements.
            checkset.remove(e)
        # tuple-unpacking will throw if there isn't exactly one element left.
        r, = checkset
        return r
    seq = [1, 8, 2, 3, 4, 5, 0, 7, 9]
    print(get_missing_element(seq))
    

    Generally for questions of the form "is this a member", you want to use set, dict, or related (frozenset, collections.Counter, ...)