File tree Expand file tree Collapse file tree 1 file changed +42
-42
lines changed Expand file tree Collapse file tree 1 file changed +42
-42
lines changed Original file line number Diff line number Diff line change @@ -74,46 +74,48 @@ With Cython you are also able to call C-functions and realize strong typing of v
74
74
75
75
.. code-block :: python
76
76
77
- def primes (int kmax ):
78
- cdef int n, k, i
79
- cdef int p[1000 ]
80
- result = []
81
- if kmax > 1000 :
82
- kmax = 1000
83
- k = 0
84
- n = 2
85
- while k < kmax:
86
- i = 0
87
- while i < k and n % p[i] != 0 :
88
- i = i + 1
89
- if i == k:
90
- p[k] = n
91
- k = k + 1
92
- result.append(n)
93
- n = n + 1
94
- return result
77
+ def primes (int kmax ):
78
+ cdef int n, k, i
79
+ cdef int p[1000 ]
80
+ result = []
81
+ if kmax > 1000 :
82
+ kmax = 1000
83
+ k = 0
84
+ n = 2
85
+ while k < kmax:
86
+ i = 0
87
+ while i < k and n % p[i] != 0 :
88
+ i = i + 1
89
+ if i == k:
90
+ p[k] = n
91
+ k = k + 1
92
+ result.append(n)
93
+ n = n + 1
94
+ return result
95
+
95
96
96
97
This implementation of an algorithm to find prime numbers has some additional commands instead of the next one, which is implemented in pure Python:
97
98
98
99
.. code-block :: python
99
100
100
- def primes ( kmax ):
101
- p= range (1000 )
102
- result = []
103
- if kmax > 1000 :
104
- kmax = 1000
105
- k = 0
106
- n = 2
107
- while k < kmax:
108
- i = 0
109
- while i < k and n % p[i] != 0 :
110
- i = i + 1
111
- if i == k:
112
- p[k] = n
113
- k = k + 1
114
- result.append(n)
115
- n = n + 1
116
- return result
101
+ def primes ( kmax ):
102
+ p= range (1000 )
103
+ result = []
104
+ if kmax > 1000 :
105
+ kmax = 1000
106
+ k = 0
107
+ n = 2
108
+ while k < kmax:
109
+ i = 0
110
+ while i < k and n % p[i] != 0 :
111
+ i = i + 1
112
+ if i == k:
113
+ p[k] = n
114
+ k = k + 1
115
+ result.append(n)
116
+ n = n + 1
117
+ return result
118
+
117
119
118
120
119
121
The only difference between the both algorithm is this part:
@@ -124,20 +126,18 @@ Strong typing with Cython:
124
126
125
127
# primes function with additional Cython code:
126
128
def primes (int kmax ):
127
- cdef int n, k, i
128
- cdef int p[1000 ]
129
- result = []
130
-
129
+ cdef int n, k, i
130
+ cdef int p[1000 ]
131
+ result = []
131
132
132
133
Normal variable definition in Python:
133
134
134
135
.. code-block :: python
135
136
136
137
# primes in standard Python syntax:
137
138
def primes ( kmax ):
138
- p= range (1000 )
139
- result = []
140
-
139
+ p= range (1000 )
140
+ result = []
141
141
142
142
What is the difference? In the upper Cython version you can see the definitions of the variable types like in standard C.
143
143
For example `cdef int n,k,i ` in line 3. This additional type definition (e.g. integer) allows the Cython compiler to generate
You can’t perform that action at this time.
0 commit comments