Although this is definitely not the fastest or certainly the most Pythonic answer, you can use collections.deque to do this.
from collections import deque def rotations(s): s_dq = deque(s) result = set() for _ in xrange(len(s_dq)): s_dq.rotate(1) result.add(''.join(s_dq)) return result
And it passes all your sample tests:
def main(): tests = ['123', '111', '197'] desired = [set(['123', '231', '312']), set(['111']), set(['197', '971', '719'])] for test, result in zip(tests, desired): print rotations(test) == result if __name__ == '__main__': main()
True
True
True
I would not recommend using collection.deque for this particular problem, but it can be applied to more complex versions of such problems. This is a very useful and, in my opinion, incomplete tool - that’s why I included it as an answer to this question.
source share