Sorting troubles
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Mon May 14 22:35:04 EDT 2007
On Mon, 14 May 2007 09:49:56 -0700, Thomas Nelson wrote:
> The thing is that [x for x in List[1:]...] is a brand new list created
> by iterating over the old one.
> How about:
> qSortHelp(List):
> newlist = qSort(List)
> for i, val in enumerate(newlist):
> List[i] = val
> You have to iterate over one more time, but this sorts the list in
> place.
A better way of spelling that would be:
def qSortHelp(List):
List[:] = qSort(List)
return List
but the helper function is redundant, as it is easy enough to make the
qSort function behave the same way. We can also make the code a smidgen
more concise by reversing the sense of the test at the start of the code:
def qSort(List):
if List:
List[:] = qSort([x for x in List[1:] if x< List[0]]) \
+ List[0:1] + qSort([x for x in List[1:] if x>=List[0]])
return List
--
Steven.
More information about the Python-list
mailing list