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

Time:11-03

Not allowed to use "Split(),Reverse(),Join() or regexes" or any other helping inbuilt python function

input something like this:

"   my name   is scheven     "

output like this:

"ym eman si nevehcs"

you need to consider removing the starting,inbetween,ending spaces aswell in the input

I have tried 2 tries, both failed i will share my try to solve this and maby an idea to improve it

First try:

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

second try:

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     "))

CodePudding user response:

Try this:

string = "   my name   is scheven     "


def reverseString(someString):
    result = ''
    curr_word = ''
    for i in string:
        if i == ' ':
            if curr_word:
                result = f'{result}{curr_word} '
                curr_word = ''
        else:
            curr_word = f'{i}{curr_word}'
    if result[-1] == ' ':
        result = result[:-1]

    return result

print(repr(reverseString(string)))

Output:

'ym eman si nevehcs'

Note: if you're allowed to use list.append method, I'd suggest using a collections.deque as it's more performant than appending to a list. But of course, in the end you'll need to join the list together, and you mentioned that you're not allowed to use str.join, so that certainly poses an issue.

CodePudding user response:

Try this:

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

You can then call it like this:

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

CodePudding user response:

The following works without managing indices:

def reverseString(someString):
    result = crnt = ""
    for c in someString:
        if c == " ":    
            if crnt:
                if result:
                    result  = " "
                result  = crnt
                crnt = ""
        else:
            crnt = c   crnt
    result  = crnt
    return result

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