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.

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:

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

``````    lstNums=[]
f=open(<filename>)
for i in f:
lstNums+=i.strip('\n').split()
lstNums=map(int,lstNums)
average=reduce(lambda x,y: x+y,lstNums)/len(lstNums)
``````

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]
``````

wonderful information share here thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.