get method
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Tue Dec 30 04:10:49 EST 2008
James Mills schreef:
> Ross, the others have informed you that you are not
> actually incrementing the count. I'll assume you've
> fixed your function now :) ... I want to show you a far
> simpler way to do this which takes advantage of
> Python's list comprehensions and mappings (which are
> really what dictionaries are):
>
>>>> s = "James Mills and Danielle Van Sprang"
>>>> dict([(k, len([x for x in s if x == k])) for k in s])
> {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm':
> 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1}
Hm, you just changed an O(n) algorithm to an O(n**2) algorithm. No big
deal for short strings, but try your solution on a string with length
10000 and see the difference. On my computer the O(n) version takes
0.008 seconds, while your version takes 8.6 seconds. That's 1000 times
slower.
--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
-- Isaac Asimov
Roel Schroeven
More information about the Python-list
mailing list