Skip to content

Instantly share code, notes, and snippets.

@Buttonwood
Created October 16, 2014 06:22
Show Gist options
  • Select an option

  • Save Buttonwood/3ecbc8a15850f26ece92 to your computer and use it in GitHub Desktop.

Select an option

Save Buttonwood/3ecbc8a15850f26ece92 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File: map-shuff-reduce.py
@Author: Hao Tan
@Date:
@Email: tanhao2013@foxmail.com
@Desc:
"""
from math import sqrt
def isPrime(aNum):
if aNum < 2:
print "Some thing wrong for prime testing here!\nYou'd better choose a big num!"
return False
elif aNum == 2 or aNum == 3 :
return True
else:
for x in xrange(2, int(sqrt(aNum))+1):
if aNum % x == 0:
return False
return True
def Map(bNum):
result = []
if bNum < 2:
print "Some thing wrong for map testing here!\nYou'd better choose a big num!"
elif bNum == 2:
result.extend([(2,2)])
else:
for p in xrange(2,bNum+1):
if isPrime(p):
if bNum % p == 0:
result.append((p,bNum))
return result
def Shuff(aList):
from collections import defaultdict
table = defaultdict(list)
for l in aList:
if len(l) >=1:
for x,y in l:
table[x].append(y)
return table
def Reduce(d):
for k in d:
print "%d\t%d" % (k,reduce(lambda x, y:x+y, d[k]))
def test():
a = [2,13,11,121,77,49,35,63,8,29,12,36,60,200,32]
al = map(Map,a)
print al
at = Shuff(al)
print at
Reduce(at)
if __name__ == '__main__':
test()
"""
[[(2, 2)], [(13, 13)], [(11, 11)], [(11, 121)], [(7, 77), (11, 77)], [(7, 49)], [(5, 35), (7, 35)], [(3, 63), (7, 63)], [(2, 8)], [(29, 29)], [(2, 12), (3, 12)], [(2, 36), (3, 36)], [(2, 60), (3, 60), (5, 60)], [(2, 200), (5, 200)], [(2, 32)]]
defaultdict(<type 'list'>, {2: [2, 8, 12, 36, 60, 200, 32], 3: [63, 12, 36, 60], 5: [35, 60, 200], 7: [77, 49, 35, 63], 11: [11, 121, 77], 13: [13], 29: [29]})
2 350
3 171
5 295
7 224
11 209
13 13
29 29
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment