Popular recipes tagged "meta:requires=operator"http://code.activestate.com/recipes/tags/meta:requires=operator/2014-08-02T02:56:12-07:00ActiveState Code RecipesYet Another NamedTuple (Python) 2014-08-02T02:56:12-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/578918-yet-another-namedtuple/ <p style="color: grey"> Python recipe 578918 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/shortcuts/">shortcuts</a>). </p> <p>Yet another look at Raymond Hettinger's excellent "namedtuple" factory. Unlike Raymond's version, this one minimizes the use of exec. In the original, the entire inner class is dynamically generated then exec'ed, leading to the bulk of the code being inside a giant string template. This version uses a regular inner class for everything except the __new__ method.</p> A simple Matrix class (Python) 2012-05-14T13:34:31-07:00Anand B Pillaihttp://code.activestate.com/recipes/users/4169530/http://code.activestate.com/recipes/578131-a-simple-matrix-class/ <p style="color: grey"> Python recipe 578131 by <a href="/recipes/users/4169530/">Anand B Pillai</a> (<a href="/recipes/tags/algebra/">algebra</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/matrix/">matrix</a>). Revision 3. </p> <p>A simple class in Python representing a Matrix with basic operations, operator overloading and class factory methods to make Matrices from different sources.</p> An analogue of enumerate for nested lists. (Python) 2012-12-11T16:59:14-08:00John Crichtonhttp://code.activestate.com/recipes/users/4181975/http://code.activestate.com/recipes/578376-an-analogue-of-enumerate-for-nested-lists/ <p style="color: grey"> Python recipe 578376 by <a href="/recipes/users/4181975/">John Crichton</a> (<a href="/recipes/tags/enumerate/">enumerate</a>, <a href="/recipes/tags/index/">index</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/list/">list</a>). Revision 6. </p> <p>A generator function which enables traversal and modification of deeply nested lists. Together with the supplied helper functions it could be useful when working with data stored in deeply nested lists, particularly when the level of nesting precludes a recursive approach.</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> Python reader + writer for spss sav files (Linux, Mac & Windows) (Python) 2013-02-20T22:07:27-08:00Albert-Jan Roskamhttp://code.activestate.com/recipes/users/4177640/http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ <p style="color: grey"> Python recipe 577811 by <a href="/recipes/users/4177640/">Albert-Jan Roskam</a> (<a href="/recipes/tags/reader/">reader</a>, <a href="/recipes/tags/sav/">sav</a>, <a href="/recipes/tags/spss/">spss</a>, <a href="/recipes/tags/writer/">writer</a>). Revision 12. </p> <p><strong>Python Program to READ &amp; WRITE Spss system files (.sav) (Linux,Mac or Windows)</strong></p> <ul> <li><em>Check <a href="https://pypi.python.org/pypi/savReaderWriter/" rel="nofollow">https://pypi.python.org/pypi/savReaderWriter/</a> for the latest version (including the libraries!)</em></li> <li>Requires libspssdio.so.1 (LINUX) or libspssdio.dylib (MAC) or spssio32.dll (WINDOWS) plus associated libaries, which can be freely downloaded from: <a href="https://www.ibm.com/developerworks/mydeveloperworks/wikis/home/wiki/We70df3195ec8_4f95_9773_42e448fa9029/page/Downloads%2520for%2520IBM%25C2%25AE%2520SPSS%25C2%25AE%2520Statistics?lang=en" rel="nofollow">https://www.ibm.com/developerworks/mydeveloperworks/wikis/home/wiki/We70df3195ec8_4f95_9773_42e448fa9029/page/Downloads%20for%20IBM%C2%AE%20SPSS%C2%AE%20Statistics?lang=en</a></li> <li>It is recommended to download the v21 I/O files (required for writing zlib (.zsav) compressed files)</li> <li>December 2012 (complete rewrite):</li> <li>Added support for slicing, indexing, array slicing + other special methods</li> <li>Added support for writing spss date fields</li> <li>Added support for almost all meta data (missing values, sets, roles, etc.)</li> <li>Added support for 64 bit Windows (tested with Win7) and other OSs (z/Linux, Solaris, HP Linux, IBM AIX (untested though)</li> <li>Added support for reading and writing zlib compressed (.zsav) files</li> <li>Removed pesky segfault error when freeing memory</li> <li>Removed errors related to encoding</li> <li>Changed some Reader defaults (verbose=False, returnHeader=False)</li> <li>Renamed SavDataDictionaryReader into SavHeaderReader</li> </ul> <p><strong>LINUX:</strong></p> <p><em>Installation (tested on Linux Ubuntu 10):</em></p> <ul> <li>additional packages/files needed are: intel-icc8-libs_8.0-1_i386.deb,libicu32_3.2-3_i386.deb, libstdc++5_3.3.6-20_i386.deb, libirc.so.</li> <li>Run the following commands in your terminal: sudo apt-get install intel-icc8-libs; sudo apt-get install libicu32; sudo apt-get install libstdc++5.</li> <li>Then convert libirc.a (static) to libirc.so (dynamic), save in same location as libspssdio.so.1: ar vx intel-icc8-libs_8.0-1_i386.deb; tar -xzvf data.tar.gz ./usr/lib/libirc.a; ar -x libirc.a.</li> </ul> <p><em>Calling the program:</em></p> <ul> <li>In the TERMINAL type: export LD_LIBRARY_PATH=/path/of/additional/sofiles; python /some/path/wrapperToProgram.py. You may also add ld_library_path to .bashrc</li> <li>The wrapper starts with "from SavReaderWriter import *", followed by e.g. stuff from the if __name__ == '__main__' section</li> </ul> <p><strong>MAC OS:</strong></p> <ul> <li>you must put all the dylib files that come with the IBM SPSS_Statistics_InputOutput_Modules_* package in the macos directory somewhere that OS X can find them</li> <li>one simple way to accomplish this is to copy them to /usr/lib</li> </ul> <p><strong>WINDOWS:</strong></p> <ul> <li>You can also find this dll in the installation directory of SPSS (although SPSS is _not_ needed!)</li> <li>The .dll should be saved in the same location as this program.</li> </ul> <p><strong>USAGE:</strong> See docstrings + __main__ section</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> Range comparison (Python) 2012-06-06T12:00:52-07:00Charlie Clarkhttp://code.activestate.com/recipes/users/4171013/http://code.activestate.com/recipes/578158-range-comparison/ <p style="color: grey"> Python recipe 578158 by <a href="/recipes/users/4171013/">Charlie Clark</a> (<a href="/recipes/tags/case/">case</a>, <a href="/recipes/tags/comparison/">comparison</a>, <a href="/recipes/tags/switch/">switch</a>, <a href="/recipes/tags/ternary/">ternary</a>). </p> <p>Although Python now has something similar to ternary operator with the result if ... else other result construction and this allows chaining (adding additional conditions on the if side, this soon becomes unreadable. A common use case is to filter values by ranges so I wrote the following when porting some code from PHP once I found I no longer understand the logic for a simple three-way filter.</p> Recursively defined, Haskell-style infinite lists (Python) 2012-05-04T14:09:14-07:00John Crichtonhttp://code.activestate.com/recipes/users/4181975/http://code.activestate.com/recipes/578119-recursively-defined-haskell-style-infinite-lists/ <p style="color: grey"> Python recipe 578119 by <a href="/recipes/users/4181975/">John Crichton</a> (<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/functional/">functional</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/infinite/">infinite</a>, <a href="/recipes/tags/itertools/">itertools</a>, <a href="/recipes/tags/lazy/">lazy</a>, <a href="/recipes/tags/recursive/">recursive</a>). Revision 2. </p> <p>A decorator to simplify the creation of recursively defined, Haskell-style infinite lists -- ie. recursive generators -- inspired by Raymond Hettinger's "Technique for cyclical iteration" [*]. </p> <p>[*] <a href="http://code.activestate.com/recipes/576961-technique-for-cyclical-iteration/" rel="nofollow">http://code.activestate.com/recipes/576961-technique-for-cyclical-iteration/</a> </p> Comparing two images (Python) 2011-04-03T11:13:24-07:00Charlie Clarkhttp://code.activestate.com/recipes/users/4171013/http://code.activestate.com/recipes/577630-comparing-two-images/ <p style="color: grey"> Python recipe 577630 by <a href="/recipes/users/4171013/">Charlie Clark</a> (<a href="/recipes/tags/compare/">compare</a>, <a href="/recipes/tags/images/">images</a>). </p> <p>Compare two images using the root mean squared analysis. A result close to 0 means a good match.</p> Yet Another Ordered Dictionary (Python) 2011-08-07T12:14:56-07:00Lucio Santihttp://code.activestate.com/recipes/users/4178886/http://code.activestate.com/recipes/577826-yet-another-ordered-dictionary/ <p style="color: grey"> Python recipe 577826 by <a href="/recipes/users/4178886/">Lucio Santi</a> (<a href="/recipes/tags/dict/">dict</a>, <a href="/recipes/tags/dictionary/">dictionary</a>, <a href="/recipes/tags/linked_list/">linked_list</a>, <a href="/recipes/tags/ordered/">ordered</a>). </p> <p>An implementation of dictionaries preserving key insertion order. Despite using a doubly-linked list to keep track of the appropriate order, this list is actually embedded in the dictionary. As a consequence, there is little space penalty, and also every operation exhibits an efficient implementation (i.e., no need to perform lookups or deletions multiple times, as it happens with other versions of this data structure).</p> to change instance to immutable (Python) 2011-08-08T05:52:18-07:00KATO Kanryuhttp://code.activestate.com/recipes/users/4178894/http://code.activestate.com/recipes/577831-to-change-instance-to-immutable/ <p style="color: grey"> Python recipe 577831 by <a href="/recipes/users/4178894/">KATO Kanryu</a> (<a href="/recipes/tags/immutable/">immutable</a>, <a href="/recipes/tags/instance/">instance</a>, <a href="/recipes/tags/python/">python</a>). </p> <p>make a class instance to immutable one. we can call fields, methods, and properties. This airms to make easier to develop multi thread object-oriented programming.</p> Python reader for spss sav files (Python) 2011-07-25T18:59:49-07:00Albert-Jan Roskamhttp://code.activestate.com/recipes/users/4177640/http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/ <p style="color: grey"> Python recipe 577650 by <a href="/recipes/users/4177640/">Albert-Jan Roskam</a> (<a href="/recipes/tags/files/">files</a>, <a href="/recipes/tags/pasw/">pasw</a>, <a href="/recipes/tags/sav/">sav</a>, <a href="/recipes/tags/spss/">spss</a>, <a href="/recipes/tags/statistics/">statistics</a>). Revision 3. </p> <p><strong>Python Program to read Spss system files (.sav)</strong></p> <ul> <li><em>* version 2 (FASTER!) *</em></li> <li>Requires spssio32.dll, which can be freely downloaded from: <a href="https://www.ibm.com/developerworks/mydeveloperworks/wikis/home/wiki/We70df3195ec8_4f95_9773_42e448fa9029/page/Downloads%2520for%2520IBM%25C2%25AE%2520SPSS%25C2%25AE%2520Statistics?lang=en" rel="nofollow">https://www.ibm.com/developerworks/mydeveloperworks/wikis/home/wiki/We70df3195ec8_4f95_9773_42e448fa9029/page/Downloads%20for%20IBM%C2%AE%20SPSS%C2%AE%20Statistics?lang=en</a></li> <li>You can also find this dll in the installation directory of SPSS (although SPSS is _not_ needed!)</li> <li><p>The .dll should be saved in the same location as this program.</p></li> <li><p>Parameters: <em>savFileName</em>: the file name of the spss data file; <em>returnHeader</em>: Boolean that indicates whether the first record should be a list of variable names (default: True); <em>recodeSysmisTo</em>: indicates to which value missing values should be recoded (default: ""); <em>selectVars</em>: indicates which variables in the file should be selected.The variables should be specified as a list or a tuple of valid variable names. If None is specified, all variables in the file are used (default: None); <em>verbose</em>: Boolean that indicates whether information about the spss data file (e.g., number of cases, variable names, file size) should be printed on the screen (default: True). <br /> <em>rawMode</em>: Boolean that indicates whether values should get SPSS-style formatting,and whether date variables (if present) should be converted to ISO-dates. If True, the program does not format any values, which increases processing speed. (default: = False) <em>interfaceEncoding</em> Indicates the mode in which text communicated to or from the I/O Module will be. Valid values are 'UTF-8' or 'CODEPAGE' (default = 'CODEPAGE')</p></li> <li><p>Typical use: savFileName = "d:/someFile.sav" with SavReader(savFileName) as sav: header = sav.next() for line in sav: process(line)</p></li> <li><p>Note: --<em>New version</em>: If you downloaded this previously, use the current version as it is <strong>MUCH faster!!</strong> --this code currently only works on Windows (32 bits). I might make it work on Linux Ubuntu 10 at some point. --date fields in spss are represented as the number of seconds since the Gregorian calendar. The program converts these, wherever possible, to ISO-dates (yyyy-mm-dd).</p></li> </ul> <p>Any feedback is welcome! I'm still learning!</p> Infix operators (Python) 2011-06-06T12:07:00-07:00Animesh Kumarhttp://code.activestate.com/recipes/users/4178212/http://code.activestate.com/recipes/577738-infix-operators/ <p style="color: grey"> Python recipe 577738 by <a href="/recipes/users/4178212/">Animesh Kumar</a> (<a href="/recipes/tags/oop/">oop</a>). </p> <p>Python has the wonderful "in" operator and it would be nice to have additional infix operator like this. This recipe shows how (almost) arbitrary infix operators can be defined.</p> Directory Pruner 2 (Python) 2011-04-05T01:37:14-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/577633-directory-pruner-2/ <p style="color: grey"> Python recipe 577633 by <a href="/recipes/users/2608421/">Stephen Chappell</a> (<a href="/recipes/tags/delete/">delete</a>, <a href="/recipes/tags/directory/">directory</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/gui/">gui</a>, <a href="/recipes/tags/utility/">utility</a>). </p> <p>This program builds on work done in <a href="http://code.activestate.com/recipes/577632/">recipe 577632</a>, adds new options to the context menu, and experiments with threading the GUI. Directory Pruner 2 appear to work better on Windows 7 while Directory Pruner 1 (the non-threaded version) performs better on Windows XP. Those are the primary platforms on which the two programs have been tested. Please use these applications at your own risk.</p> <p>If you do not like something about this recipe and want to vote it down, please let everyone what you find fault with, how you would improve it, and an example of the code you would improve.</p> Directory Pruner 3 (Python) 2011-04-05T23:15:58-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/577635-directory-pruner-3/ <p style="color: grey"> Python recipe 577635 by <a href="/recipes/users/2608421/">Stephen Chappell</a> (<a href="/recipes/tags/delete/">delete</a>, <a href="/recipes/tags/directory/">directory</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/gui/">gui</a>, <a href="/recipes/tags/utility/">utility</a>). </p> <p>After considering the monolithic design of <a href="http://code.activestate.com/recipes/577633/">recipe 577633</a> and deciding that it should be divided into several smaller modules, Directory Pruner 3 was written to take advantage of better abstraction methodologies. There are a total of twelve files in the project, and all of them except the first are contained within a directory called "Directory Pruner 3" such that they make up a package in Python. Like the other Directory Pruners, please use and configure this program at your own computer's risk.</p> <p>If you have any comments or wish to vote this recipe down, please provide an explanation as to what you find fault with in this program and also a solution that you would implement to fix the problem.</p> Table indentation (Python) 2011-03-18T14:39:59-07:00Jonathan Blakeshttp://code.activestate.com/recipes/users/4177368/http://code.activestate.com/recipes/577615-table-indentation/ <p style="color: grey"> Python recipe 577615 by <a href="/recipes/users/4177368/">Jonathan Blakes</a> (<a href="/recipes/tags/text/">text</a>). </p> <p>A function for pretty-printing a table.</p> Counter class (Python) 2011-04-17T21:27:05-07:00Praveenhttp://code.activestate.com/recipes/users/4177693/http://code.activestate.com/recipes/577664-counter-class/ <p style="color: grey"> Python recipe 577664 by <a href="/recipes/users/4177693/">Praveen</a> . </p> <p>Bag/multiset class for convenient tallying of hashable objects.</p> Aggregates using groupby, defaultdict and Counter (Python) 2011-02-07T15:38:09-08:00N Nhttp://code.activestate.com/recipes/users/1639254/http://code.activestate.com/recipes/577535-aggregates-using-groupby-defaultdict-and-counter/ <p style="color: grey"> Python recipe 577535 by <a href="/recipes/users/1639254/">N N</a> (<a href="/recipes/tags/algorithms/">algorithms</a>). Revision 2. </p> <p>How to emulate SQL aggregate functions AVG, COUNT, MAX, MIN and SUM on csv type data files using tools from the standard library.</p> Evaluator 2.0 (Python) 2010-11-25T18:24:09-08:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/577469-evaluator-20/ <p style="color: grey"> Python recipe 577469 by <a href="/recipes/users/2608421/">Stephen Chappell</a> (<a href="/recipes/tags/evaluator/">evaluator</a>, <a href="/recipes/tags/expressions/">expressions</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/parser/">parser</a>). </p> <p>This is a complete rewrite of <a href="http://code.activestate.com/recipes/576790/">recipe 576790</a>. While aiming to maintain similar functionality and continuing its implementation for self-academic purposes, a much cleaner parser / tokenizer and operator execution engine were developed. A slightly different math syntax is supported in this version, but it is arguably better and more capable than it previously was. Base prefixes are a feature now supported, and the single downgrade is calculating with integers instead of floats.</p> Infix operators (Python) 2005-02-17T11:12:04-08:00Ferdinand Jamitzkyhttp://code.activestate.com/recipes/users/98863/http://code.activestate.com/recipes/384122-infix-operators/ <p style="color: grey"> Python recipe 384122 by <a href="/recipes/users/98863/">Ferdinand Jamitzky</a> (<a href="/recipes/tags/oop/">oop</a>). Revision 3. </p> <p>Python has the wonderful "in" operator and it would be nice to have additional infix operator like this. This recipe shows how (almost) arbitrary infix operators can be defined.</p>