Popular recipes tagged "meta:min_python_2=1"http://code.activestate.com/recipes/tags/meta:min_python_2=1/2017-03-13T13:27:50-07:00ActiveState Code RecipesUnit Testing Nested Functions (Python) 2016-11-10T10:23:11-08:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580716-unit-testing-nested-functions/ <p style="color: grey"> Python recipe 580716 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/introspection/">introspection</a>, <a href="/recipes/tags/nested/">nested</a>, <a href="/recipes/tags/unittests/">unittests</a>). Revision 3. </p> <p>Python allows the declaration of nested functions. These are typically hard to unit test because using just the normal ways of calling they cannot be called from outside their surrounding function. So they cannot be considered a clearly separated unit and thus cannot be unit tested.</p> <p>This is a drawback of using them, so many developers (especially the ones deep into test driven development who strive to have a high unit test coverage) tend to avoid them in favor for standalone functions which can be called from the unit tests without any hassle.</p> <p>But not all solutions with nested functions can be written as elegant with standalone functions. Nested functions are powerful insofar that they can access the local variables of the surrounding function without any need to pass them into the nested function, thus the code can in many cases stay neat and tidy while using a standalone function instead might raise the need to pass the complete context in form of a bunch of parameters. Also, using nested functions makes their local usage clear to any reader and keeps the name space tight.</p> <p>But at least in the standard CPython (i. e. not necessarily in Jython, etc.) the implementation of functions (and methods) allows to find the nested function's code, wrap it properly to give it its needed context and then call it from the outside. I wrote a small module which helps doing exactly this.</p> Context Manager for an Arbitrary Number of Files in Python (Python) 2017-03-13T13:27:50-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580763-context-manager-for-an-arbitrary-number-of-files-i/ <p style="color: grey"> Python recipe 580763 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/open/">open</a>). Revision 2. </p> <p>The pattern using <code>with</code> together with <code>open()</code> to automatically close a file after leaving the context is well known. To open a fixed number you can simply nest these statements or use the comma notation. For having a context which represents an arbitrary number of open files you can use the <code>ExitStack</code> class, but only for Python 3.3+.</p> <p>For other Python versions I'm using the following class which I named <code>Files</code>. The presented implementation is only for reading files (for keeping it clear). Extending it for having various file modes should not pose a problem.</p> States to Regions (Python) 2016-05-09T22:24:26-07:00Jackson Killianhttp://code.activestate.com/recipes/users/4194060/http://code.activestate.com/recipes/580661-states-to-regions/ <p style="color: grey"> Python recipe 580661 by <a href="/recipes/users/4194060/">Jackson Killian</a> (<a href="/recipes/tags/dictionary/">dictionary</a>, <a href="/recipes/tags/regions/">regions</a>, <a href="/recipes/tags/states/">states</a>). </p> <p>Python dictionary mapping two letter state abbreviations to their respective regions of the country (i.e. Midwest, North East, etc.) N - North East W - West M - Mid West S - South O - Other</p> Catalog multiple drives (Python) 2016-03-11T03:39:32-08:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/580619-catalog-multiple-drives/ <p style="color: grey"> Python recipe 580619 by <a href="/recipes/users/4076953/">Jack Trainor</a> (<a href="/recipes/tags/drives/">drives</a>, <a href="/recipes/tags/files/">files</a>, <a href="/recipes/tags/utility/">utility</a>). </p> <p>As one accumulates multiple drives, hard and flash, containing, thousands even millions of files, it becomes useful to have a text file containing an alphabetized catalog list of all files and their locations by drive and directory.</p> <p>The list can be searched by eye or by an editor to locate particular files.</p> <p>The list can also be loaded into a script to be filtered programmatically as desired.</p> FileSpec: Set it, forget it, reuse it (Python) 2016-03-08T05:49:16-08:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/580618-filespec-set-it-forget-it-reuse-it/ <p style="color: grey"> Python recipe 580618 by <a href="/recipes/users/4076953/">Jack Trainor</a> (<a href="/recipes/tags/filename/">filename</a>, <a href="/recipes/tags/utilities/">utilities</a>). </p> <p>Python provides good utilities for transforming filenames, but they are tedious to use and clutter up the source code.</p> <p>FileSpec offers one-stop shopping to convert a file path to every component you might want to know, reuse, or transform.</p> Simple breadth-first, depth-first tree traversal (Python) 2015-12-18T18:15:18-08:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/579138-simple-breadth-first-depth-first-tree-traversal/ <p style="color: grey"> Python recipe 579138 by <a href="/recipes/users/4076953/">Jack Trainor</a> (<a href="/recipes/tags/tree/">tree</a>). </p> <p>When you want to avoid recursion with a tree, you read the tree nodes into a stack, which is organized either breadth-first or depth-first.</p> <p>Here are two dead simple routines for doing so. Most of the recipe is just a test bed for those functions.</p> Bytes-to-human / human-to-bytes converter (Python) 2012-02-02T16:09:52-08:00Giampaolo RodolĂ http://code.activestate.com/recipes/users/4178764/http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/ <p style="color: grey"> Python recipe 578019 by <a href="/recipes/users/4178764/">Giampaolo RodolĂ </a> (<a href="/recipes/tags/bytes/">bytes</a>, <a href="/recipes/tags/conversion/">conversion</a>, <a href="/recipes/tags/converter/">converter</a>, <a href="/recipes/tags/human/">human</a>, <a href="/recipes/tags/humanize/">humanize</a>, <a href="/recipes/tags/string/">string</a>). Revision 15. </p> <p>Here goes.</p> 10 lines for a beginner to try out the Spyder IDE for python programming (Python) 2015-09-18T15:04:09-07:00mai3ahttp://code.activestate.com/recipes/users/4192857/http://code.activestate.com/recipes/579100-10-lines-for-a-beginner-to-try-out-the-spyder-ide-/ <p style="color: grey"> Python recipe 579100 by <a href="/recipes/users/4192857/">mai3a</a> (<a href="/recipes/tags/error/">error</a>, <a href="/recipes/tags/snippet/">snippet</a>, <a href="/recipes/tags/spyder/">spyder</a>, <a href="/recipes/tags/stuffthatworks/">stuffthatworks</a>). </p> <p>This python code generates no lint errors and just print out a few numbers.</p> <p>Useful if you use the Spyder IDE for the first time, which provides NOTHING to get you started.</p> A Function To Create A 1 Second Sinewave WAVE Beep File. (Python) 2014-11-23T19:24:46-08:00Barry Walkerhttp://code.activestate.com/recipes/users/4177147/http://code.activestate.com/recipes/578971-a-function-to-create-a-1-second-sinewave-wave-beep/ <p style="color: grey"> Python recipe 578971 by <a href="/recipes/users/4177147/">Barry Walker</a> (<a href="/recipes/tags/amiga/">amiga</a>, <a href="/recipes/tags/apple/">apple</a>, <a href="/recipes/tags/audio/">audio</a>, <a href="/recipes/tags/beep/">beep</a>, <a href="/recipes/tags/error_beep/">error_beep</a>, <a href="/recipes/tags/error_sound/">error_sound</a>, <a href="/recipes/tags/e_uae/">e_uae</a>, <a href="/recipes/tags/linux/">linux</a>, <a href="/recipes/tags/sinewave/">sinewave</a>, <a href="/recipes/tags/sound/">sound</a>, <a href="/recipes/tags/wav/">wav</a>, <a href="/recipes/tags/wave/">wave</a>, <a href="/recipes/tags/windows/">windows</a>, <a href="/recipes/tags/winuae/">winuae</a>). </p> <p>sinebeep.py</p> <p>Creating an audio file called...</p> <p>beep.wav</p> <p>...that can be played using almost ANY audio player available.</p> <p>This simple snippet of code generates a 1 second sinewave WAVE file. It IS saved inside the CURRENT drawer so that you can find it... ;o)</p> <p>This works on:- Classic stock AMIGA A1200, using Python 1.4.0. WinUAE and E-UAE, AmigaOS 3.0.x using Python 1.4.0 to 2.0.1. Windows, to at least 7, using Python 2.0.1 to 3.3.2. Various Linux flavours using Python 2.4.6 to 3.2.2. Apple OSX 10.7.x and above using Python 2.5.6 to 3.4.1.</p> <p>The file size is 8044 bytes and _IF_ you need to it can be palyed directly without a player on some Linux flavours that have the /dev/dsp device. It is an 8 bit, unsigned integer, mono, 8000Hz sampling speed 8000 byte RAW file with the WAVE header added.</p> <p>It will still work with PulseAudio and OSS using...</p> <p>cat /full/path/to/beep.wav &gt; /dev/dsp</p> <p>...but with a momenatry click due to the 44 header bytes; but hey it is a beep alternative...</p> <p>Enjoy finding simple solutions to often very difficult problems.</p> <p>Bazza.</p> Tic Tac Toe (Python) 2014-07-30T19:34:23-07:00Gauravhttp://code.activestate.com/recipes/users/4190360/http://code.activestate.com/recipes/578905-tic-tac-toe/ <p style="color: grey"> Python recipe 578905 by <a href="/recipes/users/4190360/">Gaurav</a> (<a href="/recipes/tags/tac/">tac</a>, <a href="/recipes/tags/tic/">tic</a>, <a href="/recipes/tags/toe/">toe</a>). Revision 2. </p> <p>Classic Tic Tac Toe game with AI. Created using Python 2.7.6</p> Name a lambda (Python) 2014-07-02T20:54:01-07:00David Weilhttp://code.activestate.com/recipes/users/1296670/http://code.activestate.com/recipes/578902-name-a-lambda/ <p style="color: grey"> Python recipe 578902 by <a href="/recipes/users/1296670/">David Weil</a> (<a href="/recipes/tags/func_name/">func_name</a>, <a href="/recipes/tags/introspection/">introspection</a>, <a href="/recipes/tags/lambda/">lambda</a>, <a href="/recipes/tags/name/">name</a>, <a href="/recipes/tags/naming/">naming</a>). </p> <p>A very simple recipe to allow you <em>easily</em> name lambda-objects (or other kind of objects, callable, for example, partial objects) you create, with little overhead and friendly syntax.</p> Highly branched Trees (Python) 2014-05-14T19:16:04-07:00Chris Eckerhttp://code.activestate.com/recipes/users/4180203/http://code.activestate.com/recipes/578879-highly-branched-trees/ <p style="color: grey"> Python recipe 578879 by <a href="/recipes/users/4180203/">Chris Ecker</a> (<a href="/recipes/tags/tree/">tree</a>). Revision 2. </p> <p>Trees are very common data structures and are usually considered to be very efficient. However, this is only true if the tree is balanced, meaning that all branches have roughly the same number of nodes. </p> <p>There are good balancing trees, such as rb-trees or avl-trees. Unfortunately they are quite difficult to implement. An alternative tree structure is the highly branched b-tree (<a href="https://en.wikipedia.org/wiki/B-tree" rel="nofollow">https://en.wikipedia.org/wiki/B-tree</a>). In the c language, binary trees are preferable in most cases. However, in python things are different. This recipe shows how simple it is to implement a b-tree in python. The example is a sorted dict.</p> A Simple Timing Function (Python) 2013-12-01T01:39:44-08:00Mike Sweeneyhttp://code.activestate.com/recipes/users/4177990/http://code.activestate.com/recipes/578776-a-simple-timing-function/ <p style="color: grey"> Python recipe 578776 by <a href="/recipes/users/4177990/">Mike Sweeney</a> (<a href="/recipes/tags/performance/">performance</a>, <a href="/recipes/tags/timing/">timing</a>). Revision 2. </p> <p>This function prints out a message with the elapsed time from the previous call. It works with most Python 2.x platforms. The function uses a simple trick to store a persistent variable (clock) without using a global variable.</p> Wrap a a file-like object in another that calls a user callback whenever read() is called on it. (Python) 2013-09-25T01:54:53-07:00Martin Millerhttp://code.activestate.com/recipes/users/155538/http://code.activestate.com/recipes/578674-wrap-a-a-file-like-object-in-another-that-calls-a-/ <p style="color: grey"> Python recipe 578674 by <a href="/recipes/users/155538/">Martin Miller</a> (<a href="/recipes/tags/callback/">callback</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/oop/">oop</a>, <a href="/recipes/tags/progress/">progress</a>, <a href="/recipes/tags/upload/">upload</a>). </p> <p>Wraps a file-like object in another, but also calls a user callback with the number of bytes read whenever its <code>read()</code> method is called. Used for tracking upload progress, for example for a progress bar in a UI application.</p> Hamming Neighbors (Python) 2013-01-17T20:50:21-08:00Yong Shinhttp://code.activestate.com/recipes/users/4184933/http://code.activestate.com/recipes/578423-hamming-neighbors/ <p style="color: grey"> Python recipe 578423 by <a href="/recipes/users/4184933/">Yong Shin</a> (<a href="/recipes/tags/distance/">distance</a>, <a href="/recipes/tags/dynamic/">dynamic</a>, <a href="/recipes/tags/hamming/">hamming</a>, <a href="/recipes/tags/programming/">programming</a>). </p> <p>HammingNeighbors returns all integers that are k number of bits away (i.e. k Hamming distance away) from an integer. <br /> The algorithm uses dynamic programming.</p> String-like partition and rpartition functions for lists (Python) 2013-01-30T06:44:03-08:00Sam Dentonhttp://code.activestate.com/recipes/users/4172262/http://code.activestate.com/recipes/578442-string-like-partition-and-rpartition-functions-for/ <p style="color: grey"> Python recipe 578442 by <a href="/recipes/users/4172262/">Sam Denton</a> . </p> <p>Python 2.5 added the partition and rpartition methods for strings, but nothing similar for lists. These two functions provide that, with the addition of an optional key parameter with the same functionality as in itertools.groupby(. </p> xdiff in python (Python) 2012-11-12T20:59:54-08:00Hirohttp://code.activestate.com/recipes/users/4184239/http://code.activestate.com/recipes/578324-xdiff-in-python/ <p style="color: grey"> Python recipe 578324 by <a href="/recipes/users/4184239/">Hiro</a> (<a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/process/">process</a>). Revision 2. </p> <p>xdiff.py compares and output difference of file1 and file2. it finds out the lines that are unique in file1 and files2, the finding is written to file3 and file4 respectively.</p> Genetic Algorithm Neural Network in Python Source Code (Python) 2012-08-16T16:31:12-07:00David Adlerhttp://code.activestate.com/recipes/users/4182015/http://code.activestate.com/recipes/578241-genetic-algorithm-neural-network-in-python-source-/ <p style="color: grey"> Python recipe 578241 by <a href="/recipes/users/4182015/">David Adler</a> (<a href="/recipes/tags/artificial_intelligence/">artificial_intelligence</a>, <a href="/recipes/tags/neural/">neural</a>, <a href="/recipes/tags/neural_network/">neural_network</a>). </p> <p>A simple genetic algorithm neural network. </p> Artificial Neuroglial Network (ANGN) (Python) 2012-10-02T16:18:36-07:00David Adlerhttp://code.activestate.com/recipes/users/4182015/http://code.activestate.com/recipes/578242-artificial-neuroglial-network-angn/ <p style="color: grey"> Python recipe 578242 by <a href="/recipes/users/4182015/">David Adler</a> (<a href="/recipes/tags/artificial_intelligence/">artificial_intelligence</a>, <a href="/recipes/tags/genetic_algorithm/">genetic_algorithm</a>, <a href="/recipes/tags/genetic_algorithms/">genetic_algorithms</a>, <a href="/recipes/tags/neural/">neural</a>, <a href="/recipes/tags/neural_networks/">neural_networks</a>). Revision 5. </p> <p>This is an attempt at emulating the algorithm from these scientific articles:</p> <ol> <li><a href="http://www.hindawi.com/journals/cmmm/2012/476324/">2011 - Artificial Astrocytes Improve Neural Network Performance</a></li> <li><a href="http://www.plosone.org/article/info%3Adoi%2F10.1371%2Fjournal.pone.0019109">2012 - Computational Models of Neuron-Astrocyte Interactions Lead to Improved Efficacy in the Performance of Neural Networks</a></li> </ol> <p>The objective of the program is to train a neural network to classify the four inputs (the dimensions of a flower) into one of three categories (three species of flower), (taken from the <a href="http://archive.ics.uci.edu/ml/datasets/Iris">Iris Data Set</a> from the UCI Machine Learning Repository). This program has two learning phases: the first is a genetic algorithm (supervised), the second is a neuroglial algorithm (unsupervised). This ANGN is a development of a previous program only consisting of a genetic algorithm which can be found <a href="http://code.activestate.com/recipes/578241-genetic-algorithm-neural-network-in-python-source-/">here</a>.</p> <p>The second phase aims to emulate astrocytic interaction with neurons in the brain. The algorithm is based on two axioms: a) astrocytes are activated by persistent neuronal activity b) astrocytic effects occur over a longer time-scale than neurons. Each neuron has an associated astrocyte which counts the number of times its associated neuron fires (+1 for active -1 for inactive). If the counter reaches its threshold (defined as <code>Athresh</code>) the astrocyte is activated and for the next x iterations (defined as <code>Adur</code>) the astrocyte modifies the incoming weights to that particular neuron. If the counter reached a maximum due to persistent firing the incoming weights are increase by 25% for the proceeding <code>Adur</code> iterations; conversely if the counter reached a minimum due to persistent lack of firing the weights are decreased by 50% for the following <code>Adur</code> iterations). For a detailed description of the algorithm see the linked articles. For a general understanding of how this program was coded look at the pseudo-code/schematic <a href="http://commons.wikimedia.org/wiki/File:ANGN_schematic.png">here</a>.</p> <p>Any comments for improvements are welcome. There are several issues in this program which require addressing, please scroll down below code to read about these issues.</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>