Python implementation in Cpp (for educational purposes)