Answer to Question #186413 in Python for bharath

Question #186413

Given a sentence as input, print all the unique combinations of N words in lexicographical order.Input


The first line of input will be containing a sentence.

The second line of input will contain a positive integer.Output


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


For example, if the given sentence is "apple is a fruit", and N is 3, the possible unique combination of three words are (a, apple, fruit), (a, apple, is), (a, fruit, is), (apple, fruit, is). So the output should be

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

Sample Input 1

apple is a fruit

3

Sample Output 1

a apple fruit

a apple is

a fruit is

apple fruit is

Sample Input 2

raju plays cricket

2

Sample Output 2

cricket plays

cricket raju

plays raju





1
Expert's answer
2021-04-27T21:03:57-0400
my_string = "apple is a fruit"
words = my_string.split()
words.sort()

result = []
for word1 in words:
    for word2 in words:
        for word3 in words:
            s=[]
            if(word1!=word2 and word2!=word3 and word3!=word1):
                s.append(word1)
                s.append(word2)
                s.append(word3)
                s.sort()
                k = s[0] + " " + s[1] + " " + s[2]
                result.append(k)


result = list(set(result))
for r in range(0,len(result)):
    print(result[r])





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