Can't figure out how to use all() to work in my "code"
python, python-2.7
Solution
You have to pass a sequence or iterable to `all` -- it just tests whether or not all the items passed to it evaluate as true. Here's the right way to use `all`:
>>> all([True, True, True])
True
>>> all([True, False, True])
False
>>> all([x > 5 for x in range(10)])
False
>>> all([x > 5 for x in range(6, 10)])
True
>>> all(x > 5 for x in range(6, 10))
True
That last one is the best, because it takes advantage of short-circuiting.
However, your call to `all` in your code is pointless. The idea behind your code, it seems to me, is to go through all the values in `m` and remove those that are divisible by any number between 2 and 2000000. Once you've done that, `m` will contain only prime numbers.
Of course, your code still won't work if you remove `all`. That's because you're actually testing whether each number in `m` is divisible by the numbers `[1, 3, 5, 7...1999999]`. (That's the sequence signified by `xrange(1, 2000000, 2)`. Because you start at `1`, and everything is divisible by `1`, your code will count nothing as prime. And then, once you remove `1` from that sequence, anything divisible by `2` will be counted as prime by your code! You should think more carefully about which numbers you actually have to test in your inner loop.
Finally, you should think about how many loops this code will complete. Even once you have this working, it will take a very long time to generate a result. You should test it on smaller numbers first; and then, you should think about how to reduce the number of loops. (And -- only after you've thought about it a bit -- read this.)
But once you have this working, all you have to do is call `sum` on your list of primes.
Problem
``` m = range(1, 2000000, 2) sum1 = 2 for x in xrange(1, 2000000, 2): for y in m: if x != y: if x%y == 0: m.remove(x) if all(x%y != 0): sum1 += x ``` That's what I've written. It's about a problem, trying to add all the primes bellow two million. My problem is in the all() statement. What I want to happen is to check if x is a prime; that is true only if every x%y gives a remainder. Also if I use a can I use a statement (break?) to stop the loop if y > x/3 like so: ``` m = range(1, 2000000, 2) sum1 = 2 for x in xrange(1, 2000000, 2): for y in m: if y > x/3: break else: if x != y: if x%y == 0: m.remove(x) if all(x%y != 0): sum1 += x ```