Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create two linear lists from a conceptual circular list in python

Consider the following list:

>>> circle = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']  
>>> list(enumerate(circle))  
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h')]  

If circle is conceptualized as a circular list i.e. circle[0] is connected to circle[7], given a start index and an end index where start != end, I want to construct two lists that represent linear traversal orders in clockwise and counter-clockwise directions.

Depending on the values of start and end, here's what I have come up with:

Case 1: start < end

>>> circle = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']  
>>> start, end = 1, 6  
>>> clockwise = circle[start:end+1]  
>>> clockwise  
['b', 'c', 'd', 'e', 'f', 'g']  
>>> counter_clockwise = circle[start::-1] + circle[:end-1:-1]  
>>> counter_clockwise  
['b', 'a', 'h', 'g']  

Case 2: start > end

>>> circle = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']  
>>> start, end = 6, 1  
>>> clockwise = circle[start:] + circle[:end+1]  
>>> clockwise  
['g', 'h', 'a', 'b']  
>>> counter_clockwise = circle[start:end-1:-1]  
>>> counter_clockwise  
['g', 'f', 'e', 'd', 'c', 'b']  

Is there a pythonic/more-efficient/easier way of constructing these two lists?

like image 408
veritasium42 Avatar asked Mar 12 '26 10:03

veritasium42


1 Answers

You can use itertools.cycle:

import itertools

circle = ['a', 'b', 'c', 'd', 'e', 'f', 
  'g', 'h']

def clockwise(start, end):
    endless = itertools.cycle(circle)
    if start > end:
        end = start + (len(circle)-(start
          -end))
    return [next(endless) for i in range
      (end+1)][start:]

def counter_clockwise(start, end):
    endless = itertools.cycle(circle)
    if end > start:
        start = end + (len(circle)-(end
          -start))    
    return [next(endless) for i in range
      (start+1)][end:][::-1]

# start < end:
forward=clockwise(1, 6)
b1=counter_clockwise(1, 6)
#start > end:
f1=clockwise(6, 1)
backward=counter_clockwise(6, 1)

print(forward)
print(b1)
print(f1)
print(backward)

Outputs:

['b', 'c', 'd', 'e', 'f', 'g']
['b', 'a', 'h', 'g']
['g', 'h', 'a', 'b']
['g', 'f', 'e', 'd', 'c', 'b']
like image 89
Taku Avatar answered Mar 14 '26 22:03

Taku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!