Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2
- # https://repl.it/@BradenBest/ProbableJuvenileRegisters
- # Defining a general-purpose sort function (selection sort algorithm)
- # function takes a list and an optional comparator
- def cmp_default(a, b):
- """General purpose comparator. Works for numbers and strings"""
- if(a < b): return -1
- if(a > b): return 1
- return 0
- def swap(array, a, b):
- temp = array[a]
- array[a] = array[b]
- array[b] = temp
- def sort_run(array, start, cmp):
- """find the lowest item and swap it with the start point"""
- lowest = start
- for i in xrange(start, len(array)):
- if cmp(array[lowest], array[i]) > 0:
- lowest = i
- if lowest != start:
- swap(array, start, lowest)
- def sort(array, cmp = cmp_default):
- for i in xrange(len(array)):
- sort_run(array, i, cmp)
- # Testing our sort function
- def cmp_flight(a, b):
- """Sort by destination first, arrival time second"""
- cmpr = cmp_default(a[0], b[0])
- if cmpr == 0:
- return cmp_default(a[1], b[1])
- return cmpr
- def before_and_after(lst, cmp = None):
- print "Before: %s" % str(lst)
- if cmp is None:
- sort(lst)
- else:
- sort(lst, cmp)
- print "After: %s\n" % str(lst)
- list1 = [1,5,32,6,7,2,7,34,6,8,34,9,5,1,454,2]
- list2 = ["Alice", "Xander", "Jerry", "Bob", "Bobert", "Ian"]
- list3 = [["Chicago", 1045], ["Birmingham", 630], ["Chicago", 700], ["Birmingham", 845]]
- before_and_after(list1)
- before_and_after(list2)
- before_and_after(list3, cmp_flight)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement