# Untitled

By: a guest on Jun 13th, 2012  |  syntax: None  |  size: 1.17 KB  |  hits: 16  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. Explaining this primes generator function, i cannot understand [python]
2. def primes(n):
3.     if n==2: return [2]
4.     elif n<2: return []
5.     s=range(3,n+1,2)
6.     mroot = n ** 0.5
7.     half=(n+1)/2-1
8.     i=0
9.     m=3
10.     while m <= mroot:
11.         if s[i]:
12.             j=(m*m-3)/2
13.             s[j]=0
14.             while j<half:
15.                 s[j]=0
16.                 j+=m
17.         i=i+1
18.         m=2*i+3
19.     return [2]+[x for x in s if x]
20.
21. def primes(n):
22.     if n==2: return [2]
23.
24. elif n<2: return []
25.
26. s=range(3,n+1,2)
27.
28. mroot = n ** 0.5
29.
30. half=(n+1)/2-1
31.
32. i=0
33.     m=3
34.
35. while m <= mroot:
36.         if s[i]:
37.
38. j=(m*m-3)/2
39.             s[j]=0
40.
41. while j<half:
42.                 s[j]=0
43.                 j+=m
44.
45. i=i+1
46.         m=2*i+3
47.
48. return [2]+[x for x in s if x]
49.
50. >>> numbers = range(40)
51. >>> numbers[1] = 0    # 1 isn't prime
52. >>> for i in numbers:
53. ...     if i:
54. ...         for j in range(i + i, len(numbers), i):
55. ...             numbers[j] = 0
56. ...
57. >>> [n for n in numbers if n]
58. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
59.
60. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10...]
61.
62. [0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10...]
63. [0, 0, 2, 3, 0, 5, 0, 7, 0, 9, 0...]
64. [0, 0, 2, 3, 0, 5, 0, 7, 0, 0, 0...]