Search code examples
pythonloopslogicsequencecyclic

Generating Cyclic Words in Python


I have an array like

myarray = 'ABCDE'

and I want output as

required_output = [AB,BC,CD,DE,EA]  ## A cyclic form of array 'ABCDE'

I used following code

for i in range(len(myarray) + 1):

    a = i % len(myarray) ; b = i % len(myarray) + 2

    print myarray[a : b]

result I get as

AB , BC, CD, DE, E , AB

what logic I am missing which is causing 'e' to appear instead of 'ea' and also 'ab' should not have appeared ???

Another way I found was to use a loop like this

for i in range(1,len(myarray)):

    print myarray[i-1] + myarray[i]

gives output as

'EA','AB','BC','CD','DE'  ## where the last element 'EA' comes in the begining

Solution

  • It's not too hard to see what's going wrong

    >>> myarray = 'ABCDE'
    >>> for i in range(len(myarray) + 1):
    ...     a = i % len(myarray) ; b = i % len(myarray) + 2
    ...     print a, b, myarray[a: b]
    ... 
    0 2 AB
    1 3 BC
    2 4 CD
    3 5 DE
    4 6 E
    0 2 AB
    

    There's no way you're going to get a slice like 'EA' without doing something heroic like

    >>> myarray[::-4]
    'EA'
    

    The + 1 is obviously going to give you one more output than the number of items in myarray

    Easy fix is something like this

    >>> for i in range(len(myarray)):
    ...     print (myarray*2)[i:i+2]
    ... 
    AB
    BC
    CD
    DE
    EA