Some thougts on cartesian products
aleax at mail.comcast.net
Sun Jan 22 13:41:40 EST 2006
Christoph Zwerschke <cito at online.de> wrote:
> Alex Martelli schrieb:
> > Christoph Zwerschke <cito at online.de> wrote:
> > ...
> >> given length. You could get a 6/49 lotto tip with something like:
> >> choice(set(range(49)).powerset(6))
> > And that would be better than the current random.sample(range(49),6) in
> > WHAT ways, exactly...?
> You're right, random.sample(range(49),6) does the same and much faster.
> I just didn't think of it (it is new since Python 2.3).
Yep, it's one of 2.3's many little gems. Still, builtin set is new in
2.4, so it's hardly a "more classic" approach;-).
> What if you need 12 different tips for your lotto ticket?
You probably want random ones, then...
> s = set(range(49)).powerset(6)
> for x in range(10):
> print s.pop()
This is very systematic, not random;-). Still, using random.sample on s
would indeed produce 12 random different tips!-)
> But the real disadvantage of this idea is the memory consumed and the
> time to set up that memory: set(range(49)).powerset(6) has a cardinality
> of about 13 million entries! You PC would start to swap just for getting
> a lotto tip...
Well then, you need a new PC, 64-bit and with as many GB of RAM as
Until you get such a PC, something like:
tips = set()
while len(tips) < 10:
tip = frozenzet(random.sample(range(49), 6))
will have to suffice, I guess;-).
More information about the Python-list