Created
May 21, 2014 04:35
-
-
Save ysmood/b8781cfb5785cf36db31 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# Question: | |
# If user_1 followed user_2, we will get an array item like: | |
# [id_1, id_2] | |
# Here is a sample user relationship list: | |
# [ [2, 3], [1, 4], [3, 2], [1, 3], [4, 2], [7, 2], [5, 3], [4, 1] ] | |
# If two items have two same IDs, print one of the them out. | |
# So if we print out [3, 2] and [1, 4], that should be a right result. | |
rel_list = [ [2, 3], [1, 4], [3, 2], [1, 3], [4, 2], [7, 2], [5, 3], [4, 1] ] | |
digit_weight = 10 ** len( | |
str( | |
max( | |
[item for sublist in rel_list for item in sublist] | |
) | |
) | |
) | |
# Get the weight value of the relationship. | |
def weight (rel): | |
a, b = rel if rel[0] < rel[1] else rel[::-1] | |
return a * digit_weight + b | |
# Simulate to trigger the comparison event. | |
def compare_event (e): | |
if e['val'] == 0: | |
print e['rel'] | |
def compare (a, b): | |
val = weight(a) - weight(b) | |
compare_event({ 'val': val, 'rel': a }) | |
return val | |
# The default sort algorithm in Ruby is Quick Sort, which is plenty good here. | |
# Time: average O(log n) | worst n * n | |
# Memory: average log n | worst n | |
sorted(rel_list, compare) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment