Homework Solution

Using Python's Built-in Types

Problems to be Submitted (18 points)

  1. (4 points)
    friends.sort()
    print friends[1]	
    
  2. (4 points)
    stringA == stringB.capitalize()
    
  3. (5 points)

    We describe two different ways of doing this. First we make use of splitting the original string into a list, to efficiently identify the three components of the name. In particular, the middle name will have index 1 of that list.

    pieces = person.split(' ')
    pieces[1] = pieces[1][0] + '.' # first character of second piece, then '.'
    name = ' '.join(pieces)
    

    If we do not make use of the list class, the alternate is to identify the locations of both of the spaces, and to then to concatenate appropriate slices of the original string.

    firstSpace = person.index(' ')
    secondSpace = person.index(' ', firstSpace + 1)
    name = person[:firstSpace+2] + '.' + person[secondSpace:]
    

  4. (5 points)
    1. ['Do', 'Re', 'Mi'].join('-')
      

      An AttributeError occurs. The join method cannot be invoked upon a list instance; it is a method of the str class. A proper example of its usage is '-'.join(['Do', 'Re', 'Mi']).

    2. 'High' + 5
      

      A TypeError occurs. There is no definition for adding a string and an integer.

    3. ['Do', 'Re', 'Mi'].insert('Fa')
      

      A TypeError occurs. The insert method expects two parameters. The first must be an index into the list at which a new element is to be placed, and the second must be that new element. In this case, we have only sent the new element.

    4. 'hello'.remove('a')
      

      An AttributeError occurs. A string does not support a method named remove.

    5. list('hello').remove('a')
      

      A ValueError occurs. Although the list supports the remove method, the particular value of the parameter was not found in that list.


Extra Credit

  1. (2 points)

    firstIndex = groceries.index('milk')
    secondIndex = groceries.index('milk', firstIndex + 1)
    groceries.pop(secondIndex)
    

Last modified: Thursday, 26 January 2017