I have the following code written in python 2.7 to find n time Cartesian product of a set (AxAxA...xA)-
prod=[]
def cartesian_product(set1,set2,n):
if n>=1:
for x in set1:
for y in set2:
prod.append('%s,%s'%(x,y))
#prod='[%s]' % ', '.join(map(str, prod))
#print prod
cartesian_product(set1,prod,n-1)
else:
print prod
n=raw_input("Number of times to roll: ")
events=["1","2","3","4","5","6"]
cartesian_product(events,events,1)
This works properly when n=1. But changing the parameter value from cartesian_product(events,events,1) to cartesian_product(events,events,2) doesn't work. Seems there's an infinite loop is running. I can't figure where exactly I'm making a mistake.
prodasset2. Sinceprodis defined outside the function, set2 and prod are now the same thing. so when you dofor y in set2andprod.append, you are appending toset2, which is causing the infinite iteration.itertools.productdoes the job (unless this is homework of some sort)for y in set2stage. only after it comes out of that can it callcartesian_productagain which will print prod.