# Getting all possible combinations of members of a list

Hi there,

I have got a list containing the make of a car and all of the possible extras that are possible with that particular make.  The list is of the following type:

[[Toyota Yaris, Sun-Roof, Air-Con, ABS, Immobiliser, Metallic Paint, Passenger Airbag, Leather Seats, Sports Suspension] , [Volkswagon Polo, Sun-Roof, Air-Con, ABS, Immobiliser, Metallic Paint, Passenger Airbag, Leather Seats, Sports Suspension, Chrome Grill, Body Coloured Mirrors]

Another list is then needed that will have the car make along with the possible combinations of extras available to the customer.  A list like this:

[[Toyota Yaris, Sun-Roof, Air-Con] , [Toyota Yaris, Metallic Paint] , [Volkswagon Polo, ABS, Immobiliser, Metallic Paint, Passenger Airbag]] and all of the other combinations.

For this I have been using the following function, but it's not working right:

def combi(listmember):

first = listmember.pop()
if len(listmember)==0:
return [[first], []]

submember = combi(listmember)
return [[first] + lstmem for lstmem in submember] + submember

I need for all of the resulting combinations to be stored in another list and have the following format:

[[Make%Extra1*Extra2*Extra3.......] , [Make%Extra1*Extra2....] , ................]

Hope you can help,

John
###### Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x

Commented:
Here you go:

import pprint

OPTIONS = [
["Toyota Yaris", "Sun-Roof", "Air-Con", "ABS", "Immobiliser"],
["Volkswagon Polo", "Immobiliser", "Metallic Paint", "Passenger Airbag"],
]

def get_combinations(options):
"""Find all combinations by counting in binary."""
combinations = []
for i in range(1, 2**len(options)):
combinations.append([options[j] for j in range(len(options)) if (1 << j) & i])
return combinations

result = []
for row in OPTIONS:
car, combinations = row[0], get_combinations(row[1:])
for combination in combinations:
result.append("%s%%%s" % (car, "*".join(combination)))

pprint.pprint(result)
0

Commented:
I don't immediately have code to do this, but do you realise how big these lists are going to be?  That Polo has 1,024 different combinations of extras!
0