HELP Newbie solve this Problem

Andrew Dalke dalke at acm.org
Sun Mar 26 00:51:18 EST 2000


Mark Hathaway wrote:
> I'm probably giving away somebody's homework, but I
> can't allow that stupid Fartran to stand without comparison
> to Python.


Why not?  It's actually rather clear Fortran.

>
>Fortran 27 lines unreadable
>
>Python  53 lines commented
>        22 lines uncommented


But your code has a bug.  Suppose a letter is not
in the document.  Let's assume 'x' doesn't exist,
and you have lookfor = lowercase + uppercase.  I
would like to see, "x 0", but your code does:

>        self.keys.sort()
>        for char in lookfor:
>            if ignoreCase and (char in uppercase):
>                char = lower(char)
>            if char in self.keys:
>                print char, self.charDict[char]

meaning 'x' is not in self.keys, so you don't
produce any output.

And there is another bug with how you do case folding.
Again from that code snippet, you are folding the
character in the "lookfor" string, which was passed in
from the parameter.  Don't you need to add the values
for the lowercase and uppercase elements of the charDict?


Plus, you have a class design which basically fakes
global memory.  IMO, it should look like:

stats = find_char_counts(open("data"))
print_char_counts(stats)

where "find_char_counts" is like your "getText" method,
the value of stats is identical to charDict, and
"print_char_counts" is your "reportCounts" method.  This
is easier to understand (again, IMO) because you have
a "thingy" for parsing, a "thingy" with data, and a
"thingy" for output.  Then the I/O parts can be changed
without having to modify the classes (eg, if you want
to transpose the two columns, just write a new output,
or if you want to generate random character values for
input, just write to the data structure.

BTW, there's a nice idiom in Python to implement the way
you do getText but without the O(n) lookup you have
to see if the character has been initialized:

   for char in self.text:
      self.charText[char] = self.charText.get(char, 0) + 1

This is in the FAQ at http://python.org/doc/FAQ.html#4.7

                    Andrew Dalke
                    dalke at acm.org







More information about the Python-list mailing list