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
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])
Comments
Leave a comment