Minho Ha
Minho Ha

Reputation: 43

How to print all possible combinations in string using itertools?

I am studying Python personally these days. I have a question about python code.

A = "I " + (can/cannot) + " fly"
B = "I am " + (13/15) + " years old"

In theses cases, variable A can select two options, 'can' or 'cannot'. Also, variable B can select two options, 13 or 15. I don't want to use these options myself. I don't know how to select two options automatically.

If it can be automatically, I want to use itertools module. I want result using "combinations" to do this.

C = [(I can fly I am 13 years old) , (I can fly I am 15 years old) , (I cannot fly I am 13 years old) , (I cannot fly I am 15 years old)]

If anyone who can help me with this code, please help.

Upvotes: 0

Views: 354

Answers (3)

theletz
theletz

Reputation: 1795

First, you would like to find all the combinations of (can/cannot) and (13/15).

To do this you can use:

import itertools
can_or_cannot = ['can', 'cannot']
age = [13, 15]
list(itertools.product(can_or_cannot, age))

Out[13]: [('can', 13), ('can', 15), ('cannot', 13), ('cannot', 15)]

Now you can use list comprehension:

C = [f"I {can_or_cannot} fly I am {age} years old" for (can_or_cannot, age) in list(itertools.product(can_or_cannot, age))]


Out[15]: 
['I can fly I am 13 years old',
 'I can fly I am 15 years old',
 'I cannot fly I am 13 years old',
 'I cannot fly I am 15 years old']

Or, as suggested by @Olvin Roght, you can use a template and starmap:

from itertools import product, starmap

template = 'I {} fly I am {} years old'
result = list(starmap(template.format, product(can_or_cannot, age)))

Upvotes: 3

Olvin Roght
Olvin Roght

Reputation: 7812

For some reasons, @theletz decided to not include my recommendation into his answer, so I'll post it here:

from itertools import product, starmap

can_or_cannot = ['can', 'cannot']
age = [13, 15]
template = 'I {} fly I am {} years old'

result = list(starmap(template.format, product(can_or_cannot, age)))

How does it work?

  1. We use itertools.product() to get cartesian product of two lists;
  2. Result of previous action we redirect directly to itertools.starmap(), which execute str.format() and pass unpacked pair as function arguments.

Upvotes: 1

Vaibhav Jadhav
Vaibhav Jadhav

Reputation: 2076

You can try this:

fly = ["can","cannot"]
lst = []
for i in fly:
    A = "I " + i + " fly"
    for j in [13,15]:
        B = " I am " + str(j) + " years old"
        lst.append((A+B))
print(lst)

Upvotes: -2

Related Questions