Python: using list comprehension to cycle through a word with an offset (removing one letter at a time)

Viewed 43

I am trying to use list comprehension to cycle through the letters in a word and get new combinations after removing one letter at a time.

E.g. say the input string is a word: 'bathe'

I would like to get the output in a list (preferably) with the following [athe, bthe, bahe, bate]

ie, making just one pass from left to right

---- this is the literal, but I need to accomplish this with list comprehension

word = "bathe"

newlist1 = [word[1::], (word[1:2] + word[-3:]), (word[:2] + word[-2:]), word[:3] + word[-1:] ]

print('sample 1', newlist1)

newlist2 = [(word[1:2] + word[-3:]), (word[1:2] + word[-3:]), (word[:2] + word[-2:]), word[:3] + word[-1:] ]

print('sample 2', newlist2)


I got through the first pass with this code, but am stuck now

x = [(word[:i] + word[-j:]) for i in range(1,4) for j in range(4,1, -1)]

The output I get is obviously not right, but (hopefully) is directionally there (when it comes to using list comprehensions)

['bathe', 'bthe', 'bhe', 'baathe', 'bathe', 'bahe', 'batathe', 'batthe', 'bathe']

1 Answers

You can do it like this:

First, you need some way to remove a certain element from a list:

def without(lst: list, items: list) -> list:
    """
    Returns a list without anything in the items list
    """
    new_lst = lst.copy()
    for e in lst:
        if e in items:
            items.remove(e)
            new_lst.remove(e)
    return new_lst

Then, using that function you can create your new word list.

new_word_list = ["".join(without(list(word), list(letter))) for letter in word]

As showed in your wanted output, you don't want the last result of this, so you can just add [:-1] to it.

new_word_list = ["".join(without(list(word), list(letter))) for letter in word][:-1]

Another way you could do it (without the without function):

new_word_list = [word[:index - 1] + word[index:] for index, _ in enumerate(word)][1:]

The [1:] at the end is because you end up with a weird string at the beginning (because of the way it is written). The weird string is bathbathe (when word is bathe)

Related