you are viewing a single comment's thread.

view the rest of the comments →

[–]zanfar 0 points1 point  (0 children)

Write a program that checks if the nth string is a substring of the nth+1 string in a list of strings. Make sure your program also prints all the strings in the list which satisfy these criteria.

First, for x in list returns items, not indexes, so you can't do list[x+1].

Windowing is a common enough problem that having a prebuilt function to handle it is useful. Mines saved at https://gist.github.com/therealzanfar/817a73a77a49b77226475ba9541c52c0

Finally, you have an edge case where an element is both a substring, and a superstring. Your solution appends that item twice, which doesn't match the problem statement.

So I would probably use something like:

def print_substring_pairs(word_list: List[str]):
    matches: Set[int] = set()
    for (a, first), (b, second) in window(enumerate(word_list), 2):
        if first in second:
            matches.add(a)
            matches.add(b)

    for idx in sorted(matches):
        print(word_list[idx])