python - Reorder the Range with specific way -


i'm looking way reorder given range have first, last, middle one, middles of middles , on..., if @ 0-15 range this: neighbor members come @ last iteration.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

0 15 8 4 12 2 6 10 13 1 3 5 7 9 11 14

any ideas algorithm?

here's solution uses queue instead of recursion. 13 , 14 positioned differently example, if consistently consider middle of even-length list element after middle, 14 comes first.

import collections  def reorder(seq):     '''yield items seq reordered http://stackoverflow.com/q/33372753/     seq can sequence, eg. list or python 3 range object.     '''     # output first , last element before middles     if seq:         yield seq[0]     if len(seq) > 1:         yield seq[-1]      # queue of range indices (start, stop)     queue = collections.deque([(1, len(seq)-1)])     while queue:         start, stop = queue.popleft()         if start < stop:             middle = (start + stop) // 2             yield seq[middle]             queue.append((start, middle))             queue.append((middle+1, stop))  print(list(reorder(range(16)))) #[0, 15, 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13]     

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -