1

I'm trying to map a list of lines into tuples with line number and line length. My instructions require me to use the map, filter, and reduce functionalities in Python.

So far I've got filter, which is here.

def code_metric(file):
    x = filter(lambda x : x != "\n", open(file))
    y = map(lambda x: )

Sample of how it should look like ...

(1, # of chars in line)

I'm having trouble mapping the list into line numbers and line length using the map function.

2
  • you want to calculate the length of a line and store it in a tuple with the iteration number?
    – letsc
    May 5, 2015 at 0:35
  • Yes. I've got this so far ... tester = map(lambda x : (x[0] + 1, len(x[1])), enumerate(txt)) May 5, 2015 at 0:41

3 Answers 3

0

try like this:

map(lambda x:(x[0], len(x[1])), enumerate(open('your_file'), start=1))
0
0

This is the solution I ended up getting after your guys' answer helped me deduce it.

filtered = map(lambda x : (1, len(x.strip('\n'))), mapper)

The first value in the tuple was supposed to be default '1' (sorry guys!)

0
def code_metric(file):
    with open(file, 'r') as f:
        metric = list(enumerate(map(len, f), 1))
    return metric

This function will do what you want. Could you explain how lambda and reduce could be relevant to this functionality?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.