Skip to content

Instantly share code, notes, and snippets.

@piti118
Created February 9, 2011 13:57
Show Gist options
  • Save piti118/818515 to your computer and use it in GitHub Desktop.
Save piti118/818515 to your computer and use it in GitHub Desktop.
find array product like http://www.python.org/dev/peps/pep-0211/ (takes variable number of argument) [1,2,3]@[4,5]@[6,7] = [ [1,4,6],[1,4,7],[1,5,6],[1,5,7],[2,4,6]... and so on ]
# find array product like http://www.python.org/dev/peps/pep-0211/
# which means
# [1,2,3]@[4,5]@[6,7] = [1,4,6],[1,4,7],[1,5,6],[1,5,7],[2,4,6]... and so on
def aprod(*arg):
numarg = len(arg)
lenarray = map(len,arg)
finallen = reduce(lambda x,y:x*y,lenarray)
divisor = map(lambda i: reduce(lambda x,y:x*y,lenarray[i+1:],1),xrange(numarg))
index = [map(lambda n,l: (x/n)%l,divisor,lenarray) for x in xrange(finallen)]
#if you just want index for loop you can return index here
return map(lambda ia:map(lambda a,i: a[i],arg,ia),index)
print aprod([1,2,3],[2,4,5,6],[7,8,9])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment