We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
class MapReduce:
def init(self):
self.intermediate = {}
self.result = []
def emitIntermediate(self, key, value):
self.intermediate.setdefault(key, [])
self.intermediate[key].append(value)
def emit(self, value):
self.result.append(value)
def execute(self, data, mapper, reducer):
for record in data:
mapper(record)
for key in self.intermediate:
reducer(key, self.intermediate[key])
self.result.sort()
for item in self.result:
print "{\"key\":\""+item[0]+"\",\"value\":\"" + str(item[1]) + "\"}"
def mapper(record):
# parse the input record into two friends
friend1, friend2 = record.split()
# emit intermediate key-value pairs for each friend
mapReducer.emitIntermediate(friend1, 1)
mapReducer.emitIntermediate(friend2, 1)
def reducer(key, list_of_values):
# compute the total number of friends for each person
total_friends = sum(list_of_values)
# emit the final output
mapReducer.emit((key, total_friends))
if name == 'main':
# read input data from standard input
inputData = []
for line in sys.stdin:
inputData.append(line.strip())
# create a new instance of the MapReduce class
mapReducer = MapReduce()
# execute the MapReduce job with the provided mapper and reducer functions
mapReducer.execute(inputData, mapper, reducer)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Map Reduce Advanced - Count number of friends
You are viewing a single comment's thread. Return to all comments →
Any idea why doesnt work properly?
import sys
class MapReduce: def init(self): self.intermediate = {} self.result = []
def mapper(record): # parse the input record into two friends friend1, friend2 = record.split() # emit intermediate key-value pairs for each friend mapReducer.emitIntermediate(friend1, 1) mapReducer.emitIntermediate(friend2, 1)
def reducer(key, list_of_values): # compute the total number of friends for each person total_friends = sum(list_of_values) # emit the final output mapReducer.emit((key, total_friends))
if name == 'main': # read input data from standard input inputData = [] for line in sys.stdin: inputData.append(line.strip())