This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Challenge Notebook

Problem: Implement a function to reverse a string (a list of characters), in-place.

Constraints

  • Can I assume the string is ASCII?

    • Yes
    • Note: Unicode strings could require special handling depending on your language
  • Since Python string are immutable, can I use a list of characters instead?

    • Yes

Test Cases

  • None -> None
  • [''] -> ['']
  • ['f', 'o', 'o', ' ', 'b', 'a', 'r'] -> ['r', 'a', 'b', ' ', 'o', 'o', 'f']

Algorithm

If you finish this quickly, try implementing three different ways.

Code


In [21]:
def list_of_chars(list_chars):
    if list_chars:
        return list_chars[::-1]
    else:
        return None

In [47]:
for x in range(10):
    if x > 5:
        print(x, 'hi')
        if x % 2 == 0:
            print(x, 'ho')
        else:
            print(x, 'di')


6 hi
6 ho
7 hi
7 di
8 hi
8 ho
9 hi
9 di

Unit Test

The following unit test is expected to fail until you solve the challenge.


In [23]:
# %load test_reverse_string.py
from nose.tools import assert_equal


class TestReverse(object):

    def test_reverse(self):
        assert_equal(list_of_chars(None), None)
        assert_equal(list_of_chars(['']), [''])
        assert_equal(list_of_chars(
            ['f', 'o', 'o', ' ', 'b', 'a', 'r']),
            ['r', 'a', 'b', ' ', 'o', 'o', 'f'])
        print('Success: test_reverse')


def main():
    test = TestReverse()
    test.test_reverse()


if __name__ == '__main__':
    main()


Success: test_reverse

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.