Advertisement
makispaiktis

Cartesian Product

Sep 6th, 2020 (edited)
1,812
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. '''
  2. If list = [list1, list2, list3], where list1, list2, list3 are 3 lists, for example:
  3. list1 = [1, 2, 3] ,   list2 = ['a', 'b'],    list3 = [4, 5] ----> return
  4. [ [1, 'a', 4], [1, 'a', 5], [1, 'b', 4], [1, 'b', 5], .... ]
  5. '''
  6.  
  7. def cartesianProduct(listOfLists):
  8.     n = len(listOfLists)
  9.     # n = the number of lists I have to combine
  10.     if n == 1:
  11.         return listOfLists
  12.     elif n == 2:
  13.         list1 = listOfLists[0]
  14.         list2 = listOfLists[1]
  15.         returnedList = list()
  16.         for a in list1:
  17.             for b in list2:
  18.                 # a = element of list1, b = element of list2
  19.                 listAB = list()
  20.                 listAB.append(a)
  21.                 listAB.append(b)
  22.                 returnedList.append(listAB)
  23.         return returnedList
  24.     else:
  25.         # Now, n = 3,4,5, .... I have to combine these lists
  26.         # I will make a recursive algorithm, where I breakm y first variable "listOfLists"
  27.         # into 2 lists: the 1st one that has 2 lists and the remaining list
  28.         sub1 = cartesianProduct(listOfLists[0:2])
  29.         sub2 = listOfLists[2:]
  30.         sub = [sub1, sub2]
  31.         return cartesianProduct(sub)
  32.         return -100
  33.  
  34. # MAIN FUNCTION
  35. l1 = [5, 6]
  36. l2 = [15, 16]
  37. l3 = [25, 26]
  38. l4 = [35, 36]
  39. l12 = [l1, l2]
  40. l123 = [l1, l2, l3]
  41. l1234 = [l1, l2, l3, l4]
  42. print(l12)
  43. print(cartesianProduct(l12))
  44. print()
  45. print(l123)
  46. print(cartesianProduct(l123))
  47. print()
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement