onsdag 9 november 2022

[Python] len() and time complexity

Some say "if you care about speed you shouldn't use Python". Others say "since Python isn't fast, you have to optimize it to make it viable".


The behavior of len() depends on the class definition.

Calling len() is always taking constant time for iterable data structures(string, list, tuple, etc.). That's because they have __len__() defined that way. They use a counter which is altered when the iterable in question is altered. len() is therefore just returning a counter in this scenario.

Without defining __len__() you can't use len() on it. Since it's up to the creator of the class to define what this dunder method should do and return, you can have any time complexion. You could for example traverse something every time the method is called. 

måndag 7 november 2022

Pygame for Python 3.11

As of writing this, Python 3.11 is a new release and in order to use it with Pygame you have to install Pygame in slightly different way:

pip install pygame --pre

fredag 4 november 2022

How to learn & three great Python books

 I recently found an interesting article about learning:

https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5780548

From this paper:

Six strategies for effective learning:

1. Spaced practice - Instead of studying it all within a short time.

2. Interleaving - Switching between topics while studying.

3. Retrieval practice - Bringing learned information to mind from long-term memory.

4. Elaboration - Asking and explaining why and how things work.

5. Concrete examples - illustrating abstract concepts with specific examples.

6. Dual coding - Combining words with visuals.


For me, learning by doing works great. It makes it more fun and engaging.

For this I recommend the Python Cookbook: Recipes for Mastering Python 3 by Brian K. Jones and David M. Beazley.


Other great intermediate level books are Fluent Python and Effective Python: 90 Specific Ways to Write Better Python by Brett Slatkin.