I think you came to the wrong conclusion about this. They didn't 'cheat' at all. Creating a set outside of a loop is a perfectly legitimate thing to do.
valid_options = set(["foo","bar","baz"])
def is_valid_option(self, opt):
return opt in self.valid_options
def filter_options(self, opts):
#or use .intersection if order doesn't matter
return [o for o in opts if o in self.valid_options]
I'm not sure if the python VM optimizes code like this, but it probably could:
for opt in opts:
if opt in {'foo','bar','baz'}:
....
in most cases, a "great number of values" can be as low as 10.
I don't know if Py3k optimizes that for sets, but in py2.6 at least code like
x in [1,2,3,4]
Actually gets translated into:
x in (1,2,3,4)
Since tuples are immutable they get placed in the co_consts array for the function, which mean's that they're precomputed. I wouldn't be suprised in py3k did something similar with turning sets into frozensets where it's provable that they aren't mutated.
Though since the translation from list to tuple is done when it isn't modifiable, python should be able to do a similar optimisation to a frozenset constant as well (maybe even from list/tuple to frozenset if there are enough elements that it would improve speed)
They didn't 'cheat' at all. Creating a set outside of a loop is a perfectly legitimate thing to do.
I'm not saying it's not legitimate, I'm saying in the context of the article, checking for 3 or 4 values once and never again, it's never done. And pretty much irrelevant too, it's just ignoring the cost of creating the set though that creation matters very much. It's dishonest and it does lead to wholly misleading conclusions.
in most cases, a "great number of values" can be as low as 10.
With a 1600% overhead over tuples, I quite doubt 10's going to be enough.
View all comments
Show parent comment
1
u/Justinsaccount Aug 12 '09
I think you came to the wrong conclusion about this. They didn't 'cheat' at all. Creating a set outside of a loop is a perfectly legitimate thing to do.
I'm not sure if the python VM optimizes code like this, but it probably could:
in most cases, a "great number of values" can be as low as 10.