Homework Solution

More Control Structures

Problems to be Submitted (20 points)

  1. (5 points)
    1. 1 adieu
      answer is initialized to 1. Since there is one 'a', we enter the first if body. Since there is not an 'o', the second conditional fails, and there is no else clause for it. Therefore, answer remains 1.

    2. 4 aloha
      answer is initialized to 1. Since there are two of 'a', the original conditional fails, and we procede to the elif test. Since length is five, this succeeds and answer is set to 4.

    3. 1 bonjour
      answer is initialized to 1. Since there are no 'a' occurrences, the original conditional fails and we procede to the elif test. Since length is 7, this fails as well and so answer remains 1.

    4. 2 ciao
      answer is initialized to 1. Since there is one 'a', we enter the first if body. Since there is an 'o', the second conditional succeeds. This leads to the third nested condition, which succeeds since this ends with 'o', leading to answer of 2.

    5. 1 dia duit
      answer is initialized to 1. Since there is one 'a', we enter the first if body. Since there is not an 'o', the second conditional fails, and there is no else clause for it. Therefore, answer remains 1.

  2. (5 points)
    for i in range(len(indonesian)):
        if indonesian[i] == 'java':
            indonesian[i] = 'python'
    
  3. (5 points) There are many possible ways to do this. items.count can be used to check whether something has two or more occurrences. The challenge is to avoid printing such an item more than once. One approach would be to keep an auxiliary list to record the items that have already been printed. This code might be written as
    printed = []              # empty list originally
    for obj in items:
        if items.count(obj) > 1 and obj not in printed:
            print obj
            printed.append(obj)
    
    An alternative is to make sure to only print out the leftmost occurrence of each element. This can be checked by using the items.index method, yet to do this, we must formulate our loop over the integer indices rather than over the objects themselves.
    for i in range(len(items)):
          if items.count(items[i]) > 1 and items.index(items[i]) == i:
              print items[i]
    
  4. (5 points)
    result = [x + 0.5 for x in range(1,10) ]
    

Extra Credit

  1. (2 points)

    rnaList = [ rnaCode[dnaCode.index(base)] for base in dna ]
    

Last modified: Friday, 12 February 2010