user7619593
user7619593

Reputation:

How do I swap a letter with its immediate neighbor in a string?

I am trying to create a function that takes a string as an argument and returns a list of all of the generated words by swapping a letter with its immediate neighbor.

I first take each letter and create a list of strings and each string contains one letter.

Then I iterate through the new list of letters and try to swap them.

Then I join the letters together to form a string.

Then I append the new string to the list that I return.

Here is my code. Please tell me how to fix it. I don't want it to display the passed word in the list. Thank you.

def mixedString(word):

    word = word.lower()
    letters = []
    newArray = []

    for n in word:
        letter = f"{n}"
        letters.append(letter)

    newList = []

    for i in range(len(letters)):
        newWord = ""
        newArray = letters[i:] + letters[:i]
        newWord = "".join(newArray)
        newList.append(newWord)

    return newList

myWord = "Dog"

print(mixedString(myWord))

Upvotes: 0

Views: 385

Answers (3)

norok2
norok2

Reputation: 26886

There are many points of improvement, but I will be addressing the one you ask for

I don't want it to display the passed word in the list.

Just skip the first iteration in the relevant loop, e.g. by replacing this:

for i in range(len(letters)):

with this:

for i in range(1, len(letters)):

Upvotes: 0

Nathan
Nathan

Reputation: 3648

You can swap letters like this:

def swap(string, place_1, place_2):
    string = list(string)
    string[place_1], string[place_2] = string[place_2], string[place_1]
    return ''.join(string)

a = '1234'

print(swap(a, 1, 2))
>>> 1324

Upvotes: 0

orlp
orlp

Reputation: 117681

Hint: there are only n - 1 distinct words where one letter of the original word has been swapped. To see why, note that ab only has ba as result.

If a word has the letters are position i and i+1 swapped the letters before i are unchanged and the letters after i + 1 also are unchanged.

def swap(s, i):
    return s[:i] + s[i+1] + s[i] + s[i+2:]

def neighbors(s):
    return [swap(s, i) for i in range(len(s)-1)]

Upvotes: 1

Related Questions