mirror of
https://github.com/kennethreitz/python-guide.git
synced 2026-06-05 23:00:18 +00:00
indentation fixed
This commit is contained in:
+42
-42
@@ -74,46 +74,48 @@ With Cython you are also able to call C-functions and realize strong typing of v
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def primes(int kmax):
|
||||
cdef int n, k, i
|
||||
cdef int p[1000]
|
||||
result = []
|
||||
if kmax > 1000:
|
||||
kmax = 1000
|
||||
k = 0
|
||||
n = 2
|
||||
while k < kmax:
|
||||
i = 0
|
||||
while i < k and n % p[i] != 0:
|
||||
i = i + 1
|
||||
if i == k:
|
||||
p[k] = n
|
||||
k = k + 1
|
||||
result.append(n)
|
||||
n = n + 1
|
||||
return result
|
||||
def primes(int kmax):
|
||||
cdef int n, k, i
|
||||
cdef int p[1000]
|
||||
result = []
|
||||
if kmax > 1000:
|
||||
kmax = 1000
|
||||
k = 0
|
||||
n = 2
|
||||
while k < kmax:
|
||||
i = 0
|
||||
while i < k and n % p[i] != 0:
|
||||
i = i + 1
|
||||
if i == k:
|
||||
p[k] = n
|
||||
k = k + 1
|
||||
result.append(n)
|
||||
n = n + 1
|
||||
return result
|
||||
|
||||
|
||||
This implementation of an algorithm to find prime numbers has some additional commands instead of the next one, which is implemented in pure Python:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def primes( kmax):
|
||||
p= range(1000)
|
||||
result = []
|
||||
if kmax > 1000:
|
||||
kmax = 1000
|
||||
k = 0
|
||||
n = 2
|
||||
while k < kmax:
|
||||
i = 0
|
||||
while i < k and n % p[i] != 0:
|
||||
i = i + 1
|
||||
if i == k:
|
||||
p[k] = n
|
||||
k = k + 1
|
||||
result.append(n)
|
||||
n = n + 1
|
||||
return result
|
||||
def primes( kmax):
|
||||
p= range(1000)
|
||||
result = []
|
||||
if kmax > 1000:
|
||||
kmax = 1000
|
||||
k = 0
|
||||
n = 2
|
||||
while k < kmax:
|
||||
i = 0
|
||||
while i < k and n % p[i] != 0:
|
||||
i = i + 1
|
||||
if i == k:
|
||||
p[k] = n
|
||||
k = k + 1
|
||||
result.append(n)
|
||||
n = n + 1
|
||||
return result
|
||||
|
||||
|
||||
|
||||
The only difference between the both algorithm is this part:
|
||||
@@ -124,10 +126,9 @@ Strong typing with Cython:
|
||||
|
||||
#primes function with additional Cython code:
|
||||
def primes(int kmax):
|
||||
cdef int n, k, i
|
||||
cdef int p[1000]
|
||||
result = []
|
||||
|
||||
cdef int n, k, i
|
||||
cdef int p[1000]
|
||||
result = []
|
||||
|
||||
Normal variable definition in Python:
|
||||
|
||||
@@ -135,9 +136,8 @@ Normal variable definition in Python:
|
||||
|
||||
#primes in standard Python syntax:
|
||||
def primes( kmax):
|
||||
p= range(1000)
|
||||
result = []
|
||||
|
||||
p= range(1000)
|
||||
result = []
|
||||
|
||||
What is the difference? In the upper Cython version you can see the definitions of the variable types like in standard C.
|
||||
For example `cdef int n,k,i` in line 3. This additional type definition (e.g. integer) allows the Cython compiler to generate
|
||||
|
||||
Reference in New Issue
Block a user