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 [ ]:


In [32]:
def list_of_chars(list_chars):
    """Takes a string or list and returns it backwards
    
    Parameters
    ----------
    Input:
    list_chars: Str/List
    A string of characters, or a list of characters
    revstr: Str
    An empty string
    
    Output:
    revstr: Str
    A sequence of characters, in the reversed order of the initial input
    
    """
    revstr = ""
    if list_chars == None: #If the input is None, return None
        return None
    elif list_chars == ['']: # If input is an empty list, return an empty list
        return ['']
    elif type(list_chars) == list: #If input is a list, return the output as a reversed list
        ln = len(list_chars)
        while ln >= 1: #while the length of the input is greater than 1, loop through the end elements by way of length minus 1
            revstr += list_chars[ln - 1] #and append the indexed values, then reduce the length value by 1 and continue through
            ln -= 1
        return list(revstr) #convert the string to a list if input is a list
    else:
        ln = len(list_chars)
        while ln >= 1:
                revstr += list_chars[ln - 1]
                ln -= 1
        return revstr

In [ ]:


In [33]:
list_of_chars('modern')


Out[33]:
'nredom'

Unit Test

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


In [34]:
# %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.


In [ ]:


In [ ]: