Popular recipes tagged "meta:min_python_3=1"http://code.activestate.com/recipes/tags/meta:min_python_3=1/2016-05-01T13:11:05-07:00ActiveState Code RecipesEqually-spaced numbers (linspace) (Python) 2015-01-12T22:16:37-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/579000-equally-spaced-numbers-linspace/ <p style="color: grey"> Python recipe 579000 by <a href="/recipes/users/4184316/">Andrew Barnert</a> (<a href="/recipes/tags/float/">float</a>, <a href="/recipes/tags/linspace/">linspace</a>, <a href="/recipes/tags/range/">range</a>, <a href="/recipes/tags/spread/">spread</a>). </p> <p>An equivalent of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html"><code>numpy.linspace</code></a>, but as a pure-Python lazy sequence.</p> <p>Like NumPy's <code>linspace</code>, but unlike the <a href="http://code.activestate.com/recipes/577068/"><code>spread</code></a> and <a href="http://code.activestate.com/recipes/577068/"><code>frange</code></a> recipes listed here, the <code>num</code> argument specifies the number of values, not the number of intervals, and the range is closed, not half-open.</p> <p>Although this is primarily designed for floats, it will work for <code>Fraction</code>, <code>Decimal</code>, NumPy arrays (although this would be silly) and even <code>datetime</code> values.</p> <p>This recipe can also serve as an example for creating lazy sequences.</p> <p>See the discussion below for caveats.</p> Compute Memory footprint of an object and its contents (Python) 2012-11-23T23:57:31-08:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/577504-compute-memory-footprint-of-an-object-and-its-cont/ <p style="color: grey"> Python recipe 577504 by <a href="/recipes/users/178123/">Raymond Hettinger</a> (<a href="/recipes/tags/memory/">memory</a>, <a href="/recipes/tags/sizeof/">sizeof</a>). Revision 3. </p> <p>Recursive version sys.getsizeof(). Extendable with custom handlers.</p> Function guards for Python 3 (Python) 2016-05-01T13:11:05-07:00Dmitry Dvoinikovhttp://code.activestate.com/recipes/users/2475216/http://code.activestate.com/recipes/580658-function-guards-for-python-3/ <p style="color: grey"> Python recipe 580658 by <a href="/recipes/users/2475216/">Dmitry Dvoinikov</a> (<a href="/recipes/tags/call/">call</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/dispatch/">dispatch</a>, <a href="/recipes/tags/function/">function</a>, <a href="/recipes/tags/guard/">guard</a>). </p> <p>This module implements a function guard - facility to redirect the the call to one of several function implementations at run time based on the actual call arguments.</p> <p>Wrap each of the identically named functions in a @guard decorator and provide a _when parameter with a default value set to guarding expression.</p> <p>See samples at the top of the module.</p> Yet another singleton pattern in Python using class decorators (Python) 2015-08-11T19:14:45-07:00David Hollmanhttp://code.activestate.com/recipes/users/4182331/http://code.activestate.com/recipes/579090-yet-another-singleton-pattern-in-python-using-clas/ <p style="color: grey"> Python recipe 579090 by <a href="/recipes/users/4182331/">David Hollman</a> (<a href="/recipes/tags/patterns/">patterns</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/singleton/">singleton</a>). Revision 8. </p> <p>Another pattern for creating singleton instances of classes in Python.</p> Amazon SNS handler for the logging module (Python) 2014-11-06T17:32:26-08:00Andrea Corbellinihttp://code.activestate.com/recipes/users/4186880/http://code.activestate.com/recipes/578956-amazon-sns-handler-for-the-logging-module/ <p style="color: grey"> Python recipe 578956 by <a href="/recipes/users/4186880/">Andrea Corbellini</a> (<a href="/recipes/tags/aws/">aws</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/sns/">sns</a>). Revision 2. </p> <p>This is a handler for the standard <a href="https://docs.python.org/library/logging.html">logging</a> module that sends notifications to the <a href="http://aws.amazon.com/sns/">Amazon Simple Notification Service</a>.</p> <p>You can use it like so:</p> <pre class="prettyprint"><code>logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d ' '%(thread)d %(message)s', }, 'simple': { 'format': '%(levelname)s %(message)s', }, }, 'handlers': { 'sns': { 'level': 'INFO', 'class': 'SNSHandler', 'formatter': 'verbose', 'topic_arn': 'YOUR SNS TOPIC ARN', }, }, 'loggers': { 'YOUR MODULE': { 'handlers': ['sns'], 'level': 'INFO', 'propagate': True, }, }, } </code></pre> Call out to an external editor (Python) 2014-09-01T18:26:51-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/578926-call-out-to-an-external-editor/ <p style="color: grey"> Python recipe 578926 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/editing/">editing</a>, <a href="/recipes/tags/editor/">editor</a>, <a href="/recipes/tags/external/">external</a>, <a href="/recipes/tags/text/">text</a>). Revision 2. </p> <p>Here's a function that lets you use Python to wrap calls to an external editor. The editor can be an command line editor, like venerable old "ed", or something more powerful like nano, vim or emacs, and even GUI editors. After the editor quits, the text you typed in the editor is returned by the function.</p> <p>A simple example, using the (rather cryptic) 'ed' editor on Linux. For the benefit of those unfamiliar with 'ed', I have annotated the editor session with comments.</p> <pre class="prettyprint"><code>&gt;&gt;&gt; status, text = edit('ed') 0 ## ed prints the initial number of lines a ## start "append" mode Hello World! Goodbye now . ## stop appending w ## write the file to disk 25 ## ed prints the number of bytes written q ## quit ed and return to Python &gt;&gt;&gt; status 0 &gt;&gt;&gt; print text Hello World! Goodbye now </code></pre> Strongly connected components of a directed graph. (Python) 2013-04-03T19:30:32-07:00Mark Dickinsonhttp://code.activestate.com/recipes/users/4172683/http://code.activestate.com/recipes/578507-strongly-connected-components-of-a-directed-graph/ <p style="color: grey"> Python recipe 578507 by <a href="/recipes/users/4172683/">Mark Dickinson</a> (<a href="/recipes/tags/connected/">connected</a>, <a href="/recipes/tags/directed/">directed</a>, <a href="/recipes/tags/graph/">graph</a>, <a href="/recipes/tags/strong/">strong</a>, <a href="/recipes/tags/tarjan/">tarjan</a>). Revision 3. </p> <p>Two linear-time algorithms for finding the strongly connected components of a directed graph. <code>strongly_connected_components_tree</code> implements (a variant of) Tarjan's well-known algorithm for finding strongly connected components, while <code>strongly_connected_components_path</code> implements a path-based algorithm due (in this form) to Gabow.</p> <p>Edit: I added an iterative function <code>strongly_connected_components_iterative</code>; this is a direct conversion of <code>strongly_connected_components_path</code> into iterative form. It's therefore safe to use on high-depth graphs, without risk of running into Python's recursion limit.</p> Integer square root function (Python) 2011-08-04T05:29:16-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577821-integer-square-root-function/ <p style="color: grey"> Python recipe 577821 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/integer/">integer</a>, <a href="/recipes/tags/isqrt/">isqrt</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/maths/">maths</a>, <a href="/recipes/tags/root/">root</a>, <a href="/recipes/tags/square/">square</a>). </p> <p>The <em>integer square root</em> function, or isqrt, is equivalent to floor(sqrt(x)) for non-negative x. For small x, the most convenient way to calculate isqrt is by calling int(x**0.5) or int(math.sqrt(x)), but if x is a large enough integer, the sqrt calculation overflows.</p> <p>You can calculate the isqrt without any floating point maths, using just pure integer maths, allowing the function to operate with numbers far larger than possible with floats:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; n = 1234567*(10**1000) &gt;&gt;&gt; n2 = n*n &gt;&gt;&gt; math.sqrt(n2) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OverflowError: long int too large to convert to float &gt;&gt;&gt; isqrt(n2) == n True </code></pre> Yahoo Stock Information (Python) 2012-08-25T17:16:47-07:00Alexander James Wallarhttp://code.activestate.com/recipes/users/4179768/http://code.activestate.com/recipes/577989-yahoo-stock-information/ <p style="color: grey"> Python recipe 577989 by <a href="/recipes/users/4179768/">Alexander James Wallar</a> (<a href="/recipes/tags/computation/">computation</a>, <a href="/recipes/tags/corey_goldberg/">corey_goldberg</a>, <a href="/recipes/tags/finance/">finance</a>, <a href="/recipes/tags/information/">information</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/realtime/">realtime</a>, <a href="/recipes/tags/stock/">stock</a>, <a href="/recipes/tags/yahoo/">yahoo</a>). Revision 3. </p> <p>This recipe is solely due to the programming of Corey Goldberg (<a href="mailto:corey@goldb.org">corey@goldb.org</a>). The only thing I did to it was make it into a class. I thought that by uploading it here that more people would come across it and more people could use it. It is really good. It gives you stock information.</p> Generate equally-spaced floats (Python) 2011-09-24T18:49:39-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577878-generate-equally-spaced-floats/ <p style="color: grey"> Python recipe 577878 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/float/">float</a>, <a href="/recipes/tags/range/">range</a>, <a href="/recipes/tags/spread/">spread</a>). </p> <p>Generating a list of equally-spaced floats can surprising due to floating point rounding. See, for example, the recipe for a <a href="http://code.activestate.com/recipes/577068">floating point range</a>. One way of avoiding some surprises is by changing the API: instead of specifying a start, stop and step values, instead use a start, stop and count:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; list(spread(0.0, 2.1, 7)) [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8] </code></pre> <p>Like <a href="http://code.activestate.com/recipes/577068">frange</a> <code>spread</code> takes an optional mode argument to select whether the start and end values are included. By default, start is included and end is not, and exactly count values are returned.</p> (Yet another) Assignment in expression Recipe (Python) 2011-12-17T20:03:26-08:00harish anandhttp://code.activestate.com/recipes/users/4180291/http://code.activestate.com/recipes/577987-yet-another-assignment-in-expression-recipe/ <p style="color: grey"> Python recipe 577987 by <a href="/recipes/users/4180291/">harish anand</a> (<a href="/recipes/tags/expression/">expression</a>, <a href="/recipes/tags/shortcuts/">shortcuts</a>). Revision 3. </p> <p>Python does not support assignment in if and while statements such as "if (x=func()):". This is an attempt to bring similar functionality to python by injecting bytecode to all functions and methods in a module. This recipe is inspired from recipes <a href="http://code.activestate.com/recipes/66061">66061</a>, <a href="http://code.activestate.com/recipes/202234-assignment-in-expression">202234</a> and <a href="http://code.activestate.com/recipes/277940-decorator-for-bindingconstants-at-compile-time">277940</a>.</p> Selective directory walking (Python) 2011-10-20T05:05:39-07:00Nick Coghlanhttp://code.activestate.com/recipes/users/2035254/http://code.activestate.com/recipes/577913-selective-directory-walking/ <p style="color: grey"> Python recipe 577913 by <a href="/recipes/users/2035254/">Nick Coghlan</a> (<a href="/recipes/tags/directories/">directories</a>, <a href="/recipes/tags/files/">files</a>, <a href="/recipes/tags/globbing/">globbing</a>). Revision 2. </p> <p>Python's os.walk() standard library iterator is useful if you want to walk an entire directory tree, but you're on your own when it comes to implementing name filtering and recursive depth limiting on top of it.</p> <p>This recipe supports these features with an interface that is just as convenient as the underlying os.walk() API, while being significantly more powerful.</p> Rsync Algorithm (Python) 2011-01-09T16:32:22-08:00Eric Pruitthttp://code.activestate.com/recipes/users/4170757/http://code.activestate.com/recipes/577518-rsync-algorithm/ <p style="color: grey"> Python recipe 577518 by <a href="/recipes/users/4170757/">Eric Pruitt</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/delta/">delta</a>, <a href="/recipes/tags/diff/">diff</a>, <a href="/recipes/tags/patch/">patch</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/rsync/">rsync</a>). Revision 4. </p> <p>This is a pure Python implementation of the <a href="http://samba.anu.edu.au/rsync/">rsync algorithm</a>. On my desktop (3.0GHz dual core, 7200RPM), best case throughput for target file hash generation and delta generation is around 2.9MB/s. Absolute worst case scenario (no blocks in common) throughput for delta generation is 200KB/s to 300KB/s on the same system.</p> <p>Tested in Python 2.5, 2.6, and 3.1. In 2.7, io.BufferedReader should yield the best throughput. On all other versions use __builtin__.open.</p> format_iter: easy formatting of arbitrary iterables (Python) 2011-08-16T11:44:59-07:00Nick Coghlanhttp://code.activestate.com/recipes/users/2035254/http://code.activestate.com/recipes/577845-format_iter-easy-formatting-of-arbitrary-iterables/ <p style="color: grey"> Python recipe 577845 by <a href="/recipes/users/2035254/">Nick Coghlan</a> (<a href="/recipes/tags/formatting/">formatting</a>, <a href="/recipes/tags/strings/">strings</a>). </p> <p>The <code>format_iter</code> recipe defines a simple wrapper around <code>str.join</code> and <code>str.format</code> that makes it easy to format an arbitrary iterable with a specified format string and item separator.</p> Search sequences for sub-sequence (Python) 2011-08-19T05:17:00-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577850-search-sequences-for-sub-sequence/ <p style="color: grey"> Python recipe 577850 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/find/">find</a>, <a href="/recipes/tags/searching/">searching</a>, <a href="/recipes/tags/sequence/">sequence</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/sublist/">sublist</a>, <a href="/recipes/tags/substring/">substring</a>). </p> <p>The list and tuple index() method and <code>in</code> operator test for element containment, unlike similar tests for strings, which checks for sub-strings:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; "12" in "0123" True &gt;&gt;&gt; [1, 2] in [0, 1, 2, 3] False </code></pre> <p>These two functions, search and rsearch, act like str.find() except they operate on any arbitrary sequence such as lists:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; search([1, "a", "b", 2, 3], ["b", 2]) 2 </code></pre> Bloom Filter (Python) 2011-05-05T07:25:01-07:00Sundar Srinivasanhttp://code.activestate.com/recipes/users/4177884/http://code.activestate.com/recipes/577686-bloom-filter/ <p style="color: grey"> Python recipe 577686 by <a href="/recipes/users/4177884/">Sundar Srinivasan</a> (<a href="/recipes/tags/big_table/">big_table</a>, <a href="/recipes/tags/bloom_filter/">bloom_filter</a>, <a href="/recipes/tags/sets/">sets</a>, <a href="/recipes/tags/spelling_checker/">spelling_checker</a>). Revision 2. </p> <p>Space efficient, probabilistic set membership tester. Has no False Negatives but allows a rare False Positive.</p> Bitmap Maker (Python) 2011-04-21T13:08:46-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/577674-bitmap-maker/ <p style="color: grey"> Python recipe 577674 by <a href="/recipes/users/2608421/">Stephen Chappell</a> (<a href="/recipes/tags/experiment/">experiment</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/images/">images</a>, <a href="/recipes/tags/proof_of_concept/">proof_of_concept</a>, <a href="/recipes/tags/test/">test</a>). </p> <p>A friend and I were discussing the possibility of creating every possible image that is 800x600x24 (800 pixels wide by 600 pixels tall and using 24-bit color). This recipe is a proof-of-concept program showing what is possible with just a 2x2 image using 15 different colors (yielding a total of 50,625 images when run). In terms of the original thought experiment, a total of <code>16777216 ** 480000</code> images should be possible given the 800x600x24 specifications (or <code>1 &lt;&lt; 11520000</code> in binary). In base 10 that is <code>10 ** 3467865.55</code> and shows that there are an enormous number of possible states that a 800x600 canvas can take.</p> <p>If you have any comments or wish to down-vote this recipe, please provide your insight as to what could be improved upon and how you would go about fixing any problems that you might find.</p> Convert a youtube transcript in srt subtitle (Python) 2010-11-12T01:59:53-08:00Ginkohttp://code.activestate.com/recipes/users/4175855/http://code.activestate.com/recipes/577459-convert-a-youtube-transcript-in-srt-subtitle/ <p style="color: grey"> Python recipe 577459 by <a href="/recipes/users/4175855/">Ginko</a> (<a href="/recipes/tags/converter/">converter</a>, <a href="/recipes/tags/srt/">srt</a>, <a href="/recipes/tags/transcript/">transcript</a>, <a href="/recipes/tags/youtube/">youtube</a>). </p> <p>A quick and dirty script to convert youtube's transcripts (xml format) to .srt subtitle files.</p> <p>To download youtube's transcript, use this url: <a href="http://video.google.com/timedtext?lang=en&amp;v=VIDEO_ID" rel="nofollow">http://video.google.com/timedtext?lang=en&amp;v=VIDEO_ID</a> (replace "VIDEO_ID" by the ID which is in the video URL).</p> <p>You can easily use this converter in a script which could download the transcript by importing it and then call the main function.</p> Sleepsort with processes and pipes (Python) 2011-06-17T02:37:58-07:00Benjamin Petersonhttp://code.activestate.com/recipes/users/4170802/http://code.activestate.com/recipes/577758-sleepsort-with-processes-and-pipes/ <p style="color: grey"> Python recipe 577758 by <a href="/recipes/users/4170802/">Benjamin Peterson</a> (<a href="/recipes/tags/process/">process</a>, <a href="/recipes/tags/sorting/">sorting</a>, <a href="/recipes/tags/unix/">unix</a>). Revision 2. </p> <p>Sleepsort is a sorting algorithm that uses the system sleep syscall in a very creative fashion.</p> <p>This is the same algorithm as <a href="http://code.activestate.com/recipes/577756/">recipe 577756</a> but using *nix processes instead of threads.</p> Python Tkinter Canvas Rectangle Selection Box (Python) 2010-10-01T02:17:50-07:00Sunjay Varmahttp://code.activestate.com/recipes/users/4174115/http://code.activestate.com/recipes/577409-python-tkinter-canvas-rectangle-selection-box/ <p style="color: grey"> Python recipe 577409 by <a href="/recipes/users/4174115/">Sunjay Varma</a> (<a href="/recipes/tags/canvas/">canvas</a>, <a href="/recipes/tags/rectangle/">rectangle</a>, <a href="/recipes/tags/selection/">selection</a>, <a href="/recipes/tags/tkinter/">tkinter</a>). </p> <p>A simple, yet effective rectangle selection box. :)</p> <p>Works with a tkinter canvas! Just add the class and set it up like in the example code. The cross heir was my own touch, the RectTracker only draws a box.</p> <p>Have fun! And please don't just vote down, post what you don't like if you don't like it.</p>