Reverse words in a given string | Reverse the string ; Check if number of words is even ; Find the middle word ; Starting from the middle start swapping words at jth position and l - 1 - j position ; Check if number of words is odd ; Find the middle word ; Starting from the middle start swapping the words at jth position and l - 1 - j position ; return the reversed sentence ; Driver Code
def RevString ( s , l ) : NEW_LINE INDENT if l % 2 == 0 : NEW_LINE INDENT j = int ( l / 2 ) NEW_LINE while ( j <= l - 1 ) : NEW_LINE s [ j ] , s [ l - j - 1 ] = s [ l - j - 1 ] , s [ j ] NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j = int ( l / 2 + 1 ) NEW_LINE while ( j <= l - 1 ) : NEW_LINE s [ j ] , s [ l - 1 - j ] = s [ l - j - 1 ] , s [ j ] NEW_LINE j += 1 NEW_LINE return s ; NEW_LINE DEDENT DEDENT s = ' getting ▁ good ▁ at ▁ coding ▁ needs ▁ a ▁ lot ▁ of ▁ practice ' NEW_LINE string = s . split ( ' ▁ ' ) NEW_LINE string = RevString ( string , len ( string ) ) NEW_LINE print ( " ▁ " . join ( string ) ) NEW_LINE