Python Programming Exercises,
Gently Explained
111
assert reverseString('aaazzz') == 'zzzaaa'
assert reverseString('xxxx') == 'xxxx'
Try to write a solution based on the information in this description. If you still
have trouble
solving this exercise, read the
Solution Design and Special Cases and Gotchas sections for
additional hints.
Prerequisite concepts: lists, list(), for loops, range(), len(),
integer division, indexes,
swapping values, join()
Solution Design
Instead of building up a string from the characters in text in reverse order, let’s make our
function first convert the string in text into a list of single-character strings. Python’s list()
function does when we pass it a string. For example, list('Hello') returns the list value ['H',
'e', 'l', 'l', 'o']
. We can assign this list as the new value of text.
Once we have the characters of text in a list, create a for loop that loops over the first half of
the list’s indexes. This can be calculated from the expression len(text) // 2.
We want to replace
the character at each index with the character at the ―mirror‖ index in the second half of the list. The
mirror of the first index is the last index, the mirror of the second index is the second to last index,
the mirror of the third index
is the third to last index, and so on.
To calculate the mirror of an index i in text, you would want len(text) - 1 - i. For
example, the mirror of index 0 is len(text) - 1 - 0, the mirror of index 1 is len(text) - 1
- 1
, the mirror of index 2 is len(text) - 1 - 2, and so on.
Python’s assignment statement allows you to swap two values simultaneously. For example, the
assignment statement myList[0], myList[5] = myList[5], myList[0] swaps the values
at indexes 0 and 5 in a hypothetical myList variable.
Figure 36-1 shows the characters of a hypothetical 12-item list made from 'Hello, world'
being swapped until the string is reversed.
Python Programming Exercises, Gently Explained
112
Figure 36-1: The process of reversing a list of single-character strings by swapping their mirror
indexes.
Finally, the join() string method creates a string from the text list with the instruction
''.join(text)
. This is the string the reverseString() function should return.
Dostları ilə paylaş: