Answer to Question #186408 in Python for bharath

Question #186408

Given a sentence as input, print all the unique combinations of two 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 of two words in lexicographical order.Explanation


For example, if the given sentence is "raju plays cricket", the possible unique combination of two are (cricket, plays), (cricket, raju), (plays, raju). So the output should be

cricket plays
cricket raju
plays raju

Sample Input 1

raju plays cricket

Sample Output 1

cricket plays

cricket raju

plays raju

Sample Input 2

python is a programming language

Sample Output 2

a is

a language

a programming

a python

is language

is programming

is python

language programming

language python

programming python





1
Expert's answer
2021-04-27T23:33:16-0400
#get the input sentence from the user
sentence = input("Enter a sentence: ")

#split the sentence into separate words
s = sentence.split()

#sort the words in alphabetical order
s.sort()

#initialize a list to store the paired words
result = []

n=len(s) #get the length of the splitted sentence

for i in range(n):
    for j in range(i+1,n):
        two_words=s[i]+" "+s[j]
        result.append(two_words)  #append the words to the list

#display each line containing the unique combination of two words in lexicographical orde
for item in result:
    print(item)

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