2 ms·
Yes, it's shorter, but we're not playing golf. It's conceptually pretty much the same, and then you just go with whichever one you came up with first. Yours s
by ColinWright 8y ago
Yes, it's shorter, but we're not playing golf. It's conceptually pretty much the same, and then you just go with whichever one you came up with first.
Yours says:
Convert to lower case
Convert non-letters to CR
The original says:
Convert non-letters to CR
Convert to lower case
Conceptually the same. The point is, most people don't seem to be able to do this at all, although there are many who can tinker with a given solution and improve it around the edges. It's the ability to come up with the initial version that seems to be rare.
- darrenf 8y agoMy first reaction was to wonder why `tr` was required at all - neither conversion struck me as necessary. These days both `sort` and `uniq` can do case-insensitivity: sort -f | uniq -ic So I just allow the shell to do word splitting: for x in `cat foo.txt` ; do echo $x ; done | sort -f | uniq -ic | sort -rn | head -<num>
- ColinWright 8y agoDoesn't that have different behaviour if there is punctuation in the file? On my phone and not in a position to test it, so I'm not sure, but I think it's different.
- darrenf 8y agoIt does indeed. Good catch :)
- xorcist 8y agoDon't abuse command line parameters just to do word splitting. There's at least a dozen obvious ways to do that without leaving your reader guessing what that loop does. Avoid being clever. If you want to change word separators to line separators then just do that (with tr, sed, or some other way) and the purpose will be obvious. And please be mindful of looping over user supplied data like that. Those things are typically the ones that works fine in test but blow up in production. The environment has a maximum size, and you shouldn't store large amounts of data there.
- mannykannot 8y agoIs it really that rare, though, and if so, what makes it rare? I find that when I am doing this sort of thing, the issues seem to be the same as when writing a conventional loop - in this case: Split the stream of text into words. Normalize with respect to case. Accumulate a count of each distinct word. Sort by the counts. Print the number needed. Furthermore, I would guess that the corner cases (such as hyphenated words) are as likely to trip someone up in either approach. Perhaps what makes it rare is not having seen an example before - but one example is enough to demonstrate the principle, thanks to its elegant simplicity. The hard part used to be in remembering which utility has an option that performs the transformation you are looking for, but practice helped with that, especially once one knew enough to guess which utility probably had that feature, at which point one brought up its man page. These days, of course, it is usually easy to search for the solution you want.