How to resolve the algorithm Phrase reversals step by step in the Python programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Phrase reversals step by step in the Python programming language

Table of Contents

Problem Statement

Given a string of space separated words containing the following phrase:

Show your output here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Phrase reversals step by step in the Python programming language

This code implements three different types of string reversals in Python:

  • Character reversal: reverses the order of all the characters in a string.
  • Word character reversal: reverses the order of all the characters in each word in a string.
  • Word order reversal: reverses the order of all the words in a string.

The code first defines three functions that perform these three types of reversals:

  • reversedCharacters(s): reverses the order of all the characters in a string s.
  • wordsWithReversedCharacters(s): reverses the order of all the characters in each word in a string s.
  • reversedWordOrder(s): reverses the order of all the words in a string s.

The main function main tests these three functions on a sample string and prints the results.

The code also defines several helper functions:

  • compose(g, f): composes two functions f and g into a new function that applies f to the argument and then applies g to the result of f.
  • reverse(xs): reverses the order of the elements in a list or string xs.
  • tabulated(s): creates a tabular string representation of a list of values xs, with a heading s, a display function xShow for the values, and a display function fxShow for the results of applying a function f to the values.
  • unwords(xs): joins a list of strings xs into a single space-separated string.
  • words(s): splits a string s into a list of words, using whitespace as the delimiter.

Source code in the python programming language

>>> phrase = "rosetta code phrase reversal"
>>> phrase[::-1]					  # Reversed.
'lasrever esarhp edoc attesor'
>>> ' '.join(word[::-1] for word in phrase.split())	  # Words reversed.
'attesor edoc esarhp lasrever'
>>> ' '.join(phrase.split()[::-1])	                  # Word order reversed.
'reversal phrase code rosetta'
>>>


'''String reversals at different levels.'''


# reversedCharacters :: String -> String
def reversedCharacters(s):
    '''All characters in reversed sequence.'''
    return reverse(s)


# wordsWithReversedCharacters :: String -> String
def wordsWithReversedCharacters(s):
    '''Characters within each word in reversed sequence.'''
    return unwords(map(reverse, words(s)))


# reversedWordOrder :: String -> String
def reversedWordOrder(s):
    '''Sequence of words reversed.'''
    return unwords(reverse(words(s)))


# TESTS -------------------------------------------------
# main :: IO()
def main():
    '''Tests'''

    s = 'rosetta code phrase reversal'
    print(
        tabulated(s + ':\n')(
            lambda f: f.__name__
        )(lambda s: "'" + s + "'")(
            lambda f: f(s)
        )([
            reversedCharacters,
            wordsWithReversedCharacters,
            reversedWordOrder
        ])
    )


# GENERIC -------------------------------------------------


# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    '''Function composition.'''
    return lambda f: lambda x: g(f(x))


# reverse :: [a] -> [a]
# reverse :: String -> String
def reverse(xs):
    '''The elements of xs in reverse order.'''
    return xs[::-1] if isinstance(xs, str) else (
        list(reversed(xs))
    )


# tabulated :: String -> (a -> String) ->
#                        (b -> String) ->
#                        (a -> b) -> [a] -> String
def tabulated(s):
    '''Heading -> x display function -> fx display function ->
                f -> value list -> tabular string.'''
    def go(xShow, fxShow, f, xs):
        w = max(map(compose(len)(xShow), xs))
        return s + '\n' + '\n'.join(
            xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
        )
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )


# unwords :: [String] -> String
def unwords(xs):
    '''A space-separated string derived from a list of words.'''
    return ' '.join(xs)


# words :: String -> [String]
def words(s):
    '''A list of words delimited by characters
       representing white space.'''
    return s.split()


if __name__ == '__main__':
    main()


  

You may also check:How to resolve the algorithm Guess the number/With feedback step by step in the Go programming language
You may also check:How to resolve the algorithm Averages/Mean angle step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm LZW compression step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Arithmetic/Complex step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm XML/Output step by step in the Nim programming language