Popular recipes tagged "algorithm"http://code.activestate.com/recipes/tags/algorithm/2017-05-12T10:40:58-07:00ActiveState Code Recipesgroupby() For Unsorted Input (Python) 2017-05-12T10:40:58-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580800-groupby-for-unsorted-input/ <p style="color: grey"> Python recipe 580800 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/datastructures/">datastructures</a>, <a href="/recipes/tags/generators/">generators</a>, <a href="/recipes/tags/grouping/">grouping</a>, <a href="/recipes/tags/lazy/">lazy</a>). </p> <p>We all know the <code>groupby()</code> which is available in the <code>itertools</code> standard module. This one yields groups of consecutive elements in the input which are meant to be together in one group. For non-consecutive elements this will yield more than one group for the same key.</p> <p>So effectively, <code>groupby()</code> only reformats a flat list into bunches of elements from that list without reordering anything. In practice this means that for input sorted by key this works perfect, but for unsorted input it might yield several groups for the same key (with groups for other keys in between). Typically needed, though, is a grouping with reordering if necessary.</p> <p>I implemented a likewise lazy function (yielding generators) which also accepts ungrouped input.</p> Reversi Othello (Python) 2016-09-19T18:03:09-07:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/580698-reversi-othello/ <p style="color: grey"> Python recipe 580698 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/ai/">ai</a>, <a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/game/">game</a>, <a href="/recipes/tags/games/">games</a>). </p> <p>Reversi/Othello Board Game using Minimax, Alpha-Beta Pruning, Negamax, Negascout algorithms.</p> Simple Infix Expression Evaluation (Python) 2015-11-07T18:44:05-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/579122-simple-infix-expression-evaluation/ <p style="color: grey"> Python recipe 579122 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/stack/">stack</a>). </p> <p>Simple infix expression evaluation using a stack.</p> Hopfield Artificial Neural Network (C++) 2016-07-03T21:58:49-07:00Jay ballerhttp://code.activestate.com/recipes/users/4194368/http://code.activestate.com/recipes/580688-hopfield-artificial-neural-network/ <p style="color: grey"> C++ recipe 580688 by <a href="/recipes/users/4194368/">Jay baller</a> (<a href="/recipes/tags/ai/">ai</a>, <a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/artificial_intelligence/">artificial_intelligence</a>, <a href="/recipes/tags/neural_network/">neural_network</a>). </p> <p>(Discrete (Binary)) Hopfield Artificial Neural Network (ANN).</p> <p>For more info see:</p> <p><a href="http://en.wikipedia.org/wiki/Hopfield_net" rel="nofollow">http://en.wikipedia.org/wiki/Hopfield_net</a></p> <p><a href="http://www.scholarpedia.org/article/Hopfield_network" rel="nofollow">http://www.scholarpedia.org/article/Hopfield_network</a></p> Computing simple list functions recursively (Python) 2016-03-01T20:41:13-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580617-computing-simple-list-functions-recursively/ <p style="color: grey"> Python recipe 580617 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/lists/">lists</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/recursion/">recursion</a>, <a href="/recipes/tags/recursive/">recursive</a>). </p> <p>This recipe shows how to compute some simple list functions (functions that operate on lists) using simple recursive algorithms. Simple non-recursive algorithms exist for these tasks; this recipe is just for illustrative purposes. However, the principles described can be used for more complex recursive algorithms, for which non-recursive algorithms might be more complex than the recursive ones.</p> Infix Expression Evaluation (Python) 2015-11-08T05:08:26-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/579123-infix-expression-evaluation/ <p style="color: grey"> Python recipe 579123 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/stack/">stack</a>). </p> <p>Infix expression evaluation using two stacks.</p> Flattening an arbitrarily nested list in Python (Python) 2014-10-05T21:44:45-07:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/578948-flattening-an-arbitrarily-nested-list-in-python/ <p style="color: grey"> Python recipe 578948 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/flatten/">flatten</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/lists/">lists</a>, <a href="/recipes/tags/python/">python</a>). </p> <p>This is a recipe to flatten a Python list which may have nested lists as items within it. It works for lists that have a maximum depth of nesting roughly equal to the recursion depth limit of Python, which is set to 1000 by default, though it can be increased with sys.setrecursionlimit().</p> Extended Euclidean Algorithm (Python) 2016-03-03T07:12:28-08:00Samuel James Ericksonhttp://code.activestate.com/recipes/users/4187478/http://code.activestate.com/recipes/578631-extended-euclidean-algorithm/ <p style="color: grey"> Python recipe 578631 by <a href="/recipes/users/4187478/">Samuel James Erickson</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/common/">common</a>, <a href="/recipes/tags/discrete/">discrete</a>, <a href="/recipes/tags/divisor/">divisor</a>, <a href="/recipes/tags/euclid/">euclid</a>, <a href="/recipes/tags/extended/">extended</a>, <a href="/recipes/tags/gcd/">gcd</a>, <a href="/recipes/tags/greatest/">greatest</a>, <a href="/recipes/tags/logarithm/">logarithm</a>). Revision 2. </p> <p>given input of integers a and b, this program returns GCD(a,b) along with integers x and y such that ax+by=GCD(a,b).</p> Finding sets in the card game SET! (Python) 2013-04-05T12:49:36-07:00Sander Evershttp://code.activestate.com/recipes/users/4173111/http://code.activestate.com/recipes/578508-finding-sets-in-the-card-game-set/ <p style="color: grey"> Python recipe 578508 by <a href="/recipes/users/4173111/">Sander Evers</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/optimization/">optimization</a>, <a href="/recipes/tags/search/">search</a>, <a href="/recipes/tags/setgame/">setgame</a>). Revision 2. </p> <p>In the card game <a href="http://en.wikipedia.org/wiki/Set_%28game%29">SET!</a>, players are shown an array of 12 (or more) symbol cards and try to identify a so-called 3-card <strong>set</strong> among these cards as quickly as possible.</p> <p>A card has four attributes (number, shape, color and shading), each of which can take 3 possible values. In a <strong>set</strong>, for each attribute, all three cards should have either the same value, or the three different values.</p> <p>This recipe solves the problem of finding <em>all</em> sets within an array of an arbitrary number of cards, showing some clever optimizations and celebrating the clarity of Python in expressing the algorithms.</p> Eight queen problem (Javascript) (JavaScript) 2013-03-20T19:03:44-07:00Thomas Lehmannhttp://code.activestate.com/recipes/users/4174477/http://code.activestate.com/recipes/578497-eight-queen-problem-javascript/ <p style="color: grey"> JavaScript recipe 578497 by <a href="/recipes/users/4174477/">Thomas Lehmann</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/queen/">queen</a>, <a href="/recipes/tags/queens/">queens</a>). </p> <ul> <li>Adding this for my old <a href="http://code.activestate.com/recipes/577438/">recipe 577438</a> (in Python).</li> <li>Use node.js or HTML as execution (see comments in "log" function)</li> </ul> Topological Sort (Python) 2012-09-27T12:21:23-07:00Sam Dentonhttp://code.activestate.com/recipes/users/4172262/http://code.activestate.com/recipes/578272-topological-sort/ <p style="color: grey"> Python recipe 578272 by <a href="/recipes/users/4172262/">Sam Denton</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/sort/">sort</a>, <a href="/recipes/tags/sorting/">sorting</a>, <a href="/recipes/tags/topological/">topological</a>, <a href="/recipes/tags/toposort/">toposort</a>). </p> <p>A topological sort (sometimes abbreviated topsort or toposort) or topological ordering of a directed graph is a linear ordering of its vertices such that, for every edge uv, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG).</p> Knight's Tour using Warnsdorff Algorithm (Python) 2012-12-17T06:04:19-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/578382-knights-tour-using-warnsdorff-algorithm/ <p style="color: grey"> Python recipe 578382 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>). </p> <p>Knight's Tour using Warnsdorff Algorithm.</p> Generating Balanced Parenthesis (Python) 2013-02-14T22:00:22-08:00bartenderhttp://code.activestate.com/recipes/users/4185259/http://code.activestate.com/recipes/578458-generating-balanced-parenthesis/ <p style="color: grey"> Python recipe 578458 by <a href="/recipes/users/4185259/">bartender</a> (<a href="/recipes/tags/algorithm/">algorithm</a>). </p> <p>The python code generates balanced parenthesis recursively. Example for depth=3 i.e. 3 opening brackets and 3 closing brackets,the sample output should be:</p> <p>((())) (()()) (())() ()(()) ()()()</p> <p>The number of such output ( 5 in above case) is a Catalan Number.</p> topological sorting again (Python) 2013-03-06T19:21:11-08:00yotahttp://code.activestate.com/recipes/users/4184815/http://code.activestate.com/recipes/578406-topological-sorting-again/ <p style="color: grey"> Python recipe 578406 by <a href="/recipes/users/4184815/">yota</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/graph/">graph</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/sort/">sort</a>, <a href="/recipes/tags/topological/">topological</a>). Revision 9. </p> <p>Topological sorting is the answer to the following question : in a direct acyclic graph, how can I pick up nodes "in order", such as upstream nodes are always before downstream ones ? Many solutions may exists, many algorithms too.</p> <p>Alas, it seems I'm too stupid to understand already proposed recipes on topological sorting. Hopefully I do grasp the "write once, read many" concept.</p> <p>Here, you will find a plain algorithm, optimized only for code clarity, of a topological sorting for direct acyclic graphs, implemented in python from the pseudo code found on <a href="http://en.wikipedia.org/wiki/Topological_sorting">wikipedia</a>:</p> <pre class="prettyprint"><code>L ← Empty list that will contain the sorted elements S ← Set of all nodes with no incoming edges while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S if graph has edges then return error (graph has at least one cycle) else return L (a topologically sorted order) </code></pre> <p>Only tested with python3.2, should work with other versions. Be careful, code indented with tabs, since space is evil è_é</p> Knight's Tour Map using Warnsdorff's Algorithm (Python) 2012-12-18T01:05:51-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/578386-knights-tour-map-using-warnsdorffs-algorithm/ <p style="color: grey"> Python recipe 578386 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/graphics/">graphics</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/pil/">pil</a>). </p> <p>Solves Knight's Tour Problem using Warnsdorff's Algorithm for every square on the chessboard of arbitrary size.</p> <p>It colors each initial square with a color that depends on the final square coordinates. (This is a method used to create fractals.) Many different formulas maybe used for coloring (based on abs/rel x/y/dist/ang).</p> <p>Calculating each tour in full creates a highly chaotic image (and takes hours). So I added maxItPercent to cut-off tours earlier. (Using %10 creates an image that has both ordered and chaotic regions.)</p> Super Simple Sudoku Solver in Python source code (Python) 2012-06-23T14:56:05-07:00David Adlerhttp://code.activestate.com/recipes/users/4182015/http://code.activestate.com/recipes/578140-super-simple-sudoku-solver-in-python-source-code/ <p style="color: grey"> Python recipe 578140 by <a href="/recipes/users/4182015/">David Adler</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/recursive/">recursive</a>, <a href="/recipes/tags/recurssion/">recurssion</a>, <a href="/recipes/tags/sodoku/">sodoku</a>, <a href="/recipes/tags/sudoku/">sudoku</a>). Revision 5. </p> <p>A simple algorithm which uses a recursive function to solve the puzzle.</p> <hr /> <p>THE ALGORITHM</p> <p>The credit for this algorithm must go to Richard Buckland: <a href="http://www.youtube.com/watch?v=bjObm0hxIYY&amp;feature=autoplay&amp;list=PL6B940F08B9773B9F&amp;playnext=1" rel="nofollow">http://www.youtube.com/watch?v=bjObm0hxIYY&amp;feature=autoplay&amp;list=PL6B940F08B9773B9F&amp;playnext=1</a></p> <p>Takes a partially filled in grid, inserts the min value in a cell (could be a random cell, in this case the first free cell). If the min value is not legal it will increment until the max value is reached (number 9), checking each time if the incremented value is legal in that cell (ie does not clash with any already entered cells in square, col or row). If it is legal, it will call itself (the hasSolution function) thus using this slightly more filled in grid to find a new cell and check which value is legal in this next cell. If no values are legal in the next cell, it will clear the previous grid entry and try incrementing the value.</p> <p>isLegal = does not conflict with any other numbers in the same row, column or square</p> A-star Shortest Path Algorithm (C++) 2010-12-25T23:36:35-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/577457-a-star-shortest-path-algorithm/ <p style="color: grey"> C++ recipe 577457 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/game/">game</a>, <a href="/recipes/tags/graph/">graph</a>, <a href="/recipes/tags/graphs/">graphs</a>, <a href="/recipes/tags/routes/">routes</a>). Revision 4. </p> <p>A-star (A*) is a shortest path algorithm widely used for RTS games, GPS navigation etc.</p> Genetic Algorithm in Python source code - AI-Junkie tutorial (Python) 2012-06-19T12:59:13-07:00David Adlerhttp://code.activestate.com/recipes/users/4182015/http://code.activestate.com/recipes/578128-genetic-algorithm-in-python-source-code-ai-junkie-/ <p style="color: grey"> Python recipe 578128 by <a href="/recipes/users/4182015/">David Adler</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/artificial/">artificial</a>, <a href="/recipes/tags/genetic/">genetic</a>, <a href="/recipes/tags/network/">network</a>, <a href="/recipes/tags/neural/">neural</a>, <a href="/recipes/tags/python/">python</a>). Revision 5. </p> <p>A simple genetic algorithm program. I followed this tutorial to make the program <a href="http://www.ai-junkie.com/ga/intro/gat1.html." rel="nofollow">http://www.ai-junkie.com/ga/intro/gat1.html.</a></p> <p>The objective of the code is to evolve a mathematical expression which calculates a user-defined target integer.</p> <hr /> <p>KEY:</p> <p>chromosome = binary list (this is translated/decoded into a protein in the format number --> operator --> number etc, any genes (chromosome is read in blocks of four) which do not conform to this are ignored.</p> <p>protein = mathematical expression (this is evaluated from left to right in number + operator blocks of two)</p> <p>output = output of protein (mathematical expression)</p> <p>error = inverse of difference between output and target</p> <p>fitness score = a fraction of sum of of total errors</p> <hr /> <p>OTHER:</p> <p>One-point crossover is used.</p> <p>I have incorporated <strong>elitism</strong> in my code, which somewhat deviates from the tutorial but made my code more efficient (top ~7% of population are carried through to next generation)</p> Evolutionary Algorithm (Generation of Prime Numbers) (Python) 2011-11-27T06:45:00-08:00Alexander James Wallarhttp://code.activestate.com/recipes/users/4179768/http://code.activestate.com/recipes/577964-evolutionary-algorithm-generation-of-prime-numbers/ <p style="color: grey"> Python recipe 577964 by <a href="/recipes/users/4179768/">Alexander James Wallar</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/example/">example</a>, <a href="/recipes/tags/genetic/">genetic</a>, <a href="/recipes/tags/genetic_algorithm/">genetic_algorithm</a>, <a href="/recipes/tags/genetic_algorithms/">genetic_algorithms</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/number/">number</a>, <a href="/recipes/tags/of/">of</a>, <a href="/recipes/tags/prime/">prime</a>, <a href="/recipes/tags/primelist/">primelist</a>, <a href="/recipes/tags/primes/">primes</a>, <a href="/recipes/tags/theory/">theory</a>). </p> <p>This is an evolutionary algorithm that returns a random list of prime numbers. This code is highly inefficient for a reason. This algorithm is more of a proof of concept that if a prime was a heritable trait, it would not be a desired one. </p> <p>Parameters:</p> <p>isPrime --> n: number to check if it is prime allPrimes --> n: size of list of random primes, m: the primes in the list will be between 0 and m</p> Shannon-Fano Data Compression (Python) 2010-12-18T22:09:40-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/577502-shannon-fano-data-compression/ <p style="color: grey"> Python recipe 577502 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/data_compression/">data_compression</a>). Revision 3. </p> <p>Shannon-Fano Data Compression. It can compress any kind of file up to 4 GB.</p> <p>(But trying to compress an already compressed file like zip, jpg etc. can produce a (slightly) larger file though. Shannon-Fano is not the best data compression algorithm anyway.)</p>