Sage is a Python (and the snippet you pasted works fine in Python). And I'm also curious what would qualify that code as "horrid." I'd make light suggestion to improve performance by making `seen` a set right off the bat, but for this size of problem, that sort of detail is unimportant. Calling somebody's code "horrid" without even understanding what it's doing isn't a productive approach to, well; anything, really.