Refactored based on Python solution on Codewars