Homework Solution

Strings and Lists

Problems to be Submitted (20 points)

  1. (10 points)

    Write a program that accepts a sentence from the user on a single line, and which outputs the number of words in the sentence. A sample execution appears as follows:
    Enter a sentence: The quick brown fox jumps over the lazy dog
    You entered 9 words.

    Solution:

    sentence = input('Enter a sentence: ')
    k = len(sentence.split())
    print('You entered', k, 'words.')

  2. (10 points)

    Write a program that prompts the user for a name that is assumed to be of form FirstName MiddleName LastName and which echos the name except with the middle name replaced by the middle initial and a period.

    The precise format should match the following sample session.

    What is your name? Elmer James Fudd
    Elmer J. Fudd

    Solution:

    person = input('What is your name? ')
    pieces = person.split()
    print(pieces[0] + ' ' + pieces[1][0] + '. ' + pieces[2])

    An alternate approach is to avoid the explicit split but to use index to find the locations of the two expected spaces, and then use slicing.

    person = input('What is your name? ')
    j = person.index(' ')
    k = person.index(' ', j+1)   # find second space
    print(person[ :j+2] + '.' + person[k:])
    Look carefully at the limits of the slices used to get all relevant portions of the original text, as with Elmer James Fudd


Last modified: Sunday, 16 September 2018