The pythonic way of generating strings

Consider the string '1234' . You need a function that generates all rotations: '1234', '3412', '4123', '2341' . I created a simple test package:

 assert rotations('123') == set(['123', '231', '312']) assert rotations('111') == set(['111']) assert rotations('197') == set(['197', '971', '719']) 

What is the pythonic way to do this? I ended up with the code below

 def rotations(num): str_num = str(num) result = set() for mid in xrange(len(str_num)): result.add( str_num[mid:] + str_num[:mid] ) return result 
+5
source share
3 answers
 s='1234' z = {s[x:]+s[:x] for x in range(len(s))} 
+3
source

The second example shows that your approach is ineffective if the number is periodic (e.g. 123123123123). As a solution - check if this rotation has appeared. If so, the sequence is periodic and you have already detected all the distinguishable rotations, so just return the result:

 def rotations(num): str_num = str(num) result = set() for mid in range(len(str_num)): rot = str_num[mid:] + str_num[:mid] if rot in result: return result else: result.add(rot) return result 

(I changed your xrange to range since I am using Python 3 - you can of course change it back).

+3
source

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.

+2
source

Source: https://habr.com/ru/post/1235191/


All Articles