-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq1rd.py
executable file
·51 lines (47 loc) · 1.57 KB
/
q1rd.py
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
#!/usr/bin/env python
import sys
from itertools import groupby
def parseInput():
for line in sys.stdin:
if len(line)>0:
line = line.strip()
yield line
def most_common(list):
return max(set(list), key=list.count)
def reducer():
current_key = None
neighbor_list = []
current_amount = 0.0
# for each driver, assign him/her the neighbor with maximal frequency
for line in parseInput():
key, neighbor, amount = line.split('\t')
if key == current_key:
if amount == '-1': # location line
neighbor_list.append(neighbor)
else:
try:
amount = float(amount)
current_amount += amount
except Exception:
continue
else: # key changes
if current_key and neighbor_list:
neighbor = most_common(neighbor_list)
print "%s\t%s" % (neighbor, current_amount)
current_key = key
neighbor_list = []
current_amount = 0.0
if amount == '-1': # location line
neighbor_list.append(neighbor)
else:
try:
amount = float(amount)
current_amount += amount
except Exception:
continue
if key == current_key: #final clean up
if key == current_key and neighbor_list:
neighbor = most_common(neighbor_list)
print "%s\t%s" % (neighbor, current_amount)
if __name__=='__main__':
reducer()