#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2014
    Posts
    4
    Rep Power
    0

    Smile Please help me with this assignment


    The program reads from a text file called "names.txt" that contains last names, one per line in order to calculate the most common first letter of the names in the file and output that letter to the screen.

    Here is what I have so far:

    Code:
    import string
    
    first_letters = ""
    
    infile = open("names.txt", "r")
    
    for line in infile:
    
        whole_line = line.strip()
    
        first_letter = line[0]
    
        first_letter = first_letter.lower()
    
        first_letters += whole_line[0]
    
    infile.close()
    
    max_count = 0
    
    max_count_letter = 'a'
    
    for letter in string.ascii_lowercase:
    
        letter_count = len(infile)
    
        if letter_count > max_count:
    
            max_count = letter_count
    
            max_count_letter = first_letter
    
    print(max_count_letter)
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    157
    Rep Power
    2
    I think an exercise like this is best suited to a dictionary. That way, you're only keeping track of those letters that are used. Your idea of the lower case is a good one. You can do that in the same statement as the dictionary update. So you would initialize a dictionary outside your reading loop: dLtrs={}. Then, first_letter=line.strip()[0]. Then dLtrs[first_letter.lower()]=dLtrs.get(first_letter.lower(),0)+1.

    Finally, to know the letter used most often: dLtrs.keys()[dLtrs.values().index(max(dLtrs.values()))]
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    428
    Rep Power
    66
    Originally Posted by KyoPhan
    Code:
    import string
    You don’t need this, as you can quite easily see for yourself: not once do you use anything from the “string” namespace.

    Code:
        whole_line = line.strip()
        first_letter = line[0]
        first_letter = first_letter.lower()
        first_letters += whole_line[0]
    I think you’re getting confused here. “line” is the input line, and “whole_line” holds (despite its name) only the stripped-down version of it; then you use both line[0] (which may be a blank character) and whole_line[0] (which is now guaranteed to be non-blank).

    Further, use “with” when opening the file. Much safer and cleaner.
    My armada: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (mini laptop, work laptop), Android 4.2.1 (tablet)

IMN logo majestic logo threadwatch logo seochat tools logo