#! /usr/bin/python3
# ==================================================================
# Reorder the elements in a list
#
# Reorder the list every Nth element.
#
# Note: There is no way to recover the original order of the list
# elements when sort is used. The original list's order
# information is lost.
#
# See the sort related code. What happens when sort is used?
#
# ------------------------------------------------------------------
#
# For example with sort (step every third element):
#
# original list [44, 3, 56, 2, 56, 8, 9, 43, 22, 1]
# reordered list [1, 9, 44, 2, 22, 56, 3, 43, 56, 8]
# restored list? [1, 2, 3, 8, 9, 22, 43, 44, 56, 56]
#
# ==================================================================
#
# notes:
#
# 1. for python2 try xrange
#
# ==================================================================
# ---- reorder list ------------------------------------------------
def reorder_list(oldlist,step,use_sort=False):
'''
Reorder a list given an integer step value.
use_sort defaults to False. Use True to use a sort.
'''
##print('\nReorder List (step={},sort={})'.format(step,use_sort))
sortlist = list(oldlist)
if use_sort: # sort the original list?
sortlist.sort()
newlist = list(sortlist) # list to modify and return
l = len(newlist) # list length
jj = 0
j = 0
s = 0
##print('')
for i in range(0,l):
##print('i={} j={} src={}'.format(i,j,sortlist[i]))
newlist[j] = sortlist[i]
j += step
if j >= l:
jj += 1
j = jj
##print('')
print('')
print('---- Reorder list ----------------------------')
print('step = {}'.format(step))
print('use sort = {}'.format('True' if use_sort else 'False'))
print('original {}'.format(oldlist))
if use_sort:
print('sorted {}'.format(sortlist))
print('reordered {}'.format(newlist))
return newlist
# ---- restore list ------------------------------------------------
def restore_list(oldlist,step):
'''
Restore a reordered list given an integer step value.
Note: There is no way to recover the original order of the list
elements because of the sort. The original list's order
information is lost.
'''
##print('\nRestore List (step={})'.format(step))
newlist = list(oldlist)
l = len(newlist) # list length
ii = 0
i = 0
s = 0
##print('')
for j in range(0,l):
##print('j={} i={} src={}'.format(j,i,oldlist[j]))
newlist[j] = oldlist[i]
i += step
if i >= l:
ii += 1
i = ii
##print('')
print('')
print('---- Restored list ---------------------------')
print('step = {}'.format(step))
print('reordered {}'.format(oldlist))
print('restored {}'.format(newlist))
return newlist
# --- main ---------------------------------------------------------
if __name__ == '__main__':
l = [44,3,56,2,56,8,9,43,22,1] # test list
step = 3 # reorder step count
print('\n==== reordere without sort ===================')
ll = reorder_list(l,step)
lll = restore_list(ll,step)
print('\n==== reorder with sort =======================')
ll = reorder_list(l,step,True)
lll = restore_list(ll,step)