简体   繁体   中英

Is there any way to condense a for-else loop in Python?

I have made a piece of code that spits out prime numbers up to the 10001st number. It currently takes up 4 lines of code, and was wondering if I could condense it further? Here it is;

for i in range(3,104744,2):
    for x in range(3,int(i/2),2):
        if i % x == 0 and i != x: break
    else: print(i)

I am aware that condensing code too much is usually not a good thing, but was wondering if it was possible.

Thanks.

You can use a list comprehension and any to get a one-liner solution:

>>> [p for p in range(2, 100) if not any (p % d == 0 for d in range(2, int(p**0.5) + 1))]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

It uses the fact that a divisor cannot be larger than the square root of the number it divies.

It seems to work fine:

>>> len([p for p in range(2, 104744) if not any (p % d == 0 for d in range(2,int(p**0.5)+1))])
10001

List comprehension

>>> r=range(2,100)
>>> [p for p in r if [p%d for d in r].count(0)<2]

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Try this one:

for i in range(3,100,2):
    if all( i%x for x in range(3, i//2, 2) ):
        print(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM