codewards 不接受答案 --- 但我的输出符合他们想要的输出

Answer not accepted for codewards --- but my output matches their desired output

这是套路:

来自https://www.codewars.com/kata/5264d2b162488dc400000001/train/python

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"

这是我的代码:

def spin_words(sentence):
    sentence_array = sentence.split()
    new_array = []
    for word in sentence_array:
        if len(word) >=  5:
            word = word[::-1]
            new_array.append(word)
        else:
            new_array.append(word)
    new_sentence = ''
    for word in new_array:
        new_sentence += word + ' '
    
    return new_sentence

无法弄清楚为什么它没有被接受

您的代码的问题是返回的字符串将有尾随空格。使用 [:-1]:

的一片删除它们
def spin_words(sentence):
    sentence_array = sentence.split()
    new_array = []
    for word in sentence_array:
        if len(word) >=  5:
            word = word[::-1]
            new_array.append(word)
        else:
            new_array.append(word)
    new_sentence = ''
    for word in new_array:
        new_sentence += word + ' '
    
    return new_sentence[:-1]

更清洁、更高效的方法:

def spin_words(sentence):
    word_array = sentence.split()
    spin_array = [word[::-1] if len(word) > 4 else word for word in word_array]
    new_sentence = ' '.join(spin_array)
    return new_sentence

你在最后打印额外的 space 这是错误的。

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

我找到了让它通过的答案:

def spin_words(sentence):
sentence = "Hey fellow warriors"
sentence_array = sentence.split()
new_array = []
for word in sentence_array:
    if len(word) >=  5:
        word = word[::-1]
        new_array.append(word)
    else:
        new_array.append(word)
print(new_array)
new_sentence = ' '.join(new_array)
print(new_sentence)
return new_sentence