Answer to Question #186427 in Python for bharath

Question #186427

Given a sentence as input, print all the unique combinations of the words of the sentence, considering different possible number of words each time (from one word to N unique words in lexicographical order).Input


The input will be a single line containing a sentence.Output


The output should be multiple lines, each line containing the unique combination from one word to N words in lexicographical order.Explanation


For example, if the given sentence is "apple is a fruit".

All possible one-word unique combinations are

a
apple
fruit
is


All possible two words unique combinations are

a apple
a fruit
a is
apple fruit
apple is
fruit is


All possible three words unique combinations are

a apple fruit
a apple is
a fruit is
apple fruit is


All possible four words unique combinations are

a apple fruit is

Sample Input 1

apple is a fruit

Sample Output 1

a

apple

fruit

is

a apple

a fruit

a is

apple fruit

apple is

fruit is

a apple fruit

a apple is

a fruit is

apple fruit is

a apple fruit is


1
Expert's answer
2021-04-29T03:16:47-0400
from itertools import combinations


print('Enter the string: ')
string = input()
words = string.split(' ')
for a in range(1, len(words)+1):
  comb = combinations(words, a)
  for x in comb:
    print(" ".join(x)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS