Question #209307

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.


Expert's answer

#Python 3.9.5


def combinationsWords(user_str):

    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")

user_str = input('Enter a string with words: ')

combinationsWords(user_str)

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!

LATEST TUTORIALS
APPROVED BY CLIENTS