The project is:

Write a program that computes and prints the average of the numbers in a text file. You should make use of two higher-order functions (i.e., map and reduce, or something else) to simplify the design.

Create a text file and name as numbers.txt and add the following data:

45 66 88

100 22 98

I know multiple ways to easily get the average, but I've been really confused as to how I should implement any higher-order functions into a code that would satisfy this project. Please help.

5 Years
Discussion Span
Last Post by hayatkhansum

Well, "map()" is going to be useful to make the strings you read from the file into numbers. I wouldn't use "reduce()" in this case but I think "sum()" qualifies as "higher order". So it looks like each line of the file has several numbers (and a linefeed). So for each line gets split, stripped, and concatenated into a list of string representations of numbers:

[edit]I guess you could use "reduce()" just show how clever you are:

    for i in f:
    average=reduce(lambda x,y: x+y,lstNums)/len(lstNums)

Edited by rrashkin: On second thought...


Strangely enough, both map() and reduce() have been slated to go away with Python3. However, at present time they are still kept around.
reduce() can be found in module functools and map() can be replaced with a simple list comprehension.

def map(f, s): return [f(x) for x in s]

Edited by HiHe

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.