I have a small function that when passed a str that names a file that contains a program; it returns a 2-tuple with the number of the non-empty lines in that program, and the sum of the lengths of all those lines. Here is my current functioning code:
def code_metric(file_name):
line_count = char_count = 0
with open(file_name) as fin:
stripped = (line.rstrip() for line in fin)
for line_count, line in enumerate(filter(None, stripped), 1):
char_count += len(line)
return line_count, char_count
Is there a way to implement this function using functionals such as map, filter, and reduce and small lambdas to pass to these functionals? I could make it work conventionally but having some issue with using functionals. Any help would be great.
1 Answer 1
line_count
can be obtained withlen(lines)
instead of an enumerate.- You use
rstrip
(rightstrip), I think thatstrip
is better as you (probably) don't want to count the blanks of indentation as characters. f
is the standard name for files in Python notfin
- Using list comprehension and a for loop as you do is much more readable than a functional alternative, anyway, down here I show you a functional version:
:
def code_metric(file_name):
with open(file_name) as f:
lines = f.read().splitlines()
char_count = sum(map(len,(map(str.strip,filter(None,lines)))))
return len(filter(None,lines)), char_count
-
\$\begingroup\$ @Caridorc- I tried using the function you gave but it keeps giving me the following error:
char_count = sum(map(len, (map(str.strip(), filter(None, lines))))) TypeError: descriptor 'strip' of 'str' object needs an argument
\$\endgroup\$LucyBen– LucyBen2015年02月08日 19:42:38 +00:00Commented Feb 8, 2015 at 19:42 -
\$\begingroup\$ @LucyBen excuse me, it is fixed now. \$\endgroup\$Caridorc– Caridorc2015年02月08日 19:44:54 +00:00Commented Feb 8, 2015 at 19:44
-
\$\begingroup\$ @Caridorc- Thank you. I've updated the question with your code. The output doesn't match when I ran as the figures are off. I've provided an example of the run as well. Hope that helps. \$\endgroup\$LucyBen– LucyBen2015年02月08日 20:00:15 +00:00Commented Feb 8, 2015 at 20:00
-
\$\begingroup\$ @Caridorc, you're counting un-filtered lines - essentially counting those that are empty too \$\endgroup\$volcano– volcano2015年02月12日 23:08:30 +00:00Commented Feb 12, 2015 at 23:08
Explore related questions
See similar questions with these tags.