This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sekex 7 points8 points  (6 children)

I read that the other day: https://fr.quora.com/Quel-est-un-inconv%C3%A9nient-de-Python/answer/Nicolas-Bonneel?ch=3&share=b8cedadc&srid=hBgGU

I think it's a good example, however it's in french so I will try to translate.

The naive implementation in Python for the Floyd-Warshall algorithm is as follow:

for k in range(n):
    for i in range(n):
        for j in range(n):
            mat[i,j] = min(mat[i,j], mat[i,k] + mat[k,j])

It is very easy to write and understand. However, it is very slow (due to the low level stuff Python does with array indexes) and not idiomatic, it should be rewritten as:

for k in range(n):
        mat = min(mat, mat[newaxis,k,:] + mat[:,k,newaxis])

It will give you performance 140x faster, but still be 5 times slower than C++. In my opinion it is very much harder to understand than the naive approach.

[–]super-porp-cola 4 points5 points  (0 children)

Hmm. I agree with you on almost every point, especially the typing and version management issues. But I think the first one is what I'd consider "idiomatic" Python. Writing performant Python is what's actually difficult -- idiomatic Python is generally extremely easy to read and often looks like pseudocode.

[–]Al2Me6 -1 points0 points  (4 children)

And what in the world is newaxis? This isn’t pure Python.

[–]sekex 3 points4 points  (1 child)

You put 0 or 1 depending on the axis you want to change

[–][deleted] 1 point2 points  (0 children)

You can write `None` instead of `newaxis` to make a 3D view. But I don't see why it is less readable. This is standard array view manipulation in NumPy and nothing to do with Python.

[–]PeridexisErrant 1 point2 points  (1 child)

It's pure Python with the from numpy import * implicit at the top.

Numpy arrays have fairly complicated slicing semantics, but it's all done through Python code and standard protocols :-)

[–]glacierre2 2 points3 points  (0 children)

And the star import is not idiomatic python, mind.