converted Java solution to Python