How to make this naive python implement of Quicksort more pythonic? -


i'm 2 hours reading of diveintopython , implemented naive version of quicksort.

import operator  def even(num):     return operator.mod(num,2) == 0  def last(list):     return len(list)-1  def median(list):     if even(len(list)):         return len(list)/2 - 1     else:         return len(list)/2  def sort(list, pivot_selector):     if len(list) <= 1:         return list     else:         = pivot_selector(list)         pivot = list[i]         less, greater, equal = [], [], []         x in list:             if x < pivot:                 less.append( x )             elif x == pivot:                 equal.append( x )             else:                 greater.append( x )      return sort(less, pivot_selector) + equal + sort(greater, pivot_selector)  if __name__ == "__main__":     print sort([5,4,3,2],median)     print sort([],median)     print sort([2],median)     print sort([3,2],median)     print sort([3,2,3],median)     print sort([1,3,2],median)     print sort([1,'a',0],median)     print sort([none,1,0],median) 

5 questions:

  1. this code resides in file called quicksort.py. how 1 hide method even being exported public.
  2. is pythonic pass in *pivot_selector* parameter ?
  3. anything wrong or suboptimal quicksort implementation ?
  4. how allow user specify comparator enforce custom ordering on list elements ?
  5. is there pythonic way enforce constraint list parameter must contain homogeneous types ?

1 - code resides in file called quicksort.py. how 1 hide method being exported public.

the convention name functions private module with underscore @ beginning.

2 - pythonic pass in *pivot_selector* parameter ?

since python has first class functions it's fine pass functions around parameters.

3 - wrong or suboptimal quicksort implementation ?

the use of equal list seems non-traditional me. usually items equal pivot end in greater list.

4 - how allow user specify comparator enforce custom ordering on list elements ?

the standard python sort() , sorted() functions have optional parameter comparison function. seems best way it.

5 - there pythonic way enforce constraint list parameter must contain homogeneous types ?

in python don't worry this. python has concept of duck-typing, if object it's supposed don't worry checking type beforehand. expressed "it's easier ask forgiveness permission."

so let user of module worry exception thrown if pass in list of objects sort can't compared each other.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -