Created
March 20, 2019 20:01
-
-
Save dsoike/c336cc7b6008c40bbd0ea354c606ce76 to your computer and use it in GitHub Desktop.
Custom Sort Function in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# sort things by highest priority & lowest time | |
thing1 = {'id': 1, 'priority': 1, 'time': 500} | |
thing2 = {'id': 2, 'priority': 5, 'time': 400} | |
thing3 = {'id': 3, 'priority': 5, 'time': 600} | |
thing4 = {'id': 4, 'priority': 10, 'time': 100} | |
things = [thing1, thing2, thing3, thing4] | |
def sort_things(thing1, thing2): | |
if thing1['priority'] > thing2['priority']: | |
return -1 | |
elif thing1['priority'] < thing2['priority']: | |
return 1 | |
elif thing1['time'] < thing2['time']: | |
return -1 | |
elif thing1['time'] > thing2['time']: | |
return 1 | |
else: | |
return 0 | |
things_sorted = sorted(things, cmp=sort_things) | |
things_sorted_ids = map(lambda x: x['id'], things_sorted) | |
expected_sorted_ids = [4, 2, 3, 1] | |
print('sorted_ids={}'.format(things_sorted_ids)) | |
print('expected_ids={}'.format(expected_sorted_ids)) | |
assert(things_sorted_ids == expected_sorted_ids) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment