Skip to content

Instantly share code, notes, and snippets.

@ysmood
Created May 21, 2014 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysmood/b8781cfb5785cf36db31 to your computer and use it in GitHub Desktop.
Save ysmood/b8781cfb5785cf36db31 to your computer and use it in GitHub Desktop.
#!/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