不接受codewards的回答,但我的输出与他们期望的输出匹配

2024-09-24 22:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这是卡塔:

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

很难弄清楚为什么不被接受


Tags: ofintestnewstringismorethis
3条回答

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

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

您在末尾打印了额外的空格,这是错误的

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)

代码的问题是返回的字符串后面会有一个空格。通过使用[:-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

相关问题 更多 >