Answer to Question #341376 in Python for sandhya

Question #341376

Family List:

A list of words is called the Family if the words in the list follow the following rule.

we should be able to obtain each word in the list by

-changing exactly one letter from the previous word in the list

-or , by adding exactly one letter to the previous word in the list

-or ,by removing exactly one letter from the previous word in the list

Given a list of words ,determine if the list is a Family or Not a Family

input:

The first line of input is an integer T representing the number of test cases

the first line of each test case has an integer N representing the total number of words

The second line contains N space separated strings


1
Expert's answer
2022-05-18T15:25:46-0400
number_tests = int(input())


for _ in range(number_tests):
    number_words = int(input())
    words = list(map(str, input().split(' ')))
    is_family = 1
    for i, word in enumerate(words):
        if i != 0 and word != words[i - 1]:
            if abs(len(word) - len(words[i-1])) > 1:
                is_family = 0
                break
            else:
                prev = words[i-1]
                if len(word) == len(words[i-1]):
                    counter = sum(a != prev[j] for j, a in enumerate(word))
                    if counter > 1:
                        is_family = 0
                        break
                elif len(word) > len(prev):
                    count_a = 0
                    t_word = 0
                    t_prev = 0
                    while t_prev < len(prev) and t_word < len(word):
                        if word[t_word] != prev[t_prev]:
                            t_prev -=1
                            count_a += 1
                        t_prev += 1
                        t_word += 1
                    if count_a > 1:
                        is_family = 0
                        break
                else:
                    count_a = 0
                    t_word = 0
                    t_prev = 0
                    while t_prev < len(prev) and t_word < len(word):
                        if word[t_word] != prev[t_prev]:
                            t_word -=1
                            count_a += 1
                        t_prev += 1
                        t_word += 1
                    if count_a > 1:
                        is_family = 0
                        break
    if is_family == 1:
        print("family")
    else:
        print("not a family")

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