Search code examples
pythonfor-loopiteratordefinitions

Python 'not in' operator not working correctly?


def step(g, m, n):
    notstorage=[]
    actualvalues =[]
    for i in range(m, (n+1)):
        for primechecker in range(2,i):
            if i % primechecker == 0:
                notstorage.append(i)



    for value in range(m, (n+1)):
        if (value) and (value+g) not in set(notstorage):
            actualvalues.append(value)
            actualvalues.append(value+g)
            break
    return(actualvalues)

In the above code I'm trying to figure out which numbers are prime and create a list that checks if there are two prime numbers separated by a certain number (g). I'm having issues because for some reason the number 303 is being returned as a prime number when it clearly is not since it is divisible by 3.... I'm not sure why the code isn't working properly?

When I input:

step(4,300,400)

I am expecting an output of (307,311) since those are the first 2 prime numbers that are 4 numbers apart but instead I get a return of (303, 307)

Not sure what I've done wrong?


Solution

  • You need to use this syntax instead:

    if (value) not in set(notstorage) and (value+g) not in set(notstorage):