Answer to Question #185586 in Python for J NAGAMANI

Question #185586

Non-Adjacent Combinations of Two Words

Given a sentence as input, find all the unique combinations of two words and print the word combinations that are not adjacent in the original sentence in lexicographical order.


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


The output should be multiple lines, each line containing a valid unique combination of two words. A valid combination will not contain the words that appear adjacent in the given sentence. Print "No Combinations" if there are no valid combinations_Explanation.


Sample Input 1

raju always plays cricket


Sample Output 1

always cricket

cricket raju

plays raju


Sample Input 2

python is a programming language


Sample Output 2

a language

a python

is language

is programming

language python

programming python


Please the output should be printed exactly as shown in the above testcases.


1
Expert's answer
2021-04-26T05:41:09-0400
#Get the input string
inputWords = list(input("Enter string: ").split())
#List of Combinations of Two Words
combinationsTwoWords = []
for i in range(len(inputWords)):
    for j in range(i+2,len(inputWords)):
        if inputWords[i] < inputWords[j]:
            combinationsTwoWords.append(inputWords[i] + ' ' + inputWords[j])
        else:
            combinationsTwoWords.append(inputWords[j] + ' ' + inputWords[i])
#Display Non-Adjacent Combinations of Two Words
for w in sorted(combinationsTwoWords):
    print(w)

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

J NAGAMANI
26.04.21, 14:27

Thank you

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS