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 we need to do this in-place, it seems we cannot use the slice operator or the reversed function?
    • Correct
  • 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

Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.

Code


In [1]:
def list_of_chars(list_chars):
    # TODO: Implement me
    if li
    return list_chars[::-1]

Unit Test

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


In [3]:
# %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()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-aec48f963aa8> in <module>()
     20 
     21 if __name__ == '__main__':
---> 22     main()

<ipython-input-3-aec48f963aa8> in main()
     16 def main():
     17     test = TestReverse()
---> 18     test.test_reverse()
     19 
     20 

<ipython-input-3-aec48f963aa8> in test_reverse(self)
      6 
      7     def test_reverse(self):
----> 8         assert_equal(list_of_chars(None), None)
      9         assert_equal(list_of_chars(['']), [''])
     10         assert_equal(list_of_chars(

<ipython-input-1-9a9cadce3624> in list_of_chars(list_chars)
      1 def list_of_chars(list_chars):
      2     # TODO: Implement me
----> 3     return list_chars[::-1]
      4 

TypeError: 'NoneType' object is not subscriptable

Solution Notebook

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