iterating over strings seems to be really slow?

Chris Angelico rosuav at gmail.com
Wed Aug 27 19:01:46 EDT 2014


On Thu, Aug 28, 2014 at 6:53 AM, Rodrick Brown <rodrick.brown at gmail.com> wrote:
> def wc1():
> word=""
> m={}
> for c in s:
> if c != " ":
> word += c
> else:
> if m.has_key(word):
> m[word] += 1
> else:
> m[word] = 1
> word=""
>
> return(m)

Your code is all buried behind HTML formatting, which makes it hard to read.

But frankly, I would first look at writing correct and idiomatic code,
unless you're doing a direct translation from C or something (in which
case keeping the style as similar as possible to the original makes it
easier to verify). The second function is MUCH clearer than the first.
Don't worry too much about performance until you've checked that one
against some definition of correctness, and then do all your
performance checking with a quick correctness check against the
idiomatic version.

ChrisA



More information about the Python-list mailing list