• Things I learned from Video Code Review with veky

Since the last year, one of our Awesome Users veky has been doing video code review on CheckiO. Here is a very short highlight of the most interesting and educational code:

Avoid for i in range(len(items)-1)

"This is the most unpythonic way"

There are a lot of Python functions that will help you to simplify it:

for i in range(len(items)-1):
     item = items[i]

This can be written as

for i, item in enumerate(items):

and if you want to use number (i+1) instead of index you can do:

for num, item in enumerate(items, 1):

Instead of:

for i in range(len(items) -1):
     item = items[i]
     num = i+1

If you want to use more than one element in "for", then instead of:

for i in range(len(items)-1):
     left = items[i]
     right  = items[i+1]

You can do:

for left, right in zip(items, items[1:]):

Video

lru_cache - this ugly guy can become your best friend in a speed optimization process

Here is a very unoptimized solution for fibonacci number:

def stupid_fibonacci(n):
	if n < 2:
		return n
	else:
		return stupid_fibonacci(n-1) + stupid_fibonacci(n-2)

On my laptop, stupid_fibonacci(35) can take up to 1 minute but if you add lru_cache decorator:

from functools import lru_cache as memoize

@memoize()
def stupid_fibonacci(n):
	if n < 2:
		return n
	else:
		return stupid_fibonacci(n-1) + stupid_fibonacci(n-2)

.. then, execution will be 1000x faster.

Video

Max arg and max val

Those are two very simple lines of code. One which gives you an element with maximal length:

max(items, key=len)

… and another that gives you a maximal length itself:

max(map(len, items))

Video

Extracting sequence

Items = [3,1,4,6,7]
min_item, *other_data, max_item = sorted(items)

This small trick works starting with python3.5. It allows you to extract values not only from the start of the sequence but also from the end of it.

*other_data, last_item = items

Video

Some other small tricks

>>> True == False == False
False

>>> (True == False) == False
True

>>> 32.bit_length()
    32.bit_length()
                ^
SyntaxError: invalid syntax

>>> 32 .bit_length()
Out[17]: 6

Welcome to CheckiO - games for coders where you can improve your codings skills.

The main idea behind these games is to give you the opportunity to learn by exchanging experience with the rest of the community. Every day we are trying to find interesting solutions for you to help you become a better coder.

Join the Game