Answer to Question #195728 in Python for sai

Question #195728

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


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. The words in each line should be lexicographical order and the lines as well should be in lexicographical order. 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

Sample Input 3

to be or not to be

Sample Output 3

be be

be not

or to

to to


1
Expert's answer
2021-05-19T15:51:24-0400
def nonAdjacentCombinations(sentens:str):


	s = sentens.split()
	combinations = []
	flag = False
	if len(s) > 2:
		for i in range(0, len(s) - 2):
			for j in range(i + 2, len(s)):
				w_1 = [k for k, e in enumerate(s) if e == s[i]]
				w_2 = [k for k, e in enumerate(s) if e == s[j]]
				if (len(w_1) + len(w_2)) > 2:


					for el_1 in w_1:
						for el_2 in w_2:
							if abs(el_1 - el_2) == 1:
								flag  = True
				if flag:
					flag = False
					continue
				tmp = (' '.join(sorted([s[i], s[j]], key=str.upper)))
				if tmp not in combinations:
					combinations.append(tmp)
	if len(combinations) > 0:
		for line in sorted(combinations, key=str.upper):
			print(line)
	else:
		print('No Combinations')


while True:
	s = input()
	if s == 'exit':
		break
	else:
		nonAdjacentCombinations(s)

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