Home > Enterprise >  Return all possible combinations of two lists
Return all possible combinations of two lists

Time:12-08

I've tried to return all the possible combinations of two given lists using class the combination will have to consist of one element from each list. I can do until the length of the second list is 1. But after increasing the length, I don't get the expected output.

as an example the code is

class IceCreamMachine:

    def __init__(self, ingredients, toppings):
        self.ingredients = ingredients
        self.toppings = toppings
        
    def scoops(self):
        IceCreamList = []
        for i in range(len(self.ingredients)):
            IceCreamList.append([self.ingredients[i], self.toppings[i%len(self.toppings)]])
        
        return IceCreamList
        
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])

print(machine.scoops())

it returns the expected output which is [['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']] but whenever I tend to increase the element of the second list it shows an incorrect answer. Can anyone suggest me how to solve the problem?

CodePudding user response:

using itertools.product

import itertools

class IceCreamMachine:
    def __init__(self, ingredients, toppings):
        self.ingredients = ingredients
        self.toppings = toppings
        
    def scoops(self):
      return list(itertools.product(self.ingredients,self.toppings))
        
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce","banana sauce"])
print(machine.scoops())

output

[('vanilla', 'chocolate sauce'), ('vanilla', 'banana sauce'), ('chocolate', 'chocolate sauce'), ('chocolate', 'banana sauce')]

CodePudding user response:

I think this can be done by using two for-loop:

def scoops(self):
    IceCreamList = []
    for i in range(len(self.ingredients)):
        for j in range(len(self.toppings)):
            IceCreamList.append([self.ingredients[i], self.toppings[j]])
    
    return IceCreamList

use "for [variable] in [list]" can make the code looks simpler

def scoops(self):
    IceCreamList = []
    for i in self.ingredients:
        for j in self.toppings:
            IceCreamList.append([i,j])
    
    return IceCreamList

if you want to have the combination with more than one option, the code will be more complicated then this...

  • Related