CPSC150A
Scientific Computing

Activity 15

File I/O

Average File

Write the function average_file(file_name), which has a string parameter that is the name of a file. The file contains only numbers, each on their own line. The function should return a floating point number, which is the average of all of the numbers from the file.

Example

>>> print(open('numbers.txt').read())
1
10
5
3
7
2
9
4
6
8
>>> print(average_file('numbers.txt'))
5.5

Non-Blank Lines

Write a function called non_blank_lines(file_name), which has a string parameter that is the name of a file. The function should return a list of non-blank lines from the file.

Example

>>> print(open('input.txt').read())
spam

2
ham


True
eggs

>>> print(non_blank_lines('input.txt'))
['spam', '2', 'ham', 'True', 'eggs']

Posterize

While you might not recognize the name “posterize,” you probably have seen an example of it. Posterization is a method by which the number of colors in the image is reduced. In the case of the hope poster, it was reduced to a 4 color poster.

Details

Create a program that reads a PPM image file and writes a new PPM image file which is the posterized version of the read file.

To posterize a picture, the program should read the color of a pixel, an RGB triplet, and compute the grayscale value of the pixel by averaging the red, green, and blue values. The program should write a color to the output file based on the average value. For example, if the average value is low, between 0 and 64 for example, then write a dark color to the file.

Example

Hint

  • A PPM image has 3 lines at the beginning which encode meta data for the image. These 3 lines should be copied verbatim into the next image.
  • Recall that you can use the int function to convert a floating point value into an integer.
  • Be careful if you are mixing calls to readline while you are also using the for line in input_file type of loop! The loop is already reading one of the lines for you.

Submission

Please show your source code and run your programs. Only programs that have perfect functionality will be accepted as complete.