Search code examples
python-3.6traversal

Reverse each word except punctuation(s) without altering their position - Python3


I am trying to solve a problem with the below #PROBLEM DEFINITION -

  1. Reverse each word in the input string.
  2. The order of the words will be unchanged.
  3. A word is made up of letters and/or numbers.
  4. Other characters (spaces, punctuation) will not be reversed.

However, I am not able to satisfy the requirement of keeping the order enacted. Below is my code. Any help would be appreciated.

Provided: input string = 'Hello! cu2 Ayaan...'

Expected: output string = 'olleH! 2uc naayA...'


def swap(a, b):
    return b, a

def reverse_each_word(sentence):
    list_of_string = [i for i in sentence]
    r = len(list_of_string) - 1
    l = 0
    while l < r:
        if not list_of_string[l].isalpha():
            l += 1
        elif not list_of_string[r].isalpha():
            r -= 1
        else:
            list_of_string[l], list_of_string[r] = swap(list_of_string[l], list_of_string[r])
            l += 1 
            r -= 1
    result = "".join(list_of_string)
    return result

Solution

  • Good effort. You are almost there. Congrats. I did minimal changes in your code. All I did is I split up the sentence into words (and then split each character of the word) and applied your reversal logic to every split word-list. There was also a check missing ..isdigit() since as per prerequisite 3 a word can be composed of alphabets as well as a digit. That's all. Rest is your code.

    I have assumed that words are separated by 1 and only 1 blank spaces. If not please use re module.

    Below is the code. If you don't understand anything, please ask.

    def swap(a, b):
        return b, a
    
    def reverse_each_word(sentence):
        list_of_string = [i for i in sentence.split(" ")]
        Finalresult = ""
        for eachString in list_of_string:
            eachString = [x for x in eachString]
            r = len(eachString) - 1
            l = 0
            while l < r:
                if not (eachString[l].isalpha() or eachString[l].isdigit()):
                    l += 1
                elif not (eachString[r].isalpha() or eachString[r].isdigit()):
                    r -= 1
                else:
                    eachString[l], eachString[r] = swap(eachString[l], eachString[r])
                    l += 1 
                    r -= 1
            result = "".join(eachString)
            Finalresult += (result+" ")
        return Finalresult
    
    print(reverse_each_word( 'Hello! cu2 Ayaan...'))
    

    The output is

    olleH! 2uc naayA...