Home > front end >  How to create combination of words using python list
How to create combination of words using python list

Time:08-29

I'm having python list and want to create a combination of words without duplicates and search for each combination available in the string.

fruits = ['apple','banana','grape','papaya']

create combination of above list like this:

combination = [" apple banana","apple grape","apple papaya","banana grape","banana papaya", "grape papaya"]

Is it possible to reverse the combination list like:

reverse_combination = [" banana apple", "grape apple","papaya apple", "grape banana", "papaya banana", "papaya grape"]

I tried using two for loops but I'm not able to get what I need. If someone suggests the better logic it will help me. Thank You.

CodePudding user response:

Use itertools.combinations

Ex:

import itertools

fruits = ['apple','banana','grape','papaya']

result = []
resultRev = []
for i, v in itertools.combinations(fruits, 2):
    result.append(" ".join([i, v]))
    resultRev.append(" ".join([v, i]))
    
print(result)
print(resultRev)

Output:

['apple banana', 'apple grape', 'apple papaya', 'banana grape', 'banana papaya', 'grape papaya'] 
['banana apple', 'grape apple', 'papaya apple', 'grape banana', 'papaya banana', 'papaya grape']

CodePudding user response:

It is possible to use two for-loops.

for fruit_idx1 in range(0, len(fruits) - 1):
    for fruit_idx2 in range(fruit_idx1   1, len(fruits) - 1):
        combination.append(f"{fruits[fruit_idx1]} {fruits[fruit_idx2]}")

You can reverse it by doing:

for combo in combination:
    reverse_combination.append(' '.join(combo.split()[::-1]))
  • Related