Answer to Question #203190 in Python for Reddy

Question #203190

All Possible Subsets

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
1
Expert's answer
2021-06-04T07:14:09-0400
from itertools import combinations


def Combinations(W,n):
    Comb=[]
    for i in combinations(W,n):
        s=""
        for r in range(0,len(i)):
           s = s + i[r] + " " 
        Comb.append(s)
    return(Comb) 


#lexological ordering lexicogarphical 
my_string = "apple is a fruit"
words = my_string.split()
words.sort()


print("Input String: ",my_string)


for r in range(1,len(words)+1):
   print("\nSentence using %d word(s) Combinations:"%r)
   u = sorted(Combinations(words,r))
   for i in range(len(u)):
       print(u[i])

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