|
| 1 | +# EXAMPLE NUMBER 1 |
| 2 | +def reverser(string1, p1=0, p2=None): |
| 3 | + if len(string1) < 2: |
| 4 | + return string1 |
| 5 | + p2 = p2 or len(string1)-1 |
| 6 | + while p1 < p2: |
| 7 | + aux = string1[p1] |
| 8 | + string1[p1] = string1[p2] |
| 9 | + string1[p2] = aux |
| 10 | + p1 += 1 |
| 11 | + p2 -= 1 |
| 12 | + |
| 13 | +def reversing_words_setence_logic(string1): |
| 14 | + reverser(string1) |
| 15 | + p = 0 |
| 16 | + start = 0 |
| 17 | + final = [] |
| 18 | + while p < len(string1): |
| 19 | + if string1[p] == u"\u0020": |
| 20 | + reverser(string1,start,p-1) |
| 21 | + start = p+1 |
| 22 | + p += 1 |
| 23 | + reverser(string1,start,p-1) |
| 24 | + |
| 25 | + return "".join(string1) |
| 26 | + |
| 27 | +# EXAMPLE NUMBER 2 AND 3 USING PYTHON AWESOMESAUCE |
| 28 | +def reversing_words_setence_py(str1): |
| 29 | + ''' reverse the words in a sentence''' |
| 30 | + words = str1.split() |
| 31 | + rev_set = " ".join(reversed(words)) |
| 32 | + return rev_set |
| 33 | + |
| 34 | +def reversing_words_setence_py2(str1): |
| 35 | + """ |
| 36 | + Reverse the order of the words in a sentence. |
| 37 | + :param string: the string which words will be reversed. |
| 38 | + :return: the reversed string. |
| 39 | + """ |
| 40 | + words = str1.split(' ') |
| 41 | + words.reverse() |
| 42 | + return ' '.join(words) |
| 43 | + |
| 44 | +# EXAMPLE 4, VERY SILLY, USING BRUTE FORCE |
| 45 | +def reverse_words_brute(string): |
| 46 | + """ |
| 47 | + Reverse the order of the words in a sentence. |
| 48 | + :param string: the string which words will be reversed. |
| 49 | + :return: the reversed string. |
| 50 | + """ |
| 51 | + word, sentence = [], [] |
| 52 | + for character in string: |
| 53 | + if character != ' ': |
| 54 | + word.append(character) |
| 55 | + else: |
| 56 | + # So we do not keep multiple whitespaces. An empty list evaluates to False. |
| 57 | + if word: |
| 58 | + sentence.append(''.join(word)) |
| 59 | + word = [] |
| 60 | + # So we do not keep multiple whitespaces. An empty list evaluates to False. |
| 61 | + if word != '': |
| 62 | + sentence.append(''.join(word)) |
| 63 | + sentence.reverse() |
| 64 | + return ' '.join(sentence) |
| 65 | + |
| 66 | +# TESTS |
| 67 | +def test_reversing_words_sentence(): |
| 68 | + str1 = "Buffy is a Vampire Slayer" |
| 69 | + assert(reversing_words_setence_py(str1) == "Slayer Vampire a is Buffy") |
| 70 | + assert(reversing_words_setence_py2(str1) == "Slayer Vampire a is Buffy") |
| 71 | + assert(reverse_words_brute(str1) == "Slayer Vampire a is Buffy") |
| 72 | + assert(reversing_words_setence_logic(list(str1)) == "Slayer Vampire a is Buffy") |
| 73 | + |
| 74 | + print("Tests passed!") |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == '__main__': |
| 78 | + test_reversing_words_sentence() |
| 79 | + |
0 commit comments