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?
#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")
Comments
Leave a comment