R
RickMuller
I have to sort a list, but in addition to the sorting, I need to
compute a phase factor that is +1 if there is an even number of
interchanges in the sort, and -1 if there is an odd number of
interchanges.
I could write a bubble sort, count the number of interchanges, and
compute the factor, but I have a feeling that there some
decorate-sort-undecorate solution buried in this problem somewhere.
However, I can't see it. Can anyone else help me with this?
I was thinking of something along the lines of zipping the list with a
range() of the same length, sorting that, and then counting the number
of times the second list has an item smaller than its previous item. In
other words
a = [1,10,2,7]
b = zip(a,range(len(a)))
b.sort()
a_sorted = [i for i,j in b]
order = [j for i,j in b]
phase = 0
for i in range(len(order)-1):
if order > order[i+1]: phase += 1
phase = 2*(phase%2)-1
However, I can't prove that this works, and there's *got* to be a more
elegant way.
Thanks in advance,
Rick
compute a phase factor that is +1 if there is an even number of
interchanges in the sort, and -1 if there is an odd number of
interchanges.
I could write a bubble sort, count the number of interchanges, and
compute the factor, but I have a feeling that there some
decorate-sort-undecorate solution buried in this problem somewhere.
However, I can't see it. Can anyone else help me with this?
I was thinking of something along the lines of zipping the list with a
range() of the same length, sorting that, and then counting the number
of times the second list has an item smaller than its previous item. In
other words
a = [1,10,2,7]
b = zip(a,range(len(a)))
b.sort()
a_sorted = [i for i,j in b]
order = [j for i,j in b]
phase = 0
for i in range(len(order)-1):
if order > order[i+1]: phase += 1
phase = 2*(phase%2)-1
However, I can't prove that this works, and there's *got* to be a more
elegant way.
Thanks in advance,
Rick