Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save kevinslin/5102851 to your computer and use it in GitHub Desktop.

Select an option

Save kevinslin/5102851 to your computer and use it in GitHub Desktop.

Revisions

  1. @9thbit 9thbit created this gist Jan 4, 2012.
    15 changes: 15 additions & 0 deletions SortingWithRandomizedTies.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    import random

    def compare_with_ties(a, b):
    diff = cmp(a, b)
    return diff if diff else random.choice([-1, 1])

    a = {'a': 1, 'b': 2, 'c': 1, 'd':2, 'e': 1}

    print "Initial dictionary:\n", str(a.iteritems())

    print "\nSorted without randomizing ties:"
    print sorted(a.iteritems(), key=lambda (k, v): v)

    print "\nSorted with randomized ties:"
    print sorted(a.iteritems(), key=lambda (k, v): v, cmp=compare_with_ties)