Answer to Question #211597 in Python for sudheer

Question #211597

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

For example, if the given sentence is "python is a programming language", the possible unique combination of two are (a, is), (a, language), (a, programming), (a, python), (is, language), (is, programming), (is, python), (language, programming), (language, python), (programming, python). Out of these the combinations, (a, is), (a, programming), (is, python), (language, programming) are not valid as they contain words that are adjacent in the given sentence. So the output should be

a language

a python

is language

is programming

language python

programming python

input: input:

raju always plays cricket to be or not be

output: output:

always cricket be be

cricket raju be not

plays raju or to

to to

it should satisfy both inputs and hidden testcases?

so,can anyone make code for this?


1
Expert's answer
2021-06-30T03:15:46-0400
#python 3.9.5


user_str = input('Enter a string with words: ')
words = user_str.split()
words_result = []
words_adjacent =[]
for i in range(len(words)-1):
    words_adjacent.append(sorted([words[i],words[i+1]]))
for i in range(len(words)):
    for j in range(i+2,len(words)):
        word = sorted([words[i],words[j]])
        if word not in words_result and word not in words_adjacent :
            words_result.append(word)
if words_result:
    for item in sorted(words_result):
        print(*item)
else:
    print("No Combinations")

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