algorithm - Permutations and indexes, python -
i create list of permutations of lets 0,1,2
perm = list(itertools.permutations([0,1,2]))
this used accessing indexes in list in specific order. every time index accessed popped. when element popped, elements indexes higher popped elements index shift 1 position down. means if want pop list indexes [0,1,2] result in index error, since index 2 not exist when reach it. [0,1,2] should therefor popped in order [0,0,0].
more examples
[0,2,1] = [0,1,0] [2,0,1] = [2,0,0] [1,2,0] = [1,1,0]
right being handled through series of checks, question if knows smart way turn list of lists generated itertools desired list:
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 0), (2, 0, 0), (2, 1, 0)]
simply iterate through each tuple, , decrement indexes of each subsequent index greater element:
l=[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] def lower_idxs(lst): new_row = list(lst) i, val in enumerate(new_row): j in xrange(i+1, len(new_row)): if new_row[i] < new_row[j]: new_row[j] -= 1 return new_row print [lower_idxs(x) x in l]
will print out
[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0], [2, 1, 0]]
here fancier one-liner based on randy c's solution:
print [tuple(y-sum(v<y v in x[:i]) i,y in enumerate(x)) x in l]
Comments
Post a Comment