1

I am trying to write a simple Python script capable of the following:

The user inputs a string of letters and the code returns the combinations in the following way:

ABC ----> ABC, CAB, BCA. 

In this instance the "neighbors" remain the same but the last letter is moved to the beginning. I've been trying itertools but combinations and permutations aren't exactly what I'm looking for. Any help would be greatly appreciated!

timgeb
  • 76,762
  • 20
  • 123
  • 145

2 Answers2

2

You are looking for rotations, not permutations.

collections.deque can do that.

>>> d = deque('ABC')
>>> ''.join(d)
>>> 'ABC'
>>> d.rotate(1)
>>> ''.join(d)
>>> 'CAB'
>>> d.rotate(1)
>>> ''.join(d)
>>> 'BCA'

If you want to store all the rotations in a list, you can do

>>> d = deque('ABC')
>>> result = [''.join(d)]
>>> for _ in range(len(d) - 1):
...:    d.rotate(1)
...:    result.append(''.join(d))
...:    
>>> result
>>> ['ABC', 'CAB', 'BCA']

You should be able to handle the user input stuff yourself.

timgeb
  • 76,762
  • 20
  • 123
  • 145
2

I don't thing there is a direct function for it, but it's fairly simple to generate a oneliner

x='abcde'
result = [x[-i:]+x[:-i] for i in range(len(x))]
# result will be ['abcde', 'eabcd', 'deabc', 'cdeab', 'bcdea']
ilmarinen
  • 4,557
  • 3
  • 16
  • 12
  • Thank you so much! Worked perfectly. – Matt Hostetler Nov 04 '18 at 21:43
  • This worked well for regular string as asked in this question. I have a new issue is that the string is now separated by "," where I want to split them. What I want to do is: A,B,C ---------> 'A,B,C' 'C,A,B' 'B,C,A' – Matt Hostetler Nov 16 '18 at 16:08
  • The oneliner works with any iterable, so the easiest for you is to split the string with the separator you want. x='a,b,c,d,e'.split(',') – ilmarinen Nov 17 '18 at 21:10