So, I get interesting behavior from some filters laid out in a for loop. I will start with a demo:
>>> x = range(100)
>>> x = filter(lambda n: n % 2 == 0, x)
>>> x = filter(lambda n: n % 3 == 0, x)
>>> list(x)
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]
Here we get the expected result. We have a range inside the filter inside the filter, and the filter conditions add up as we want. Now here is my problem.
I wrote a function to calculate the relative primes of a number. It looks like this:
def relative_primes(num):
'''Returns a list of relative primes, relative to the given number.'''
if num == 1:
return []
elif is_prime(num):
return list(range(1, num))
result = range(1, num)
for factor in prime_factors(num):
result = filter(lambda n: n % factor != 0, result)
return list(result)
For some reason, the filter only applies to the LAST coefficient in the list obtained from prime_factors (). Example:
>>> prime_factors(30)
[2, 3, 5]
>>> relative_primes(30)
[1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29]
We see that multiple 2 or 3 are excluded from the list. Why is this happening? Why does the above example work, but the filters in the for loop do not work?