3 ms·
Generally most use this: freqs = {} for c in "abracadabra": try: freqs[c] += 1 except: freqs[c] = 1 If this is
by stcredzero 15y ago
Generally most use this:
freqs = {}
for c in "abracadabra":
try:
freqs[c] += 1
except:
freqs[c] = 1
If this is really the common idiom, I'd say this is a sign that professional programming has yet to fully mature as a field.
Some may say a better solution would be:
freqs = {}
for c in "abracadabra":
freqs[c] = freqs.get(c, 0) + 1
Okay, so I understood immediately what was going on with the 2nd bit of code.
Rather go for the collection type defaultdict
from collections import defaultdict
freqs = defaultdict(int)
for c in "abracadabra":
freqs[c] += 1
As a non-pythonista, the 3rd bit of code, I had to Google "defaultdict" to figure out. It's only a couple of seconds to Google, and a professional should know this tidbit, but it seems like premature optimization to me. This brings to mind this post:
http://news.ycombinator.com/item?id=3995185 http://news.ycombinator.com/item?id=3995185
As a programmer, one's most valuable resource is brainpower. Supposedly, a programmer's most important goal is writing clear code. Look around at what goes on in our industry. There's a lot of our most valuable resource spent on showing off our cleverness, not directed towards the clearest code. To me this is like spending money to show one can spend money or playing an instrument to show off dexterity instead of producing gorgeous sounds.
(I think this starts in school and other environments where one is motivated to show off one's coding chops.)
Most of the complexity in our field accrues like litter: a bit here and a bit there. I think it says something about the culture of the folks who live there.
- nostrademons 15y agoWell, yes, but I'd also like to think that code should raise the level of the programmers reading it. You shouldn't avoid language features just because some people don't know about them. That's as ridiculous as the folks who say "Don't use the ?: operator because folks who haven't taken Intro CS 101 may not be familiar with it." So you spent a couple seconds Googling defaultdict. Great, you now know what a defaultdict is and can use it in your own code. It's useful in a lot of places besides this toy example. You should avoid gratuitous complexity, where you force the reader to learn something that will never, ever be useful to them again. A great example might be writing your own encryption algorithm, which will be complicated, wrong, under-performant, and totally useless on any other project. If you just use bcrypt (or whatever the recommended best practice is now), then your code works well, and all readers of your code now know about bcrypt and can use it themselves.
- stcredzero 15y agoWell, yes, but I'd also like to think that code should raise the level of the programmers reading it...You should avoid gratuitous complexity I have a different set of policies than most programmers, which arises from my observation that our field's priorities are out of whack with the actual cost-benefit. Our greatest costs involve understanding systems, so our first priority should typically be to produce readable and understandable code. You shouldn't avoid language features just because some people don't know about them. One should pick language features to optimize for readability, which is entirely contextual. If your shop has a culture of using ?: to the point where it's like a coding standard then you should keep on doing that. So long as code can be read and understood, programmers will learn. Better yet, if the culture of a shop is that use of language features and other tools are motivated by contextual cost-benefit, then programmers will learn from this example. As it is, programmers generally are more interested in showing off, having fun, and writing things as easily as possible. It's less common to have a culture of prioritizing reading.
- SiVal 15y agoI agree strongly. It amazes me that in the ugly vs. beautiful category, the article uses this as the beautiful: return [i/2 for i in nums if not i % 2] "not i % 2"? That's beautiful? We do a division and ask whether the remainder is not true? What does it mean for a remainder of a division to be not true? Is sqrt(3) untrue? Is 17 not yellow? Is this really the clearest way to say even number? Yes, after years of working in C, I'm well aware of how C does bools, but that's because C's values are small and fast, not beautiful and clear. In C, there's barely any abstraction to leak--you just manipulate bits and don't worry about mixing your metaphors. But Python has different priorities, which is why I prefer it to C when my users (and I) won't be hurt by the performance difference. If we're showing off clarity instead of cleverness, wouldn't this be a better way to demonstrate it: return [i/2 for i in nums if i%2 == 0] And I prefer the concept of "clarity" to "beauty" when it comes to code. Beauty is, well, whatever in the eyes of the beholder. Clarity, for me, is the question of how fast code can be read and understood correctly by a given programmer who is familiar (not more) with the language, not necessarily familiar with other languages, and unfamiliar with what the code does. The faster such a person can skim the code and understand it correctly, the easier it will be to modify and keep free of bugs. If we're so smart, why don't we show it by using our brains to write code that is quicker to read and understand correctly than code written by lesser lights?
- LukeStebbing 15y agoOr just say: from collections import Counter freqs = Counter("abracadabra") I was surprised to see that missing, given that Counter was mentioned in the next section.
- anthonyb 15y agoAh, Guido's time machine strikes again :) Here's my (now mostly obsolete) version: def count(string): counts = {} for item in set(string): counts[item] = string.count(item) return counts print count("abracadabra") I had a look into the collections library, and it just uses iterable.iteritems(). I suspect that this might be faster for larger strings with multiple repeating characters, since set() and count() will pass the string directly to C.
- feral 15y agoI agree with the spirit of your argument. In fact, I almost came here to write a parallel comment: I'm really not sure that reversing the list 'a' with 'a[::-1]' is better than 'reversed(a)', which usually effectively does the same thing, but whose meaning is much more obvious. But, while I agree with your general point, in the specific case of 'defaultdict', I differ. I use 'defaultdict' all the time and I'm glad its there. It feels cleaner than 'freqs.get(c,0)'. I define the default value in one place, and then the interface to my datastructure is simpler; hence as I continue writing, I can spend more of my brainpower in the problem domain. Its a small detail, but its one less thing to think about when writing a complex algorithm.
- stcredzero 15y agoI define the default value in one place, and then the interface to my datastructure is simpler; hence as I continue writing, I can spend more of my brainpower in the problem domain. Actually, this speaks to point: optimization should be for reading, not for writing.
- jsprinkles 15y agoreversed(a) and a[::-1] are not equivalent. The former produces an iterator over the given list (with all the mutability dangers that come with it), while the latter produces a copied list. For plain iteration, you're correct, reversed() is better (similar to how xrange vs. range was back in the day); however, for reversing something and keeping it around, the slice syntax is better. >>> reversed([1, 2, 3]) <listreverseiterator object at 0x107265650> >>> [1, 2, 3][::-1] [3, 2, 1] To clarify your point, list(reversed(a)) and a[::-1] are equivalent. It's a slightly subtle point, but extremely important if you're keeping the result of reversed() around for any length of time. If you're just iterating at the moment that you use it, yes, they're effectively equivalent.
- njharman 15y agolist(reversed(a))