improved speed of Python solution