[Tutor] How to find optimisations for code
Peter Otten
__peter__ at web.de
Fri Oct 19 14:26:09 EDT 2018
Pat Martin wrote:
> So should we always use sets or dictionaries if possible? Are these more
> efficient because of not keeping track of their position?
Not always. If you want to know how often one entry/char occurs in a linear
storage like a list, a string, or a file, then you can loop over the data:
num_c = some_string.count(c) # the loop is hidden in the count() method
pairs = (line.partition("=")[::2] for line in file)
value = next(value for key, value in pairs if key == wanted_key)
However, if you expect frequent similar questions go with a lookup table:
freq = Counter(some_string)
for c in strings.ascii_lowercase:
print(c, "occurs", freq[c], "times")
lookup = dict(pairs)
for key in wanted_keys:
print(key, "is", lookup.get(key, "unknown"))
Before you start measure if the effort may be worthwhile, i. e. whether the
linear approach causes a relevant delay.
When you're done doublecheck if you got the desired improvement, i. e.
whether you optimised the right place.
More information about the Tutor
mailing list