Thursday, February 29, 2024
HomeSoftware EngineeringThe right way to Reverse Phrases in Python

The right way to Reverse Phrases in Python

The problem

Full the operate that accepts a string parameter, and reverses every phrase within the string. All areas within the string ought to be retained.


"That is an instance!" ==> "sihT si na !elpmaxe"
"double  areas"      ==> "elbuod  secaps"

The answer in Python code

Possibility 1:

def reverse_words(textual content):
    out = []
    for phrase in textual content.cut up(" "):
    return " ".be a part of(out)

Possibility 2:

def reverse_words(str):
    return ' '.be a part of(s[::-1] for s in str.cut up(' '))

Possibility 3:

def reverse_words(str):
    return " ".be a part of(map(lambda phrase: phrase[::-1], str.cut up(' ')))

Take a look at instances to validate our answer

import check
from answer import reverse_words

@check.describe("Fastened Checks")
def fixed_tests():'Fundamental Take a look at Instances')
    def basic_test_cases():
        check.assert_equals(reverse_words('The fast brown fox jumps over the lazy canine.'), 'ehT kciuq nworb xof spmuj revo eht yzal .god')
        check.assert_equals(reverse_words('apple'), 'elppa')
        check.assert_equals(reverse_words('a b c d'), 'a b c d')
        check.assert_equals(reverse_words('double  spaced  phrases'), 'elbuod  decaps  sdrow')


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments