Homework Solution

For loops

Problems to be Submitted (20 points)

  1. (5 points)

    Here is a solution using an index-based loop to create slices.

    for i in range(len(word)):
        print word[ :1+i]
    

    Here is a solution that builds up the pieces character-by-character.

    latest = ''	
    for c in word:
        latest += c      # add newest letter to end
        print latest
    
  2. (5 points)
    fact = 1
    for val in range(2,k+1):   # up to but not including k+1
        fact = fact * val
    
  3. (5 points)
    e = 0.0
    for k in range(n):
        # compute factorial for k as above
        fact = 1
        for val in range(2,k+1):   # up to but not including k+1
            fact = fact * val
        # now add in a new term
        e = e + 1.0/fact           # note use of float 1.0 in numerator
    

    We can do even better by not recomputing the factorial from scratch each time, but instead basing it on the previous iteration, as follows.

    e = 1.0         # let's add in first term by hand for 1/0!
    factorial = 1
    for k in range(1,n):   # other n-1 terms
        # update factorial
        factorial = factorial * k
        # add new term
        e = e + 1.0/factorial
    
  4. (5 points)
    original = raw_input('Enter numeric string: ')
    base = int(raw_input('What base is the number? '))
    place = 1                    # we start with the one's digit
    total = 0
    original = original[ : :-1]  # reverse for convenience
    for digit in original:
        total = total + place * int(digit)
        place = place * base
    print total
    

Extra Credit

  1. (2 points)

    byLast = []
    for person in people:
        pieces = person.split()
        byLast.append( (pieces[1], pieces[0]) )    # (lastname,firstname)
    byLast.sort()
    for person in byLast:
        print person[1] + ' ' + person[0]          # back to 'firstname lastname'
    

Last modified: Friday, 05 February 2010