Reputation: 35646
Lets say I have a Python list like following.
list2 = list('ABCDCBEGHGWAOUOV')
['A', 'B', 'C', 'D', 'C', 'B', 'E', 'G', 'H', 'G', 'W', 'A', 'O', 'U', 'O', 'V']
While traversing the list at the 5th point I see 'C' is occurring again. So up to 'D' it is +4 and and the -1 since it come back.
A->B->C->D +3
C<-D -1
B<-C -1
B->E->G->H +3
G<-H -1
G->W +1
A<-W -4 etc...
I need to count steps for forward as positive and backward as negative. Any help for implementing this?
list1 = []
for item in list2:
if item in list1:
sum(1 for i in list2)
else:
list1.append(item)
Upvotes: 0
Views: 84
Reputation: 56467
I'm not sure what's the expected output or what's the rule behind these numbers. This doesn't make much sens: A<-W -4
. And this: A->B->C->D +4
: do you count nodes? But here C<-D -1
you count "steps", i.e. arrows? Anyway I'll give it a shot since it looks like a funny thing:
from itertools import islice
def get_it(list2):
moves = []
buffer = []
prev = list2[0]
for current in islice(list2, 1, None):
el = 2 * (current > prev) - 1
if buffer and el != buffer[0]:
moves.append(sum(buffer))
buffer = []
buffer.append(el)
prev = current
if buffer:
moves.append(sum(buffer))
return moves
Upvotes: 1