Python 在没有内置功能的情况下反转句子中的每个单词 python 同时保持顺序

Python reverse each word in a sentence without inbuilt function python while preserve order

不允许使用“Split()、Reverse()、Join() 或正则表达式” 或任何其他 帮助内置 python 函数

输入如下内容:

"   my name   is scheven     "

输出如下:

"ym eman si nevehcs"

您需要考虑删除输入中的开始、中间、结束空格

我已经尝试了 2 次,但都失败了,我将分享我解决这个问题的尝试,并提出改进它的想法

第一次尝试:

def reverseString(someString):
    
    #lenOfString = len(someString)-1
    
    emptyList = []
    
    for i in range(len(someString)):
        emptyList.append(someString[i])
    
    lenOfString = len(emptyList)-1 
    counter = 0
    while counter < lenOfString:
        if emptyList[counter] == " ":
            counter+=1
        if emptyList[lenOfString] == " ":
            lenOfString-=1
        else:
            swappedChar = emptyList[counter]
            emptyList[counter] = emptyList[lenOfString]
            emptyList[lenOfString] = swappedChar
            counter+=1
            lenOfString-=1
     
    str_contactantion = ""
    #emptyList = emptyList[::-1]
    #count_spaces_after_letter=0       
    for letter in emptyList:
        if letter != " ":
            str_contactantion+=letter
            #str_contactantion+=" "
        str_contactantion+=" " 
              
    return str_contactantion

第二次尝试:

def reverse(array, i, j):
    emptyList = []
    if (j == i ):
        return ""

    for k in range(i,j):
        emptyList.append(array[k])

    start = 0
    end = len(emptyList) -1
    if start > end: # ensure i <= j
        start, end =end, start
    while start < end:
        emptyList[start], emptyList[end] = emptyList[end], emptyList[start]
        start += 1
        end -= 1
    strconcat=""
    for selement in emptyList:
        strconcat+=selement

    return strconcat

def reverseStr(someStr):
    start=0
    end=0
    help=0
    strconcat = ""
    empty_list = []
    for i in range(len(someStr)):
        if(someStr[i] == " "):

            continue

        else:
            start = i
            j = start
            while someStr[j] != " ":
                j+=1
            end = j
            #if(reverse(someStr,start,end) != ""):
            empty_list.append(reverse(someStr,start,end))
            empty_list.append(" ")

            for selement in empty_list:
                strconcat += selement
            i = end + 1


    return strconcat

print(reverseStr("   my name   is scheven     "))

试试这个:

string = "   my name   is scheven     "


def reverseString(someString):
    result = ''
    curr_word = ''
    for i in someString:
        if i == ' ':
            if curr_word:
                if result:
                    result = f'{result} {curr_word}'
                else:
                    result = f'{result}{curr_word}'
                curr_word = ''
        else:
            curr_word = f'{i}{curr_word}'

    return result

print(repr(reverseString(string)))

输出:

'ym eman si nevehcs'

注意: 如果允许使用 list.append 方法,我建议使用 collections.deque,因为它比附加到列表。当然,最后还是要一起加入列表,而且你提到不允许使用str.join,所以这肯定是一个问题。

试试这个:

def reverseString(someString):
    result = ""
    word = ""
    for i in (someString + " "):
        if i == " ":
            if word:
                result = result + (result and " ") + word
                word = ""
        else:
            word = i + word
    return result

然后你可以这样称呼它:

reverseString("   my name   is scheven     ")
# Output: 'ym eman si nevehcs'

以下工作无需管理索引:

def reverseString(someString):
    result = crnt = ""
    for c in someString:
        if c != " ":    
            crnt = c + crnt    # build the reversed current token
        elif crnt:  # you only want to do anything for the first space of many
            if result:
                result += " "  # append a space first  
            result += crnt     # append the current token
            crnt = ""          # and reset it
    if crnt:
        result += " " + crnt
    return result

reverseString("   my name   is scheven     ")
# 'ym eman si nevehcs'