HELP Newbie solve this Problem
Andrew Dalke
dalke at acm.org
Sun Mar 26 06:45:54 EST 2000
David Fisher gave a solution
>import string,operator;ldict={};map(lambda
>letter:operator.setitem(ldict,letter,0),map(chr,range(256)));map(lambda
>letter:operator.setitem(ldict,letter,ldict[letter]+1),open('data?').read())
;
>print string.join(map(lambda letter:letter+'
>'+`ldict[letter]`,string.lowercase),'\n')
Ahh, c'mon. You can do better than that. I count 279 characters
in that solution. Here's one in one line and 167 characters
(with several bugs introduced since the original post did smell
like a homework problem):
exec "import string;v=[0]*26
for c in map(ord,string.lower(open('data').read())):
if c >= 64 and c <= 89: v[c-64]=v[c-64]+1
for i in range(1,26):print chr(i+64),v[i]
"
Note that for Usenet purposes, I replaced the "\n" characters with
line breaks. BTW, in spirit this is similar to the FORTRAN code,
since it doesn't use a dictionary for the values.
Or the more obscure but only making one full copy of the
data rather than the two above (via map(ord, ...) and string.lower)
here is a 216 byte solution with at least three introduced
bugs:
exec "import string;s=string;t=['@']*256
t[65:91]=t[96:122]=list(s.lowercase);v=[0]*27
for c in s.translate(open('data').read(),s.join(t,'')):
v[ord(c)-64]=v[ord(c)-64]+1
for i in range(26):print chr(i+64),v[i]
"
Using the same tricks to your code yields 207 characters:
import string,operator;d={};s=string;t=operator.setitem;map(lambda
l:o(d,l,0),map(chr,range(256)));map(lambda
l:o(d,l,d[l]+1),open('data?').read());
print s.join(map(lambda l:l+' '+`d[l]`,s.lowercase),'\n')
Hmm, and using perl (again, there are bugs, some deliberate, but
I didn't even test a working solution first nor have I done much
perl programming in the last two years):
perl -e 'open(F, ">>data");foreach (<F>) {\
s/([a-zA-Z])/$d{lc($1)}++/ge } \
foreach ("A".."Z"){print "$_ $d{$_}\n"}'
or about 127 characters. The wonders of automatic hash creation
with automatic element creation with default values of 0. And
of having a ++. And a larger default library. If I did the
file read right, it's line-at-a-time, so should also be less of
a memory hog than a full read() used in the Python examples.
Andrew
dalke at acm.org
More information about the Python-list
mailing list