簡體   English   中英

遍歷字符串並反轉任何包含 5 個或更多字符的單詞 - Codewars Kata

[英]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'))

為 python 編寫 Codewars kata。 需要取一個字符串並反轉任何長度為 5 個或更多字符的單詞。 此代碼適用於單個單詞,但一旦超過一個單詞是 5 個或更多字符,它將為每個后續單詞添加這些單詞。 例如:我的“嘿,戰士們”以“嘿 wollef sroirrawwollef”的形式出現。 我只是不確定為什么要把不同的詞放在一起以及如何解決它。 據我所知,elif 中的 for 循環應該為每個單詞關閉。 我知道這應該很簡單,只是想了解正在發生的事情和原因。 謝謝!

簡單的回答:

你必須清除你的反轉詞:

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

更好的答案:

在 Ignatius Reilly 發表評論后,我的解決方案更加優雅:

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)

是我如何顛倒這個詞。

Output 相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM