Created
July 2, 2016 22:05
-
-
Save paridin/e7dffbc57e19a2056872b7bc6a99de64 to your computer and use it in GitHub Desktop.
Algorithms practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| """ | |
| Problem, Given a phrase, reverse every word preserving the order in the sentences | |
| You could not use functions from the language. | |
| Example | |
| Input: Hello World From Mexico City | |
| Output: olleH dlroW morF ocixeM ytiC | |
| First Version: 2 Julio 2016 | |
| """ | |
| # allow print() in python 2.x otherwise it fails | |
| from __future__ import print_function | |
| def phrase2reverse(string): | |
| """ | |
| Reverse an string without python libraries. | |
| :param string: | |
| :return: | |
| """ | |
| reverse = "" | |
| index = len(string) | |
| for s in string: | |
| index -= 1 | |
| reverse += string[index] | |
| return reverse | |
| def to_output(list_phrases): | |
| """ | |
| Generate the expected output | |
| :param list_phrases: | |
| :return: | |
| """ | |
| output = "" | |
| for index, phrase in enumerate(list_phrases): | |
| if index == 0: | |
| output += "{}".format(phrase) | |
| else: | |
| output += " {}".format(phrase) | |
| return output | |
| def text2reverse(text, sep=" "): | |
| """ | |
| Reverse a text without library without python libraries. | |
| :param text: | |
| :param sep: | |
| :return: | |
| """ | |
| list_phrases = [] | |
| phrase = "" | |
| for char in text: | |
| if char == sep: | |
| list_phrases.append(phrase2reverse(phrase)) | |
| phrase = "" | |
| else: | |
| phrase += char | |
| list_phrases.append(phrase2reverse(phrase)) | |
| return to_output(list_phrases) | |
| print(text2reverse("Hello World From Mexico City", sep=" ")) # sep " " is default so you can ommit it. | |
| # output: olleH dlroW morF ocixeM ytiC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment