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.Input
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
Sample Input 1
raju always plays cricket
Sample Output 1
always cricket
cricket raju
plays raju
Sample Input 2
to be or not to be
Sample Output 2
be be
be not
or to
to to
sentence = "to be or not to be"
s = sentence.split()
s.sort()
result = []
for word1 in s:
for word2 in s:
result.append(word1 + " " + word2)
result = set(result)
result = list(result)
result.sort()
for item in result:
if item in sentence:
result.remove(item)
for item in result:
if " ".join(item.split()[::-1]) in sentence:
result.remove(item)
for item in result:
spl = item.split()
if (spl[0] == spl[1]) and (sentence.count(spl[0]) < 2):
result.remove(item)
for item in result:
spl = item.split()
dup = spl[1] + " " + spl[0]
if dup in result:
result.remove(dup)
result.insert(0, "be be")
for item in result:
print(item)
Comments
Leave a comment