Skip to main content

Exercises 20.9 Exercises

  1. 1.

    A function named reverse takes a string argument, reverses it, and returns the result:
    def reverse(astring):
        """Returns the reverse of `astring`"""
    
    Complete the assert statements in the ActiveCode editor below to create a unit test for reverse. Your asserts should check that reverse works properly for the following test cases (“Input” refers to the value passed as a parameter, and “Expected Output” is the result returned from reverse):
                 Input    Expected Output
                 -------- ---------------
    Test Case 1: 'abc'    'cba'
    Test Case 2: 'b'      'b'
    Test Case 3: ''       ''
    
    Hint.
    If you’re not sure how to get started with this one, review Section 20.5.
    Solution.
    assert reverse('abc') == 'cba'
    assert reverse('b') == 'b'
    assert reverse('') == ''
    
  2. 2.

    A function named stripletters takes a string argument, removes all letters from it, and displays the result (see below). However, this function is not testable.
    Modify the function so that it can be tested with the assert statements that follow.
    Hint.
    Solution.
    def stripletters(msg):
        result = ''
        for ch in msg:
            if not ch.isalpha():
                result += ch
    
        return result
    
You have attempted of activities on this page.