views:

89

answers:

3

Is it possible to convert this function, list comprehension combination into a single list comprehension (so that keep is not needed)?

def keep(list, i, big):
    for small in list[i+1:]:
        if 0 == big % small:
            return False
    return True

multiples[:] = [n for i,n in enumerate(multiples) if keep(multiples, i, n)]
+6  A: 

I think this is it:

multiples[:] = [n for i,n in enumerate(multiples) 
                       if all(n % small for small in multiples[i+1:])] 
recursive
+1 This looks more readable than original code for me. That is somewhat subjective, though.
Tony Veijalainen
+2  A: 

multiples[:] = [n for i, n in enumerate(multiples) if 0 not in [n % other for other in multiples[i+1:]]

Advisible? Probably not.

Nathon
+1 for the lack of advisability.
llasram
+1  A: 

First thing is to learn to not use names like list in your code. Remember also the "first make it work, then optimize". If you continue to learn things, it is likely that in any case after one month you are not any more happy with your code. Try to make readable code. For that it helps if you can (heaven forbid!) read your own code after putting it aside for few weeks.

That said, it is actually more readable sometimes to make list comprehension, but often you can do it only after writing more stupid version of code.

Tony Veijalainen
good point about naming the variable list
spoon16