Python 'not in' operator not working correctly?

4.4k Views Asked by At
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?

2

There are 2 best solutions below

5
Julien On BEST ANSWER

You need to use this syntax instead:

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

0
Some programmer dude On

The expression

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

checks if (value) evaluates to True, and that (value+g) not in set(notstorage) evaluates to True.

It does not check if both (value) and (value+g) are not in the set.