CS 140 - Final Exam Study Questions

Make sure to review quizzes, Codingbat problems, homework, and the review problems we covered in the last class.

String problems

  1. True/False. Strings are a mutable type in Python.
    False. Strings are immutable. That is, they cannot be modified. For example, the second statement below fails and causes an error.
        str = 'hello'
        str[2] = 'x'
      
  2. Write a short Python code segment that prompts the user to enter their name at the keyboard and then prints the length of their name.
        name = raw_input("please enter your name:")
        print "Your name is", len(name), "characters long"
      
  3. Write a short Python code segment that prompts the user to enter their name at the keyboard and then prints the number of vowels in their name.
    Here is a possible solution:
    name = raw_input("please enter your name:")
    vowel_count = 0
    for ch in name.lower():
       if ch in ['a', 'e', 'i', 'o','u']:
          vowel_count = vowel_count + 1
    
    print "Your name has", vowel_count, "vowels in it"
      
  4. Write a short Python code segment that prompts the user to enter their name and prints "has ann" if the name "ann" appears anywhere in their name. For example, the names Anne, Joanne, Joanna, Annette, Adrianne all have "ann" in their name.
        name = raw_input("please enter your name:")
        if "ann" in name.lower():
           print "has ann"
       
    Another solution might be:
        name = raw_input("please enter your name:")
        if name.lower().find("ann") != -1:
           print "has ann"
       
  5. Write a function removeDupes that takes a string as a parameter and returns the string with all spaces removed and duplicate letters removed. For example, removeDupes("banana") returns the string "ban" and removeDupes("python programming") returns the string "pythonrgami"
    def removeDupes(str):
        result = ""
        for ch in str:
            if ch not in result and ch != " ":
               result = result + ch
               
        return result
    
    # Here is an example call of our removeDupes function
    print removeDupes("python programming")    
       
  6. Write a python function initials that takes a string as a paramater that represents a name as "First M. Last" and returns their initials. For example initials("Jane P. Doe") returns the string "JPD". Don't worry about difficult names such as Alexis-Charles-Henri Clérel de Tocqueville
      def initials(name):
        m = name.find(" ") + 1
        l = name.find(" ", m) + 1
        return name[0] + name[m] + name[l]
     
  7. Modify the initials function so that it also works when the name is specified as "Doe, Jane P." and still returns the initials "JPD". Assume that a comma means that the name is being specified as the surname name comes first. For example, initials("Doe, Jane P.")
      # Lets reuse our function from the previous problem
      def initials_fml(name):
        m = name.find(" ") + 1
        l = name.find(" ", m) + 1
        return name[0] + name[m] + name[l]
      
      # Here is the enhanced version that handles
      # "last, first mi." as well. This assumes that
      # there is a space after the comma.
      def initials(name):
        if "," not in name:
           return initials_fml(name)
        else:
            f = name.find(",") + 2
            m = name.find(" ", f) + 1
            return name[f] + name[m] + name[0]
     
  8. What is the output of the following Python program?
      def whatDoIdo(str):
         alphabet = "abcdefghijklmnopqrstuvwxyz"
         tmp = ""  # tmp is initialized to the empty string
         for ch in str:
            x = alphabet.find(ch)
            y = (x + 13) % 26
            tmp = tmp + alphabet[y]
            
         return tmp
        
      print whatDoIdo("clguba") 
      
    Hint: trace the program like we have done many times in class.

    This is another example from cryptography. This is the rotation 13 scheme where we replace a letter with the letter thirteen characters down in the alphabet. If we run out of alphabet then we wrap around to the beginning. For example, 'a' maps to 'n'. The wrap around causes, for example, 'r' to map to 'e'.

    The answer is "python"

  9. Using the definition of whatDoIdo from the previous problem what would be the output of the print statement below
         print whatDoIdo(whatDoIdo("hello"))
      
    This print statement just calls whatDoIdo twice. If you shift a character by 13 two times you just get the original character back. So this print statement would print "hello".
  10. Write a function named scramble that takes a string and scrambles it by randomly reordering the characters in the string. For example, scramble("scramble") might return the string "alsrbcme".
    Here is one of many solutions. This is very similar to the way we shuffled a deck of cards. This solution picks a character at random from the str, appends to a new string, and deletes the character from the string.
    import random
    def scramble(str):
       result = ""
       for i in range(len(str)):
          pos = int(random.random()*len(str))
          result = result + str[pos]
    
          # delete the character we just added to the string
          str = str[:pos] + str[pos+1:]
          
       return result
       

List Problems

  1. True/False. Lists are a mutable type in Python.
    True, lists can be modified. For example,
            l = [1,2,3,4,5]
            l.pop()  # remove the five
            l.pop(0) # remove the first item in the list
            l[1] = 9 # change item at index 1 to 9
          
  2. The following code segment tries to add the first and last items in a list named lst. Does it work? If not what is wrong?
          sum = lst[0] + lst[len(lst)]
        
    The problem is an array index out of range error. The correct way to do this is:
          sum = lst[0] + lst[len(lst) - 1]
          
  3. Write a function that takes a list of numbers and returns the largest number in the list (don't use the builtin function max or the sort function. Use a loop with an if-statement.)
    Here is one solution. This might be how Python's builtin max functionmight even be implemented.
      def max(l):
        current_largest = l[0]
        
        for num in l:
          if num > current_largest:
            current_largest = num
        
        return current_largest
    
        
  4. Write a function named median that takes a list of numbers as a parameter and returns the median of the list.
    Here is a solution that uses the sort function and then picks out the middle item if the list has odd length, otherwise averages the middle two items.
      
    def median(l):
        l.sort()
        if len(l) % 2 == 1:
          return l[len(l)/2]
        else:
          return (l[len(l)/2 - 1] + l[len(l)/2])/2.0
    
    # Here are a couple of example calls to the median function
    # just to test it.
    print "median", median([1,2,3,4,5,6])
    print "median", median([1,2,3,4,5,6,7])
        
  5. Write a function named countEs that takes a list of strings and returns the number of ocurrences of the letter 'e' in the list (upper and lower case). For example,
          print countEs(['hello', 'Eddie', 'the', 'helper'])
        
    should print 6. (Hint: remember the count function for strings?).
    Here's one solution that uses the builtin count function on strings.
    def countEs(l):
        e_count = 0
        for item in l:
           e_count = e_count + item.lower().count('e')
    
        return e_count    
       
  6. How do you add an element to the end of a list?
    Use the append function on lists.
  7. How do you add an element to the beginning of a list?
    Use the insert function. For example:
         l.insert(0, "fred") #insert fred at the beginning of the list.
       
  8. How would you remove the 7th item in a list?
        l.pop(7)
       
  9. Assume we have the list l below:
              l = [1,5,4,2,9,0]
            
    1. What is the output of print len(l)
          6
         
    2. Give an example line of code that would create a list index out of range error for the list l.
      Any index that is greater than or equal to the length of the list will do the job. For example,
            l[len(l)] = 5
         
    3. What is the output of print l.sort() Be careful. Trick question. What is the correct way to print l sorted?
      The sort function for lists returns None. However it modifies the list so it is in sorted order. For example:
          l = [5,4,3,2,1]
          l.sort()
          print l
         
    4. Write a short code segment that adds the largest and the smallest element in the list. (Hint: don't use a loop, but use builtin functions we have covered).
           result = max(l) + min(l)
         
  10. Assume we have a list of strings.
    1. How can we determine the length of the last string in the list?
            result = len(l[len(l) - 1])
         
    2. Assuming the list has an odd length print "has z" if the middle item in the list has a "z" in it.
            if l[len(l)/2].find('z') != -1:
               print "has z"
         
      Another solution might be:
            if 'z' in l[len(l)/2]:
              print "has z"
         
    3. Calculate and print the average length of the strings in the list. For example, if we have a list ["helloooo", "it", "is", "raining"], the average length of a word is 4.75.
      Here's a function avg that will do the trick.
      def avg(l):
        sum = 0.0
        for item in l:
            sum = sum + len(item)
        return sum/len(l)
          
      
      # here is an example call to avg    
      print avg(["helloooo", "it", "is", "raining"])