Reputation: 426
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
Upvotes: 0
Views: 1231
Reputation: 304137
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
Upvotes: 0
Reputation: 1416
Maybe it helps you:
In [1]: m = 'ABCDE'
In [2]: ml = list(m)
In [3]: zip(ml, ml[1:] + [m[0]])
Out[3]: [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'A')]
Upvotes: 0
Reputation: 838
[''.join(a) for a in zip(myarray,myarray[1:]+myarray[0])]
output:
['AB', 'BC', 'CD', 'DE', 'EA']
Upvotes: 0
Reputation: 250921
You can use zip
here:
def cycle(s):
return [ ''.join(x) for x in zip(s, s[1:]+s[:1])]
>>> cycle('ABCDE')
['AB', 'BC', 'CD', 'DE', 'EA']
>>> cycle('ABCD')
['AB', 'BC', 'CD', 'DA']
Using indexes, similar to your method:
def cycle(s):
for i in range(len(s)):
yield s[i] + s[(i+1)%len(s)]
print list(cycle('ABCDE'))
print list(cycle('ABCD'))
Output:
['AB', 'BC', 'CD', 'DE', 'EA']
['AB', 'BC', 'CD', 'DA']
Upvotes: 2
Reputation: 239453
Why not just
print [data[i: (i + 2)] for i in range(len(data) - 1)] + [data[-1] + data[0]]
Output
['AB', 'BC', 'CD', 'DE', 'EA']
Upvotes: 0