1

I have a list m in python, and I want to remove all the elements in m that are not relatively prime to all previous elements. So if m=[2,3,4] I want the output to be [2,3].

I tried iterating through the values of m, but it doesnt work since the size of m changes and then the index value is out of range.

Lawrence Benson
  • 1,398
  • 1
  • 16
  • 33
Jacob
  • 63
  • 6
  • 1
    Can you add the code that you are talking about? – Mazdak Sep 15 '15 at 14:58
  • 4
    possible duplicate of [Remove items from a list while iterating in Python](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) – tzaman Sep 15 '15 at 15:00

1 Answers1

7

You can use enumerate and any within a list comprehension and use fractions.gcd function to get the gcd for each pairs :

>>> from fractions import gcd
>>> [j for i,j in enumerate(m) if not any(gcd(j,t)!=1 for t in m[:i])]
[3, 100, 7, 11, 17]

Also as @mgilson mentioned in comment as a more efficient way instead of simple slicing in any you can use itertools.islice function.

Mazdak
  • 105,000
  • 18
  • 159
  • 188