[Baypiggies] Question about breaking out of a loop
Jeremy Fishman
jeremy.r.fishman at gmail.com
Tue Jun 7 22:32:44 CEST 2011
Your second and third definitions aren't really different from each other.
Both incur a "per-iteration penalty", the first with an if-statement and
the second with a dictionary lookup.
I bet you are not going to get a noticeable speedup over a simple
if-statement check, but an alternative approach is to solve the problem you
are checking for up-front:
>>> # warning: not a proof
...
>>> def count(seq):
... return sum(1 for e in seq)
...
>>> def f(n, w, t):
... return (c for c in combinations(range(n), w) if c[0] < t)
...
>>> def g(n, w, t):
... for i in range(t):
... for c in combinations(range(i + 1, n), w - 1):
... yield (i,) + c
...
>>> [count(f(10, 5, i)) for i in range(5)]
[0, 126, 196, 231, 246]
>>> [count(g(10, 5, i)) for i in range(5)]
[0, 126, 196, 231, 246]
>>> list(f(5, 3, 2))
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2,
3), (1, 2, 4), (1, 3, 4)]
>>> list(g(5, 3, 2))
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2,
3), (1, 2, 4), (1, 3, 4)]
- Jeremy
On Tue, Jun 7, 2011 at 12:40 PM, Hy Carrinski <hcarrinski at gmail.com> wrote:
> I am working on code to solve a combinatorial probability problem, and
> plan to send a link to the full code in a few days.
>
> There is generator that yields tuples in a defined order into a loop
> that performs a calculation. I would like to provide an option to stop
> the calculation when the threshold is reached.
>
> I have put a simplified sample of this on github:
> https://gist.github.com/1012945
>
> My questions are:
> 1. Is it an antipattern to change a datatype to cause an exception?
> 2. If so, how would you improve on my version 3 function?
>
> The function in version 3 is pretty close to my current solution, but
> the functions combinations(), f() and g() are standing in for more
> computationally intensive functions. The potential antipattern
> involves temporarily setting a value to None in a dictionary of
> integers.
>
> Thank you,
> Hy
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20110607/51203cb7/attachment.html>
More information about the Baypiggies
mailing list