Print sorbet flavors

You’re working for a restaurant and they’re asking you to generate the sorbet menu.

Provide a script printing every possible sorbet duos from a given list of flavors.

Don’t print recipes with twice the same flavor (no “Chocolate Chocolate”), and don’t print twice the same recipe (if you print “Vanilla Chocolate”, don’t print “Chocolate Vanilla”, or vice-versa).

The flavors are:

FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]

> My code is here:

FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]

for i in FLAVORS:
    if len(FLAVORS) >= 2:
        for g in FLAVORS:
            if g==i:
                continue
            else:
                print(f"{i}, {g}")
        FLAVORS.remove(g)

the result I got:

Banana, Chocolate
Banana, Lemon
Banana, Pistachio
Banana, Raspberry
Banana, Strawberry
Banana, Vanilla
Chocolate, Banana
Chocolate, Lemon
Chocolate, Pistachio
Chocolate, Raspberry
Chocolate, Strawberry
Lemon, Banana
Lemon, Chocolate
Lemon, Pistachio
Lemon, Raspberry
Pistachio, Banana
Pistachio, Chocolate
Pistachio, Lemon

The question is: Why not proposing Pistachio, Raspberry (or Raspberry, Pistachio)?

Answer

You can do the following:

import itertools
for f in itertools.permutations(FLAVORS, 2):
    if f[0] <= f[-1]:
        print(f)

It will output:

('Banana', 'Chocolate')
('Banana', 'Lemon')
('Banana', 'Pistachio')
('Banana', 'Raspberry')
('Banana', 'Strawberry')
('Banana', 'Vanilla')
('Chocolate', 'Lemon')
('Chocolate', 'Pistachio')
('Chocolate', 'Raspberry')
('Chocolate', 'Strawberry')
('Chocolate', 'Vanilla')
('Lemon', 'Pistachio')
('Lemon', 'Raspberry')
('Lemon', 'Strawberry')
('Lemon', 'Vanilla')
('Pistachio', 'Raspberry')
('Pistachio', 'Strawberry')
('Pistachio', 'Vanilla')
('Raspberry', 'Strawberry')
('Raspberry', 'Vanilla')
('Strawberry', 'Vanilla')

The condition f[0] <= f[-1] works because reversing the permutation would always flip the relation between first and last element!

Leave a Reply

Your email address will not be published. Required fields are marked *