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.

Recommended Answers

All 7 Replies

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:

    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

I was working on a similar assignment where I had to compute the average of numbers from a text file using higher-order functions like map() and reduce(). I was really stuck on how to incorporate them meaningfully, but I finally figured it out.

Here's how I approached it using Python:

from functools import reduce

with open('numbers.txt', 'r') as file:
    content = file.read()

number_strings = content.split()
numbers = list(map(int, number_strings))
total = reduce(lambda x, y: x + y, numbers)
average = total / len(numbers)

print("Average:", average)

This worked perfectly for the numbers in the file and helped me understand how to use functional programming in a real example.

commented: Feel free to link to other websites in your forum signature (in control panel) +34

I don't know why you would use reduce and lambda when you could just do

sum(numbers)

And the directive

You should make use of two higher-order functions (i.e., map and reduce, or something else) to simplify the design.

is self-contradictory as using map and reduce instead of sum does not simplify the design. It complicates it. That goes against the core principles of Python. If that was a school assignment then the teacher is teaching it poorly. Malpractice makes malperfect. Good programming habits should be taught from the start.

commented: I think you’re being pretty tough on someone trying to learn. Why put them down? -8
commented: That's sums up. +17

Why put them down?

Please explain to me how anything I said was a put down. If someone told me their methof of counting cows was "count the number of legs and divide by four", I would point out that it would be simpler just to count the number of cows. If I said "That's stupid, just count the cows", then that would be a put down. What I did was to advocate for simple over complex.

I think you are being too quick to downvote.

commented: And then I googled "3 legged cow". So would they call this a three quarter cow? +0

First of all, let me be blunt. I believe that Enzo only resurrected a 12 year old thread with the intent of spamming. You and I know that because, as moderators, we see in his profile his spamming attempts and his infractions. However, no one else coming across this thread sees that or knows that, so the other 2000 people reading this thread may look at his post through a completely different lens than you or I.

My downvote was for the benefit of all of those people. I want us to be known as a friendly community where newbies can feel welcome to post anything and there are no dumb questions and no one should ever be made to feel dumb for any code they post, no matter how wrong it might be. I feel like your comment accusing their teacher of teaching it poorly, and then preaching "malpractice makes malperfect", etc. could be taken the wrong way. For example, what do you expect a student to do with being told, "Good programming habits should be taught from the start"? Are they meant to respond in agreement? It can potentially come across as being chastised for doing something that their teacher taught them. My most important thing here is that your response is never for the one person you're responding to, but always for the thousands of people who come after and read what you have to say. Newbies who come across moderators saying things like this can make them feel intimidated to sign up and ask their own questions or post their own code for fear of being made to look stupid.

I think you’re being pretty tough on someone trying to learn. Why put them down?

I think that it is a fair statement to make that accusing someone of poor coding habits is putting them down. It's certainly not motivational. There’s a gentler way of saying it without spitting out mantras like malpractice makes malperfect, which IMHO has a condescending undertone. That's my personal opinion, and hence my personal downvote.

That being said, I would prefer to continue this discussion offline because I very much don't want to derail this topic any further than it already has.

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.