Homework Solution

For loops

Problems to be Submitted (18 points)

  1. (6 points)

    for k in range(len(word)): 
        print word[ :1+k]
    
  2. (6 points)

    n = int(raw_input('How many terms? ')) 
    e = 0.0 
    for k in range(n):
        # compute factorial for k as above
        factorial = 1
        for val in range(2,k+1):   # up to but not including k+1
            factorial *= val
        # now add in a new term
        e += 1.0/factorial         # 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 *= k
        # add new term
        e += 1.0/factorial         # note use of float 1.0 in numerator
    

    In either case, the approximation that is computed using only the first 10 terms is 2.71828152557. (That's pretty good, as the actual value of e starts with 2.718281...)

  3. (6 points)
    original = raw_input('Enter numeric string: ')
    base = int(raw_input('What base is the number? '))
    place = 1               # we will start with the one's digit
    total = 0
    original = original[ : :-1]   # reverse for convenience
    for symbol in original:
        total += int(symbol) * place
        place *= base             # next column is worth "base" times more than previous
    print total
    

Extra Credit

  1. (2 points)

    Python does not offer any formal guarantee as to the semantics of looping over a sequence as it is mutated, and the observed behavior might vary from version to version of Python. That said, on our current system we observe the output:

    A 
    C 
    E 
    A 
    E 
    E 
    
    The reason is that the for loop is internally index-based, leading to the following intermediate configurations for the list.
    with ['A', 'B', 'C', 'D', 'E', 'F'], entry is original[0] which is 'A'
    with ['B', 'C', 'D', 'E', 'F', 'A'], entry is original[1] which is 'C'
    with ['B', 'D', 'E', 'F', 'A', 'C'], entry is original[2] which is 'E'
    with ['B', 'D', 'F', 'A', 'C', 'E'], entry is original[3] which is 'A'
    with ['B', 'D', 'F', 'C', 'E', 'A'], entry is original[4] which is 'E'
    with ['B', 'D', 'F', 'C', 'A', 'E'], entry is original[5] which is 'E'

Last modified: Thursday, 16 February 2017