Answer to Question #205799 in Python for Chavali Anand Babu

Question #205799

sir in this question #177142  original output doesn't come how to solve this question

your output was come above code is





  a python
is language
is programming
language a
programming python
python language


but original out is

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-06-11T07:34:54-0400
def find_non_adjacent_combinations(sentence):
    words_list = sentence.split()
    adj_dict = {}
    for index in range(len(words_list)):
        word = words_list[index]
        if word not in adj_dict.keys():
            adj_dict[word] = set()
        left_index = index - 1
        right_index = index + 1
        if left_index >= 0:
            adj_dict[word].add(words_list[left_index])
        if right_index < len(words_list):
            adj_dict[word].add(words_list[right_index])

    combinations = []
    for w1 in words_list:
        for w2 in words_list:
            if w1 == w2 and words_list.count(w1) < 2:
                continue
            combinations.append((w1, w2))
    combinations = list(set(combinations))

    result = []
    for pair in combinations:
        ban_1 = adj_dict[pair[0]]
        ban_2 = adj_dict[pair[1]]
        if pair[0] not in ban_2 and pair[1] not in ban_1:
            result.append(pair)
    result.sort()
    for pair in result:
        duplicate = (pair[1], pair[0])
        if pair[0] != pair[1] and duplicate in result:
            result.remove(duplicate)

    for pair in result:
        print(pair[0], pair[1])


test_sentence = "raju always plays cricket"
find_non_adjacent_combinations(test_sentence)

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