Python solution for codility practice