elfs: (Default)
[personal profile] elfs
Sometimes, what I do feels like incantation. I wanted a word count on my "working directory" displays, which I maintain using python scripts. Once upon a time, this would have taken me a few lines. Maybe ten or so. And then I learned Ruby. I learned the difference between a fold, a filter, and a transform. And I learned when to do which.

def wc(f): return Numeric.sum([len(i.split()) for i in open(f, "r") if i])

I don't get paid enough for knowing this stuff.

Date: 2007-03-07 08:45 am (UTC)
From: [identity profile] tamino.livejournal.com
I'm not familiar with the Numeric module -- why not use the built in "sum" function, though?

Also, that's going to be sucking up everything into memory in order to build the result of the list comprehension... your use of the iterator interface on the file objects isn't *intrinsically* inefficient, if you just used a for loop instead of a list comprehension.

Come to think about it, weren't they going to introduce some new syntax for list comprehension generators?

Hm. Why the "if i", btw? Won't all lines from the file be true, since even blank lines have '\n'?

cool, though. :-) I like python, a lot. As well as map, filter, reduce, and list comprehensions (which are really just syntactic sugar for a combination of the first two, anyhow)

Date: 2007-03-07 05:36 pm (UTC)
From: [identity profile] elfs.livejournal.com
I used the Numeric module because it was the first one for which I found documentation. If there's a builtin sum, it's not in my Python reference (which is, admittedly, the New Riders book covering version 2.1).

You're right that the count is broken because of the 'if i' chunk. It doesn't do what I intended it to do (remove nulls caused by splits across multiple whitespaces).

And yes, there are generators in python and they completely rock. In fact, I've written Python-to-HTML and Python-to-JSON that silently swallow generators and functors, calling them directly and further interpreting their output. It's damn near DWIM code.

Profile

elfs: (Default)
Elf Sternberg

December 2025

S M T W T F S
 12345 6
78910111213
14151617181920
21222324252627
28293031   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Dec. 30th, 2025 09:41 pm
Powered by Dreamwidth Studios