functional programming - Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting? -


I have written a simple script to solve "logic puzzle", the type of puzzle from school where you have many rules and Then the problems should be able to find solutions such as "A, B, C, D, and E are five musicians playing in a concert, each plays one after the other ... if ABC goes first , And D is not the last ... who is the order of whose plays? "Etc. To evaluate possible solutions, I wrote each "rule" as a separate function that would evaluate that possible solutions (only representation in the form of strings) are valid, for example

  #Fifth slot B or DDR rule1 (solution) should be: Return solution [4] == 'B' or solution [4] == 'D' # There should be at least two spots between A B DR Rule 2 (Solution): Returns ABS (Solutions.ind Bus (A) - Smadhankindaks ( 'B')) & gt; = 2 # ATC ...  

I am interested in finding the pithic ways to test if the possible solution passes through all such rules, first to evaluate the rules after failure Capacity First of all, I wrote the simplest thing:

  def is_valid (solution): return rule 1 (solution) and rule 2 (solution) and rule 3 (solution) and ...  

But it seemed to be much worse. I thought maybe I could make it a little more beautiful with something like a list ...

  def is_valid (solutions) rule = [rule1, rule2, rule 3 , Rule 4, ...]  

...

... return to [[r [solution] but then I realized that since the understanding of the list occurs before all (), the function is evaluated, it lacks that it is not being low-circuit - evaluating each rule Or even if the first return False

is: true / false is a more phonetic / functional way to be able to evaluate a list of expressions, for a short time Short-Circuiting Returns F1 (S) and F2 (S) and F3 (S) List without the need to write ... ?

use:

  rule = [rule 1, rule 2 , Rule 3, rule 4, ...] rules_generator = (for the sake of f (in the rules) Return all (rules_generator)  

Syntactic Chinese: You can leave additional parentheses

  Rule = [Rule 1, rule 2, rule 3, rule 4, ...] All Returns (R (Solution) Rules f)  

A generator (originally) is an object with a .next () method, which gives it to the next item in something iterable. This means that they can do useful things like reading a file without having to load it all in memory, or iterating huge integers. You can recycle them with for with loops; Python manages the rear views, for example, there is a generator in category Py3k.

You can roll your own custom generator expression using return instead of yield statement in a function:

  def integers (): i = 0 while true: yield i  

and the python will save the status of the function and expeditiously. They are awesome!


Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -