CSE 111, Fall 2000

Great Ideas in Computer Science

Lecture Notes #21 Answers

d)    Suppose that S := 'Computer'.
        For each of the following,
            (i)    What do they compute?
           (ii)    Can you describe what they do in a
                    general way?

    a-    substr(S, 1, 1)
    b-    substr(S, 2, 1)
    c-    substr(S, 1, length(S))
    d-    substr(S, 1, length(S)-1)
    e-    substr(S, 2, length(S)-1)
    f-    substr(S, 2, length(S)-2)

    Answers:

    a-    'C'
            substr(S,1,1) computes the 1st character of S

    b-    'o'
            substr(S,2,1) computes the 2nd character of S

    c-    'Computer'
            substr(S,1,length(S)) computes all of S

    d-    'Compute'
            substr(S,1,length(S)-1) computes all but
                                              the last character of S

    e-    'omputer'
            substr(S,2,length(S)-1) computes all but
                                              the first character of S

    f-    Answer in Lecture Notes #22!  :-)

e)    When you're given a "substr" function,
        and asked what it does, there are 3 possible
        correct answers you can give.

        Only one of them, however, is a good answer.

        E.g., suppose you're asked what

                    substr(S, 1, length(S)-1)

               does.

        You could answer as follows:

    1)    Suppose the input string S = 'Computer'
            Then this outputs 'Compute'

            That's true, but it's only true for one
            particular input value.  It won't tell you
            what the function does when the input
            is something else, say 'Science'.

    2)    You could say that it computes the substring
            of the input string S that begins at the first
            character and has a length = the length of
            the whole string minus 1.

            That's also true, but if you don't already
            know how to do that, this answer won't
            help you "see" what the function does.
            It's just repeating the definition of "substr"
            for this special case.

    3)    The best answer is this:

            It returns all but the last character of S.

            This now easily tells you that if S = 'Science'
            then substr(S, 1, length(S)-1) = 'Scienc'

            It is the most informative answer.

    So, when trying the rest of these exercises (and
    there will be more in Lecture Notes #22), give
    this 3rd kind of answer.


Copyright © 2000 by William J. Rapaport (rapaport@cse.buffalo.edu)

file: 111F00/lecturenotes21ans.30oc00.html