logo CodeStepByStep logo

area_codes

Write a function named area_codes that prints information about the most commonly occurring area code in a file of telephone numbers. Your function accepts a string parameter representing a filename of input.

The input file contains a collection of telephone numbers, one per line, in the following format. Each phone number begins with a three-digit area code. You may assume that every line of the file is in exactly the format shown, without any other characters or formatting or spacing, and that every phone number in the file is unique.

650-723-2273
206-685-2181
800-356-9377
800-347-3288
650-725-7411
520-297-6312
206-543-1695
800-266-2278
206-543-2969

Your function should open and read the contents of this input file and figure out which area code occurs most frequently in the data. If multiple area codes are tied for being the most frequent, print the numerically smallest of the ones that tied. For example, in the data at right, the most common area codes are 800 and 206, each of which has 3 phone numbers with that area code, so your function should consider 206 to be the most commonly occurring area code.

After determining which is the most common area code, your function should prout all of the phone numbers from that area code, in sorted numerical order, one per line. For example, if the input above at right comes from a file named phonenumbers.txt, then the call of area_codes("phonenumbers.txt") should print the following console output:

206-543-1695
206-543-2969
206-685-2181

If the file is missing or unreadable, your function should produce no output. If the file exists, you may assume that it contains at least one phone number, that every line of input in the file is in the exact valid format described above, and that every phone number in the file will be unique.

Constraints:

  • You may open and read the file only once. Do not re-open it or rewind the stream.
  • You should choose an efficient solution. Choose data structures intelligently and use them properly.
  • You may create one collection (stack, queue, set, map, etc.) or nested/compound structure as auxiliary storage. A nested structure, such as a set of lists, counts as one collection. A temporary collection variable that is merely a replica or reference to some other collection (such as, v= mylist.remove()) is fine and does not count as a second structure. (You can have as many simple variables as you like, such as ints or strings.)
Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.