简体   繁体   中英

Iterate through a string and reverse any word with 5 or more characters - Codewars Kata

def spin_words(sentence):
        words = sentence.split(' ')
        newwords = []
        reverse = []
        for word in words:
                if len(word) < 5:
                        newwords.append(word)
                elif len(word) >= 5:
                        newword = list(word)
                        for letter in newword:
                                reverse.insert(0, letter)
                        newwords.append(''.join(reverse))
        return ' '.join(newwords)

print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))

Working on a Codewars kata for python. Need to take a string and reverse any words that are 5 or more characters long. This code works for single words, but once more than one word is 5 or more characters, it adds those words together for each following word. Ex: my 'Hey fellow warriors' comes back as 'Hey wollef sroirrawwollef'. I am just not sure why is is putting different words together and how to fix it. As far as I know, the for loop in the elif should close out for each word. I know it should be simple, just trying to learn what's happening and why. Thank you!

Simple answer:

You have to clear your reversed word:

def spin_words(sentence):
        words = sentence.split(' ')
        newwords = []
        reverse = []
        for word in words:
                if len(word) < 5:
                        newwords.append(word)
                elif len(word) >= 5:
                        newword = list(word)
                        for letter in newword:
                                reverse.insert(0, letter)
                        newwords.append(''.join(reverse))
                        reverse = [] # Clear the list.
        return ' '.join(newwords)

print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))

Output:

emocleW
to
sraWedoC
Hey wollef sroirraw

Nicer answer:

After Ignatius Reilly's comment I made my solution a bit more elegant:

def spin_words(sentence):
    words = sentence.split(' ')
    newwords = []
    for word in words:
        if len(word) >= 5:
            word = word[::-1]
        newwords.append(word)
    return ' '.join(newwords)

Here is how I reversed the word.

Output is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM