1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import re
import urllib
import simplejson


#--- Helpers ----------------------------------------------
def determine_hours(item):
    posted = item['postedAgo']
    if 'minutes' in posted:
        return 0
    elif 'hour' in posted:
        return int(re.match("\d+", posted).group(0))

def calculate_score(votes, item_hour_age, gravity=1.8):
    return (votes - 1) / pow((item_hour_age+2), gravity)

def sort_fn(a, b):
    if a['score'] > b['score']:
        return -1
    elif a['score'] == b['score']:
        return 0
    else:
        return 1


#Fetch current data
data = urllib.urlopen('http://api.ihackernews.com/page').read()
items = simplejson.loads(data)['items']


#Calculate score
for item in items:
    item['score'] = calculate_score(item['points'],
                                    determine_hours(item))


#Create two dicts for remembering placements
old_placements = {}
for i, item in enumerate(items):
    old_placements[item['id']] = i

new_placements = {}
for i, item in enumerate(sorted(items, sort_fn)):
    new_placements[item['id']] = i


#Print result
for i in items:
    print '%s' % (i['title'])
    print 'OldP: %02d    NewP: %02d     Points: %03d      Posted: %s' %\
                    (old_placements[i['id']], new_placements[i['id']],
                     i['points'], i['postedAgo'])
    print ''