tag:blogger.com,1999:blog-66928661511431832302024-03-14T10:39:00.177+05:30jugad2 - Vasudev Ram on software innovationVasudev Ram's blog, tracking software innovation worldwide. Independent developer, many years' varied tech experience. <a href="https://vasudevram.github.io">vasudevram.github.io</a> * <a href="https://mobile.twitter.com/vasudevram">@vasudevram</a> * <a href="https://gumroad.com/vasudevram">Products</a> * <a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">Blog subscribe</a>
Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.comBlogger1646125tag:blogger.com,1999:blog-6692866151143183230.post-83177504434267280052019-05-15T03:37:00.002+05:302019-05-15T04:00:36.916+05:30print(5 * '=' * 5 == '=' * 5 * 5 == 5 * 5 * '=')<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><a href=""></a><br />
Hi readers,<br />
<br />
I was reviewing some of my <a href="https://jugad2.blogspot.com/p/training.html">Python training</a> material, and saw these lines:<br />
<pre># Multiplying a string by a number results in another string
# with that many copies of the original string.
print "-" * 10
print 10 * '-'
print "=" * 10
print 10 * '='
</pre>Notice that the integer can be either to the left or right of the asterisk, and the same for the string, in the expressions in the print statements above.<br />
<br />
Thought of experimenting a bit more, and came up with these snippets:<br />
<pre>print(5 * '=' == '=' * 5)
True
</pre><pre>print(5 * '=' * 5 == '=' * 5 * 5 == 5 * 5 * '=')
True
</pre>Which I initially found a little surprising, but if you think about, if comparisons using the <b>less-than</b> or <b>greater-than</b> signs (or variations like <b>less-than-or-equal</b> and <b>greater-than-or-equal</b>) can be chained in Python, why can't comparisons using the <b>equals</b> sign be chained too?<br />
<br />
This works in both Python 2 and Python 3.<br />
<br />
- Enjoy.<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com2tag:blogger.com,1999:blog-6692866151143183230.post-13967411773360017082019-04-18T04:22:00.000+05:302019-04-19T03:38:39.847+05:30Python's dynamic nature: sticking an attribute onto an object<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><a href=""></a><br />
<br />
Hi, readers,<br />
<br />
[This is a <a href="https://jugad2.blogspot.com/search/label/python-beginners">beginner-level Python post</a>.]<br />
<br />
Python, being a dynamic language, has some interesting features that some static languages may not have (and vice versa too, of course).<br />
<br />
One such feature, which I noticed a while ago, is that you can add an attribute to a Python object even after it has been created. (Conditions apply.) <br />
<br />
I had used this feature some time ago to work around some implementation issue in a rudimentary RESTful server that I created as a small teaching project. It was based on the <b>BaseHTTPServer</b> module.<br />
<br />
Here is a (different) simple example program, <b>stick_attrs_onto_obj.py</b>, that demonstrates this Python feature. <br />
My informal term for this feature is "sticking an attribute onto an object" after the object is created.<br />
<br />
Since the program is simple, and there are enough comments in the code, I will not explain it in detail.<br />
<pre># stick_attrs_onto_obj.py
# A program to show:
# 1) that you can "stick" attributes onto a Python object after it is created, and
# 2) one use of this technique, to count the number# of calls to a function.
# Copyright 2019 Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: https://jugad2.blogspot.com
# Training: https://jugad2.blogspot.com/p/training.html
# Product store: https://gumroad.com/vasudevram
# Twitter: https://twitter.com/vasudevram
from __future__ import print_function
# Define a function.
def foo(arg):
# Print something to show that the function has been called.
print("in foo: arg = {}".format(arg))
# Increment the "stuck-on" int attribute inside the function.
foo.call_count += 1
# A function is also an object in Python.
# So we can add attributes to it, including after it is defined.
# I call this "sticking" an attribute onto the function object.
# The statement below defines the attribute with an initial value,
# which is changeable later, as we will see.
foo.call_count = 0
# Print its initial value before any calls to the function.
print("foo.call_count = {}".format(foo.call_count))
# Call the function a few times.
for i in range(5):
foo(i)
# Print the attribute's value after those calls.
print("foo.call_count = {}".format(foo.call_count))
# Call the function a few more times.
for i in range(3):
foo(i)
# Print the attribute's value after those additional calls.
print("foo.call_count = {}".format(foo.call_count))
</pre><br />
And here is the output of the program:<br />
<pre>$ python stick_attrs_onto_obj.py
foo.call_count = 0
in foo: arg = 0
in foo: arg = 1
in foo: arg = 2
in foo: arg = 3
in foo: arg = 4
foo.call_count = 5
in foo: arg = 0
in foo: arg = 1
in foo: arg = 2
foo.call_count = 8
</pre><br />
There may be other ways to get the call count of a function, including using a profiler, and maybe by using a closure or decorator or other way. But this way is really simple. And as you can see from the code, it is also possible to use it to find the number of calls to the function, between any two points in the program code. For that, we just have to store the call count in a variable at the first point, and subtract that value from the call count at the second point. In the above program, that would be <b>8 - 5 = 3</b>, which matches the <b>3</b> that is the number of calls to function <b>foo</b> made by the 2nd for loop.<br />
<br />
Enjoy.<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-26923456926289777292019-04-11T22:30:00.001+05:302019-04-12T00:43:54.380+05:30The Vindhyas as seen from Bhimbetka<a href=""></a><br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://upload.wikimedia.org/wikipedia/commons/e/ed/Vindhyas_as_seen_from_Bhimbetka.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://upload.wikimedia.org/wikipedia/commons/e/ed/Vindhyas_as_seen_from_Bhimbetka.jpg" width="640" height="173" data-original-width="800" data-original-height="216" /></a></div><br />
I was browsing some Wikipedia sites about Indian rivers and mountain ranges, and via a chain of links, came across <a href="https://upload.wikimedia.org/wikipedia/commons/e/ed/Vindhyas_as_seen_from_Bhimbetka.jpg">this page</a>, about the <a href="https://en.wikipedia.org/wiki/Vindhya_Range">Vindhyas</a> as seen from <a href="https://en.wikipedia.org/wiki/Bhimbetka_rock_shelters">Bhimbetka</a>.<br />
<br />
The Vindhyas are a large mountain range in central India.<br />
<br />
I lived in <a href="https://en.wikipedia.org/wiki/Madhya_Pradesh">Madhya Pradesh</a> for some years as a teenager. Madhya Pradesh is called M.P. for short; the name means, loosely, middle state, referring to its geographic position in India.<br />
<br />
The Vindhyas are partly in Madhya Pradesh, and Bhimbetka is in M.P. too.<br />
<br />
I had visited Bhimbetka, and also traveled to, or through, many other places in M.P. generally, and the Vindhyas in particular (both within and outside of M.P., such as in <a href="https://en.wikipedia.org/wiki/Maharashtra">Maharashtra</a>, a neighboring state, for example) as a kid and teenager. I loved many of those places.<br />
<br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-62526956368157607312019-04-09T23:31:00.002+05:302019-04-09T23:31:26.983+05:30The Blogger issue (unable to use its UI) seems solved nowBy <a href="https://jugad2.blogspot.in/p/about-vasudev-ram.html">Vasudev Ram</a><br />
<br />
Hi, readers,<br />
<a href=""></a><br />
<br />
The Google Blogger issue that I referred to, <a href="https://jugad2.blogspot.com/2019/04/test-post-via-email-to-check-some.html">here</a> and <a href="https://jugad2.blogspot.com/2019/04/test-post-to-check-if-earlier-blogger.html">here</a>, seems to be solved now.<br />
<br />
I suspected that it was either an issue at Google's end (e.g. an introduced bug that had not yet been fixed) or some configuration / cookie / cache issue at my end. <br />
<br />
I did some stuff to debug it, like logging out and back in, logging in to a different Gmail account and then logging back into the previous one, clearing my browser cache, etc. One or other of those things seems to have worked.<br />
<br />
I am writing this current post via the regular Blogger UI, not via the email-to-blog interface that I used in the interim. So if the post appears okay, it likely means that the issue has been resolved. Will write a small Python test post or two in the next few days to verify this, and then resume normal blogging.<br />
<br />
Thanks for your patience.<br />
<br />
- Vasudev<br />
<br />
<a href=""></a> <hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><p/>Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>, vetted by two Windows system administrator friends.</p>Jump to posts: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a></p><a href="https://jugad2.blogspot.com/p/training.html">Interested in a Python, SQL or Linux course?</a></p><a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">Get WP Engine, powerful managed WordPress hosting.</a></p><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">Subscribe to my blog (jugad2.blogspot.com) by email</a></p><a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a></p><hr/>Follow me on:</p>* <a href="https://gumroad.com/vasudevram/follow">Gumroad</a> * <a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></p> * <a href="https://mobile.twitter.com/vasudevram">Twitter</a></p>Do you create online products? Get Convertkit:</p><a href="http://mbsy.co/convertkit/28519854">Email marketing for digital product creators</a></p><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-62974032400071036062019-04-08T21:42:00.000+05:302019-04-08T21:42:01.857+05:30Test post to check if earlier Blogger issue is solved - ignore.By <a href="https://jugad2.blogspot.in/p/about-vasudev-ram.html">Vasudev Ram</a><br />
<br />
<br />
<b>Test post to check if earlier Blogger issue is solved - ignore.</b><br />
<br />
<a href=""></a> <hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><p/>Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>, vetted by two Windows system administrator friends.</p>Jump to posts: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a></p><a href="https://jugad2.blogspot.com/p/training.html">Interested in a Python, SQL or Linux course?</a></p><a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">Get WP Engine, powerful managed WordPress hosting.</a></p><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">Subscribe to my blog (jugad2.blogspot.com) by email</a></p><a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a></p><hr/>Follow me on:</p>* <a href="https://gumroad.com/vasudevram/follow">Gumroad</a> * <a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></p> * <a href="https://mobile.twitter.com/vasudevram">Twitter</a></p>Do you create online products? Get Convertkit:</p><a href="http://mbsy.co/convertkit/28519854">Email marketing for digital product creators</a></p><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-42408452685934290882019-04-07T04:50:00.001+05:302019-04-07T04:50:57.269+05:30Updated my Codementor profile with my training page link (Python, Linux, SQL, ...)Hi, readers,
<br>
<br>I updated my Codementor profile with my training page link (Python,
<br>Linux, SQL, ...)
<br>
<br>See:
<br>
<br> <a href="https://www.codementor.io/vasudevram">https://www.codementor.io/vasudevram</a>
<br>
<br>And the direct link to the training page is here, with course outlines
<br>and testimonials:
<br>
<br> <a href="https://jugad2.blogspot.com/p/training.html">https://jugad2.blogspot.com/p/training.html</a>
<br>
<br>Also, I will be posting in the way I have done for this current post -
<br>i.e. via Blogger's email-to-blog service - which has limited
<br>functionality (e.g. less formatting options) - until this Google
<br>Blogger UI issue (which started for me a few days ago) is resolved:
<br>
<br> <a href="https://jugad2.blogspot.com/2019/04/test-post-via-email-to-check-some.html">https://jugad2.blogspot.com/2019/04/test-post-via-email-to-check-some.html</a>
<br>
<br>Until then, sorry for the inconvenience.
<br>
<br>And/or may start another blog on a different blogging platform. Will
<br>keep my readers posted about what I decide, and will share the link to
<br>the new blog here if I do create a new one.
<br>
<br>Thanks.
<br>Vasudev
<br>
<br>--
<br>Training: Python, SQL, Linux, more:
<br><a href="https://jugad2.blogspot.com/p/training.html">https://jugad2.blogspot.com/p/training.html</a>
<br>Web site: <a href="https://vasudevram.github.io">https://vasudevram.github.io</a>
<br>Blog: <a href="https://jugad2.blogspot.com">https://jugad2.blogspot.com</a>
<br>Products: <a href="https://gumroad.com/vasudevram">https://gumroad.com/vasudevram</a><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-36232072349982398682019-04-06T22:36:00.001+05:302019-04-06T22:36:14.887+05:30Test post via email to check some Blogger issueTest post via Blogger's email-to-blog service, to check some possible
<br>Blogger issue that is preventing me from writing posts and managing my
<br>blog in the regular web-based admin interface.
<br>
<br>- Vasudev
<br>
<br>--
<br>Training: Python, SQL, Linux, more:
<br><a href="https://jugad2.blogspot.com/p/training.html">https://jugad2.blogspot.com/p/training.html</a>
<br>Web site: <a href="https://vasudevram.github.io">https://vasudevram.github.io</a>
<br>Blog: <a href="https://jugad2.blogspot.com">https://jugad2.blogspot.com</a>
<br>Products: <a href="https://gumroad.com/vasudevram">https://gumroad.com/vasudevram</a><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-62298357401681300502019-04-01T04:39:00.001+05:302019-04-01T05:19:45.152+05:30rmline: Python command-line utility to remove lines from a file [Rosetta Code solution]<a href=""></a><br />
<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><a href="https://en.wikipedia.org/wiki/Pipeline_(Unix)"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Pipeline.svg/506px-Pipeline.svg.png"></img></a><br />
<br />
<small><small><a href="https://en.wikipedia.org/wiki/File:Pipeline.svg">Pipeline image attribution</a></small></small><br />
<br />
Hi readers,<br />
<br />
Long time no post. Sorry.<br />
<br />
I saw this programming problem about <a href="https://rosettacode.org/wiki/Remove_lines_from_a_file">removing lines from a file</a> on <a href="http://www.rosettacode.org/wiki/Rosetta_Code">Rosetta Code</a>.<br />
<br />
<a href="https://en.wikipedia.org/wiki/Rosetta_Code">Rosetta Code (Wikipedia)</a> is a programming <a href="https://en.wikipedia.org/wiki/Chrestomathy">chrestomathy</a> site.<br />
<br />
It's a simple problem, so I thought it would make a good example for Python beginners.<br />
<br />
So I wrote a program to solve it. To get the benefits of reuse and composition (at the <a href="https://en.wikipedia.org/wiki/Command-line_interface">command line</a>), I wrote it as a <a href="https://en.wikipedia.org/wiki/Unix">Unix</a>-style <a href="https://en.wikipedia.org/wiki/Filter_(software)">filter</a>.<br />
<br />
Here it is, in file <b>rmline.py</b>:<br />
<pre># Author: Vasudev Ram
# Copyright Vasudev Ram
# Product store:
# https://gumroad.com/vasudevram
# Training (course outlines and testimonials):
# https://jugad2.blogspot.com/p/training.html
# Blog:
# https://jugad2.blogspot.com
# Web site:
# https://vasudevram.github.io
# Twitter:
# https://twitter.com/vasudevram
# Problem source:
# https://rosettacode.org/wiki/Remove_lines_from_a_file
from __future__ import print_function
import sys
from error_exit import error_exit
# globals
sa, lsa = sys.argv, len(sys.argv)
def usage():
print("Usage: {} start_line num_lines file".format(sa[0]))
print("Usage: other_command | {} start_line num_lines".format(
sa[0]))
def main():
# Check number of args.
if lsa < 3:
usage()
sys.exit(0)
# Convert number args to ints.
try:
start_line = int(sa[1])
num_lines = int(sa[2])
except ValueError as ve:
error_exit("{}: ValueError: {}".format(sa[0], str(ve)))
# Validate int ranges.
if start_line < 1:
error_exit("{}: start_line ({}) must be > 0".format(sa[0],
start_line))
if num_lines < 1:
error_exit("{}: num_lines ({}) must be > 0".format(sa[0],
num_lines))
# Decide source of input (stdin or file).
if lsa == 3:
in_fil = sys.stdin
else:
try:
in_fil = open(sa[3], "r")
except IOError as ioe:
error_exit("{}: IOError: {}".format(sa[0], str(ioe)))
end_line = start_line + num_lines - 1
# Read input, skip unwanted lines, write others to output.
for line_num, line in enumerate(in_fil, 1):
if line_num < start_line:
sys.stdout.write(line)
elif line_num > end_line:
sys.stdout.write(line)
in_fil.close()
if __name__ == '__main__':
main()
</pre><br />
Here are a few test text files I tried it on:<br />
<pre>$ dir f?.txt/b
f0.txt
f5.txt
f20.txt
</pre>f0.txt has 0 bytes.<br />
Contents of f5.txt:<br />
<pre>$ type f5.txt
line 1
line 2
line 3
line 4
line 5
</pre>f20.txt is similar to f5.txt, but with 20 lines.<br />
<br />
Here are a few runs of the program, with output:<br />
<pre>$ python rmline.py
Usage: rmline.py start_line num_lines file
Usage: other_command | rmline.py start_line num_lines
$ dir | python rmline.py
Usage: rmline.py start_line num_lines file
Usage: other_command | rmline.py start_line num_lines
</pre>Both the above runs show that when called with an invalid set of <br />
arguments (none, in this case), it prints a usage message and exits.<br />
<pre>$ python rmline.py f0.txt
Usage: rmline.py start_line num_lines file
Usage: other_command | rmline.py start_line num_lines
</pre>Same result, except I gave an invalid first (and only) argument, a file name. See the usage() function in the code to know the right order and types of arguments.<br />
<pre>$ python rmline.py -3 4 f0.txt
rmline.py: start_line (-3) must be > 0
$ python rmline.py 2 0 f0.txt
rmline.py: num_lines (0) must be > 0
</pre>The above two runs shows that it checks for invalid values for the <br />
first two expected integer argyuments, start_line and num_line.<br />
<pre>$ python rmline.py 1 2 f0.txt
</pre>For an empty input file, as expected, it both removes and prints nothing.<br />
<pre>$ python rmline.py 1 2 f5.txt
line 3
line 4
line 5
</pre>The above run shows it removing lines 1 through 2 (start_line = 1, num_lines = 2) of the input from the output.<br />
<pre>$ python rmline.py 7 4 f5.txt
line 1
line 2
line 3
line 4
line 5
</pre>The above run shows that if you give a starting line number larger than the last input line number, it removes no lines of the input.<br />
<pre>$ python rmline.py 1 10 f20.txt
line 11
line 12
line 13
line 14
line 15
line 16
line 17
line 18
line 19
line 20
</pre>The above run shows it removing the first 10 lines of the input.<br />
<pre>$ python rmline.py 6 10 f20.txt
line 1
line 2
line 3
line 4
line 5
line 16
line 17
line 18
line 19
line 20
</pre>The above run shows it removing the middle 10 lines of the input.<br />
<pre>$ python rmline.py 11 10 f20.txt
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
</pre>The above run shows it removing the last 10 lines of the input.<br />
<br />
Read more:<br />
<br />
<a href="https://en.wikipedia.org/wiki/Pipeline_(computing)">Pipeline (computing)</a><br />
<br />
<a href="https://en.wikipedia.org/wiki/Redirection_(computing)">Redirection (computing)</a><br />
<br />
The image at the top of the post is of a <a
href="https://en.wikipedia.org/wiki/Pipeline_(Unix)">Unix-style pipeline</a>, with standard input (stdin), standard output (stdout) and standard error (stderr) streams of programs, all independently redirectable, and with the standard output of a preceding command piped to the standard input of the succeeding command in the pipeline. Pipelines and I/O redirection are one of the powerful features of the Unix operating system and shell.<br />
<br />
Read a brief introduction to those concepts in an article I wrote for <b>IBM developerWorks</b>:<br />
<br />
<a
href="https://jugad2.blogspot.com/2014/09/my-ibm-developerworks-article.html">Developing a Linux command-line utility</a><br />
<br />
The above link is to a post about that utility on my blog. For the<br />
actual code for the utility (in C), and for the PDF of the article,<br />
follow the relevant links in the post.<br />
<br />
I had originally written the utility for production use for one of the <br />
largest motorcycle manufacturers in the world.<br />
<br />
Enjoy.<br />
<br />
</pre><br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-77251237917336008742019-03-16T00:39:00.001+05:302019-03-16T00:40:06.961+05:30What did Al Gore Ythm say to Data St. Ructure?By <a href="https://jugad2.blogspot.in/p/about-vasudev-ram.html">Vasudev Ram</a> <a href=""></a><br />
<br />
What did <b>Al Gore Ythm</b> say to <b>Data St. Ructure</b>?<br />
<br />
When we mate, we'll create a <a href="https://en.wikipedia.org/wiki/Algorithms_%2B_Data_Structures_%3D_Programs">Pro G. Ramma</a>!<br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><p/>Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>, vetted by two Windows system administrator friends.</p>Jump to posts: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a></p><a href="https://jugad2.blogspot.com/p/training.html">Interested in a Python, SQL or Linux course?</a></p><a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">Get WP Engine, powerful managed WordPress hosting.</a></p><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">Subscribe to my blog (jugad2.blogspot.com) by email</a></p><a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a></p><hr/>Follow me on:</p>* <a href="https://gumroad.com/vasudevram/follow">Gumroad</a> * <a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></p> * <a href="https://mobile.twitter.com/vasudevram">Twitter</a></p>Do you create online products? Get Convertkit:</p><a href="http://mbsy.co/convertkit/28519854">Email marketing for digital product creators</a></p><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-83828660000965217862019-02-16T02:42:00.001+05:302019-02-16T03:21:04.276+05:30pprint.isrecursive: Check if object requires recursive representation<br />
<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><div class="separator" style="clear: both; text-align: center;"><a href="https://upload.wikimedia.org/wikipedia/commons/f/f7/RecursiveTree.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://upload.wikimedia.org/wikipedia/commons/f/f7/RecursiveTree.JPG" width="243" height="320" data-original-width="380" data-original-height="501" /></a></div><br />
<small><small><a href="https://en.wikipedia.org/wiki/File:RecursiveTree.JPG">Tree image attribution</a></small></small><br />
<br />
Hi, readers,<br />
<a href=""></a><br />
I was using the <a href="https://docs.python.org/3/library/pprint.html">pprint</a> <a href="https://docs.python.org/2/library/pprint.html">module</a> to pretty-print some Python data structures in a program I was writing. Then saw that it has a function called <b>isrecursive</b>.<br />
<br />
The docstring for <b>pprint.isrecursive</b> says:<br />
<pre>>>> print pprint.isrecursive.__doc__
Determine if object requires a <a href="https://en.wikipedia.org/wiki/Recursion_(computer_science)#Recursive_data_structures_(structural_recursion)">recursive representation</a>.
</pre>Here is a <b>Python 3</b> shell session that shows what the <i>isrecursive</i> function does, with a list:<br />
<pre>>>> import pprint
>>> print(pprint.pprint.__doc__)
Pretty-print a Python object to a stream [default is sys.stdout].
>>> a = []
>>> a
[]
>>> pprint.isrecursive(a)
False
>>>
>>> a.append(a)
>>> a
[[...]]
>>>
>>> pprint.isrecursive(a)
True
</pre>How about for a dict?<br />
<pre>>>> b = {}
>>> pprint.isrecursive(b)
False
>>>
>>> b[1] = b
>>> b
{1: {...}}
>>> id(b) == id(b[1])
True
>>> pprint.isrecursive(b)
True
</pre>How about if an object is recursive, but not directly, like in the above two examples? Instead, it is recursive via a chain of objects:<br />
<pre>>>> c = []
>>> d = []
>>> e = []
>>> c.append(d)
>>> d.append(e)
>>> c
[[[]]]
>>> pprint.isrecursive(c)
False
>>> e.append(c)
>>> c
[[[[...]]]]
>>> pprint.isrecursive(c)
True
</pre>So we can see that <i>isrecursive</i> is useful to detect some recursive Python object structures.<br />
Interestingly, if I <b>compare c with c[0]</b> (<b>after</b> making c a recursive structure), I get:<br />
<pre>>>> c == c[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded in comparison
>>>
</pre>In <b>Python 2</b>, I get:<br />
<pre>RuntimeError: maximum recursion depth exceeded in cmp
</pre><br />
Also, <a href="https://thomaspark.co/2017/01/relevant-xkcd/">relevant <b>XKCD-clone</b></a>.<br />
<br />
The image at the top of the post is of a tree created in the <a href="https://en.wikipedia.org/wiki/Logo_(programming_language)">LOGO programming language</a> using <a href="https://jugad2.blogspot.com/2013/12/google-gets-recursion.html">recursion</a>.<br />
<br />
- Enjoy.<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
<a href="https://www.a2hosting.com/?aid=vasudevram">Get a fast web site with A2 Hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-61701602366133808792019-02-06T04:33:00.001+05:302019-02-06T15:43:16.350+05:30Exploring the /proc filesystem: an article by me in Linux Pro Magazine<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/>Hi, readers,<br />
<br />
Somewhat recently, I wrote this article which was published in <b>Linux Pro Magazine</b>:<br />
<br />
<a href="http://www.linux-magazine.com/Issues/2018/217/Exploring-proc">Exploring the /proc filesystem with Python and shell commands</a><br />
<br />
As the title suggests, it is about <b>getting information</b> from the <b>Linux /proc file system</b>, which is a <b>pseudo-file system</b> that contains different kinds of information about <b>running processes</b>. The article shows some ways of getting a few kinds of information of interest about one or more <b>specified processes</b> from <b>/proc</b>, using both <b>Python programs</b> and <b>Linux shell commands</b> or scripts. It also shows a bit of <b>shell quoting magic</b>.<br />
<br />
(The article has a few small errors that crept in, late in the publishing process, but any programmer with a bit of Python knowledge will be able to spot them and still understand the article.)<br />
<br />
<a href="http://www.linux-magazine.com/Issues/2018/217/Exploring-proc">Check it out</a>.<br />
<br />
Enjoy.<br />
<br />
- Vasudev<br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-27981745113919114892019-01-29T01:37:00.004+05:302019-01-29T02:28:59.146+05:30Daily Coding Problem #69: A functional programming solution<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><a href=""></a><br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Reducing_the_sauce.jpg/640px-Reducing_the_sauce.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Reducing_the_sauce.jpg/640px-Reducing_the_sauce.jpg" data-original-width="640" data-original-height="425" /></a></div><br />
<small><small><a href="https://commons.wikimedia.org/wiki/File:Reducing_the_sauce.jpg">Stock reduction image attribution</a></small></small><br />
<br />
Hi, readers,<br />
<br />
I subscribed to the mailing list of the <a href="https://www.dailycodingproblem.com/">Daily Coding Problem site</a> site a while ago. It's a useful site. Their <b>modus operandi</b> is to send you <b>one programming problem per day</b>, described in English. You try to solve them, in any programming language of your choice. (They say that some of the questions were asked by companies like Google, Facebook, Amazon, Microsoft, Netflix, etc.) Something like <a href="https://en.wikipedia.org/wiki/Rosetta_Code">Rosetta Code</a>.<br />
The idea is that you can use this to practice and improve your programming and algorithm development skills.<br />
<br />
I haven't been attempting to solve every problem I get in email from them, as of now. I just try one now and then. Hope to attempt more later.<br />
<br />
Daily Coding Problem #69 is one that I tried, and solved, using a <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a> approach.<br />
<br />
This is the problem statement (taken from the email I got from them):<br />
<hr>Daily Coding Problem: Problem #69<br />
To: vasudevram@gmail.com<br />
Good morning! Here's your coding interview problem for today.<br />
<br />
This problem was asked by Facebook.<br />
<br />
Given a list of integers, return the largest product that can be made by multiplying any three integers.<br />
<br />
For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 * -10 * 5.<br />
<br />
You can assume the list has at least three integers.<br />
<hr/>And here is my functional-style solution below (actually, two variants on a solution). For this post, I've used a slightly different format than what I usually use - instead of alternating code and (text) explanations, I've put all the explanations in the code, as comments - sort of like <a href="https://en.wikipedia.org/wiki/Literate_programming">literate programming</a>.<br />
<pre># daily_coding_problem_069.py
# Problem source: https://dailycodingproblem.com
# Solution created by Vasudev Ram
# Website: https://vasudevram.github.io
# Copyright 2019 Vasudev Ram
# Blog: https://jugad2.blogspot.com
# Python posts: https://jugad2.blogspot.com/search/label/python
# Product store: https://gumroad.com/vasudevram
# Twitter: https://mobile.twitter.com/vasudevram
# LinkedIn: https://linkedin.com/in.vasudevram
"""
Daily Coding Problem: Problem #69
This problem was asked by Facebook.
Given a list of integers, return the largest product that can be made
by multiplying any three integers.
For example, if the list is [-10, -10, 5, 2], we should return 500,
since that's -10 * -10 * 5.
You can assume the list has at least three integers.
"""
from __future__ import print_function
try:
reduce
except NameError as ne:
from functools import reduce
from itertools import combinations
# Create a list with a few numbers.
lis = range(1, 6)
print()
print("lis:", lis)
# First, print the combinations iterator object.
print("combinations(lis, 3):", combinations(lis, 3))
# Next, print the combinations themselves.
print("list(combinations(lis, 3)):\n" + \
"\n".join(str(item) for item in list(combinations(lis, 3))))
print()
# Then define a function that takes an iterable and returns
# the product of all the numbers in it.
def product(iterable):
p = 1
for i in iterable:
p *= i
return p
# Test the product function a few times:
print("product(range(10)):", product(range(10)))
print("product(range(1, 11)):", product(range(1, 11)))
print("product(range(1, 6, 2)):", product(range(1, 6, 2)))
print("product(range(1, 10, 2)):", product(range(1, 10, 2)))
print()
# Now use the product function with the combinations function
# to solve Daily Coding Problem #69:
print("max(map(product, combinations(lis, 3)):", \
max(map(product, combinations(lis, 3))))
# Now let's solve the same problem with reduce and operator.mul
# instead of the product function above:
# Here is the docstring for reduce:
print("reduce.__doc__:", reduce.__doc__)
print
from operator import mul
# Here is the docstring for mul:
print("operator.mul.__doc__:", mul.__doc__)
print()
# Show how reduce works with mul with a few examples:
print("reduce(mul, range(1, 5)):", reduce(mul, range(1, 5)))
print("reduce(mul, range(3, 7)):", reduce(mul, range(3, 7)))
print()
# Use reduce-with-mul instead of product.
print("max(map(lambda s: reduce(mul, s), combinations(lis, 3))):", \
max(map(lambda s: reduce(mul, s), combinations(lis, 3))))
# Here's the call using product again for comparison:
print("max(map(product, combinations(lis, 3))):", \
max(map(product, combinations(lis, 3))))
print()
# A few more calls to the reduce-with-mul version:
lis4 = range(1, 5)
print("lis4:", lis4)
print("max(map(lambda s: reduce(mul, s), combinations(lis4, 3))):", \
max(map(lambda s: reduce(mul, s), combinations(lis4, 3))))
print()
lis6 = range(1, 7)
print("lis6:", lis6)
print("max(map(lambda s: reduce(mul, s), combinations(lis6, 3))):", \
max(map(lambda s: reduce(mul, s), combinations(lis6, 3))))
print()
lis7 = range(1, 8)
print("lis7:", lis7)
print("max(map(lambda s: reduce(mul, s), combinations(lis7, 3))):", \
max(map(lambda s: reduce(mul, s), combinations(lis7, 3))))
print()
# And finally, here is the solution run again with the example
# input given in the Facebook problem mentioned above:
lis_fb = [-10, -10, 5, 2]
print("lis_fb:", lis_fb)
print("max(map(lambda s: reduce(mul, s), combinations(lis_fb, 3))):", \
max(map(lambda s: reduce(mul, s), combinations(lis_fb, 3))))
print()
# The result matches the given answer, 500.
# Now let's modify the Faceboook input and run the code again:
lis_fb2 = [-10, 8, -10, 9, 5, 7, 2]
# (Added values 8, 9 and 7 to the list.)
print("lis_fb2:", lis_fb2)
print("max(map(lambda s: reduce(mul, s), combinations(lis_fb2, 3))):", \
max(map(lambda s: reduce(mul, s), combinations(lis_fb2, 3))))
print()
# The result is right again, since -10 * -10 * 9 = 900 is
# the largest product.
</pre><br />
Here is the output of a run of the program using Python 3:<br />
<pre>lis: range(1, 6)
combinations(lis, 3): <itertools.combinations object at 0x0000000001DA9598>
list(combinations(lis, 3)):
(1, 2, 3)
(1, 2, 4)
(1, 2, 5)
(1, 3, 4)
(1, 3, 5)
(1, 4, 5)
(2, 3, 4)
(2, 3, 5)
(2, 4, 5)
(3, 4, 5)
product(range(10)): 0
product(range(1, 11)): 3628800
product(range(1, 6, 2)): 15
product(range(1, 10, 2)): 945
max(map(product, combinations(lis, 3)): 60
reduce.__doc__: reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
operator.mul.__doc__: Same as a * b.
reduce(mul, range(1, 5)): 24
reduce(mul, range(3, 7)): 360
max(map(lambda s: reduce(mul, s), combinations(lis, 3))): 60
max(map(product, combinations(lis, 3))): 60
lis4: range(1, 5)
max(map(lambda s: reduce(mul, s), combinations(lis4, 3))): 24
lis6: range(1, 7)
max(map(lambda s: reduce(mul, s), combinations(lis6, 3))): 120
lis7: range(1, 8)
max(map(lambda s: reduce(mul, s), combinations(lis7, 3))): 210
lis_fb: [-10, -10, 5, 2]
max(map(lambda s: reduce(mul, s), combinations(lis_fb, 3))): 500
lis_fb2: [-10, 8, -10, 9, 5, 7, 2]
max(map(lambda s: reduce(mul, s), combinations(lis_fb2, 3))): 900
I also tested it with Python 2 and it gave basically the same output,
maybe with the exception of some minor message differences between 2 and 3.
So I'm not showing the 2 output here.
</pre><br />
The image at the top of the post is of stock with bay leaf and thyme being <b>reduced</b> in a pan.<br />
Here is the Wikipedia article about <a href="https://en.wikipedia.org/wiki/Reduction_(cooking)">reduction in cooking</a>.<br />
<br />
The functional programming meaning of reduce sort of matches the cooking meaning, right? Heh.<br />
<br />
Enjoy.<br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
<a href="https://www.sendowl.com/?r=c7f16">Sell More Digital Products With SendOwl</a>.<br />
<br />
<a href="https://www.a2hosting.com/?aid=vasudevram">Get a fast web site with A2 Hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul> <li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-91352235399741204962019-01-22T15:56:00.001+05:302019-01-22T16:01:07.742+05:30Factorial one-liner using reduce and mul for Python 2 and 3<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><big><big><big>$ foo bar | baz</big></big></big><br />
<br />
Hi, readers,<br />
<br />
A couple of days ago, I wrote this post for computing factorials using the <b>reduce</b> and <b>operator.mul</b> functions:<br />
<br />
<a href="https://jugad2.blogspot.com/2019/01/factorial-function-using-reduce-function.html">Factorial function using Python's reduce function</a><br />
<br />
A bit later I realized that it can be made into a Python one-liner. Here is the one-liner - it works in both Python 2 and Python 3:<br />
<pre>$ py -2 -c "from __future__ import print_function; from functools
import reduce; from operator import mul; print(list(reduce(mul,
range(1, fact_num + 1)) for fact_num in range(1, 11)))"
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
$ py -3 -c "from __future__ import print_function; from functools
import reduce; from operator import mul; print(list(reduce(mul,
range(1, fact_num + 1)) for fact_num in range(1, 11)))"
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
</pre><br />
(I've split the commands above across multiple lines to avoid truncation while viewing, but if trying them out, enter each of the above commands on a single line.)<br />
<br />
A small but interesting point is that one of the imports is not needed in Python 2, and the other is not needed in Python 3:<br />
<br />
- importing <b>print_function</b> is not needed in Py 3, because in 3, print is a function, not a statement - but it is not an error to import it, for compatibility with Py 2 code - where it actually needs to be imported for compatibility with Py 3 code (for using print as a function), ha ha.<br />
<br />
- importing <b>reduce</b> is not needed in Py 2, because in 2, reduce is both a built-in and also available in the <b>functools</b> module - and hence it is not an error to import it.<br />
<br />
Because of the above two points, the same one-liner works in both Py 2 and Py 3.<br />
<br />
Can you think of a similar Python one-liner that gives the same output as the above (and for both Py 2 and 3), but can work without one of the imports above (but by removing the same import for both Py 2 and 3)? If so, type it in a comment on the post.<br />
<br />
<b>py</b> is <a href="https://jugad2.blogspot.com/2013/04/py-python-launcher-for-windows.html">The Python launcher for Windows</a>.<br />
<br />
Enjoy.<br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><br />
<br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-40574432434873385402019-01-21T03:57:00.001+05:302019-01-21T04:25:22.335+05:30Factorial function using Python's reduce function<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><a href=""></a><br />
<br />
[This is a <b>beginner-level</b> Python post. I label such posts as "<b>python-beginners</b>" in the Blogger labels at the bottom of the post. You can get a <b>sub-feed</b> of all such posts for any label using the label (case-sensitive) in a URL of the form:<br />
<br />
https://jugad2.blogspot.com/search/label/label_name where label_name is to be replaced by an actual label, <br />
<br />
such as in:<br />
<br />
<a href="https://jugad2.blogspot.com/search/label/python-beginners">jugad2.blogspot.com/search/label/python-beginners</a><br />
<br />
and<br />
<br />
<a href="https://jugad2.blogspot.com/search/label/python">jugad2.blogspot.com/search/label/python</a><br />
]<br />
<br />
Hi, readers,<br />
<br />
The <b>factorial</b> function (<a href="https://en.wikipedia.org/wiki/Factorial">Wikipedia article</a>) is often implemented in programming languages as either an iterative or a recursive function. Both are fairly simple to implement.<br />
<br />
For the <b>iterative</b> version, to find the value of <b>n factorial</b> (written <b>n!</b> in mathematics), you set a variable called, say, product, equal to 1, then multiply it in a loop by each value of a variable i that ranges from 1 to n.<br />
<br />
For the <b>recursive</b> version, you define the <b>base case</b> as <b>0! = 1</b>, and then for all higher values of n factorial, you compute them <b>recursively</b> as the product of n with (n - 1) factorial. <br />
<br />
[ Wikipedia article about <a href="https://en.wikipedia.org/wiki/Iteration">Iteration</a>. ]<br />
<br />
[ Wikipedia article about <a href="https://en.wikipedia.org/wiki/Recursion_(computer_science)">Recursion in computer_science</a>. ]<br />
<br />
Here is another way of doing it, which is also iterative, but uses <b>no explicit loop</b>; instead it uses Python's <a href="https://docs.python.org/2/library/functions.html#reduce">built-in</a> <b><a href="https://en.wikipedia.org/wiki/Fold_(higher-order_function)#Examples">reduce()</a> function</b>, which is part of the <b><a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a></b> paradigm or style:<br />
<pre>In [179]: for fact_num in range(1, 11):
...: print reduce(mul, range(1, fact_num + 1))
...:
1
2
6
24
120
720
5040
40320
362880
3628800
</pre>The above snippet (run in IPython - command-line version), loops over the values 1 to 10, and computes the factorial of each of those values, using <b>reduce</b> with <b>operator.mul</b> (which is a functional version of the multiplication operator). In more detail: the function call <b>range(1, 11)</b> returns a list with the values 1 to 10, and the for statement iterates over those values, passing each to the expression involving reduce and mul, which together compute each value's factorial, using the iterable returned by the second range call, which produces all the numbers that have to be multiplied together to get the factorial of fact_num.<br />
<br />
The Python <b>docstring</b> for reduce:<br />
<pre>reduce.__doc__: reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
</pre>Did you know that there are many different kinds of factorials? To learn more, check out this post:<br />
<br />
<a href="https://jugad2.blogspot.com/2016/10/by-vasudev-ram-nicomachus-theorem-3d.html">Permutation facts</a><br />
<br />
- Enjoy.<br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
<a href="https://www.sendowl.com/?r=c7f16">Sell More Digital Products With SendOwl</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com3tag:blogger.com,1999:blog-6692866151143183230.post-59678766304055245512019-01-18T02:34:00.000+05:302019-01-18T02:46:04.185+05:30Announcing PIaaS - Python Interviewing as a Service<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://4.bp.blogspot.com/-VrpYGL40ULw/XEDtsZvd5UI/AAAAAAAAB2M/VV_xBDG6ww0V3CGYwriBcTUkTZumZojuQCLcBGAs/s1600/PIaaS-01.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://4.bp.blogspot.com/-VrpYGL40ULw/XEDtsZvd5UI/AAAAAAAAB2M/VV_xBDG6ww0V3CGYwriBcTUkTZumZojuQCLcBGAs/s400/PIaaS-01.png" width="400" height="164" data-original-width="1357" data-original-height="556" /></a></div><br />
Hello, readers,<br />
<br />
Announcing <b>Python Interviewing as a Service</b>:<br />
<br />
I'm now officially offering <b>PIaaS</b> - <i>Python Interviewing as a Service</i>. I have done it some earlier, informally, for clients. Recently a couple of companies asked me for help on this again, so I am now adding it to my list of offered services, the others being <a href="http://vasudevram.github.io/services.html">consulting</a> (software design and development, code review, technology evaluation and recommendation) and <a href="https://jugad2.blogspot.com/p/training.html">software training</a>.<br />
<br />
I can help your organization <b>interview and hire Python developer candidates</b>, offloading (some of) that work from your core technical and HR / recruitment staff.<br />
<br />
I can also interview on related areas like <b>SQL</b> and <b>RDBMS</b>, and <b>Unix</b> and <b>Linux commands</b> and <b>shell scripting</b>.<br />
<br />
I have long-term experience in all the above areas.<br />
<br />
To hire me for PIaaS or to learn more about it, contact me via the Gmail address on my site's <a href="https://vasudevram.github.io/contact.html">contact page</a>. <br />
<br />
- Vasudev Ram<br />
<br />
My Codementor profile: <a href="https://www.codementor.io/vasudevram">Vasudev Ram on Codementor</a><br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://3.bp.blogspot.com/-2FXGYEgNGM4/ViFMYvafNiI/AAAAAAAAA5E/oJVGnxL8n1E/s400/so-you-know-python.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://3.bp.blogspot.com/-2FXGYEgNGM4/ViFMYvafNiI/AAAAAAAAA5E/oJVGnxL8n1E/s320/so-you-know-python.jpg" width="320" height="318" data-original-width="385" data-original-height="382" /></a></div><br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-965920237667237722019-01-08T19:55:00.001+05:302019-01-08T20:41:40.863+05:30The Teachable Full-time Creator Masterclass 2019<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/>Hi, readers,<br />
<br />
As I said a few days ago in this post:<br />
<br />
<a href="https://jugad2.blogspot.com/2019/01/great-teachable-offer-coming-in-few-days.html">Great Teachable offer coming in a few days ...</a><br />
<br />
, here are the details for the <a href="https://mbsy.co/rpBVT"><b>Teachable Full-time Creator Masterclass</b></a> 2019.<br />
<br />
It will go on from 14th to 21st January 2019.<br />
<br />
What’s the <b>Full-time Creator masterclass</b>?<br />
<br />
The Full-time Creator is a <b>free</b>, 4-part <b>masterclass</b> that <b>Teachable</b> is hosting over the course of a <b>week</b> - consisting of <b>4</b> jam-packed <b>video trainings</b> that will be dripped out over <b>7 days</b>. The ideal <b>audience</b> for this <b>event</b> includes <b>creators</b> (think: bloggers, coaches, experts, authors, consultants, influencers, hobbyists, offline trainers, etc.) who want to <b>create</b> a profitable <b>online course</b>, using the knowledge they already have. After the week-long masterclass, they'll be offered an <b>opportunity</b> to <b>buy</b> Teachable's service — and when they do they'll receive <b>$4K+</b> in valuable <b>bonuses</b> for <b>free</b>.<br />
<br />
After the week-long masterclass, you will be invited to sign up for Teachable.<br />
<br />
Sign up for the <a href="https://mbsy.co/rpBVT"><b>Teachable Full-time Creator Masterclass</b></a> 2019 here.<br />
<br />
P.S. Although I've already been a trainer (both offline and online) for some years now, I plan to attend this Masterclass myself. I'm sure I'll pick up some useful tips that will help in my training work. <br />
<br />
See you there.<br />
<br />
- Vasudev.<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
<a href="https://www.sendowl.com/?r=c7f16">Sell More Digital Products With SendOwl</a>.<br />
<br />
<a href="https://www.a2hosting.com/?aid=vasudevram">Get a fast web site with A2 Hosting</a>.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-11278905719544751882019-01-06T03:50:00.000+05:302019-01-06T03:50:04.415+05:30Great Teachable offer coming in a few days ...<br />
... so watch this space.<br />
<br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-48514710773351159922019-01-03T22:59:00.000+05:302019-01-03T23:37:37.288+05:30Multiple item search in an unsorted list in Python<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><div class="separator" style="clear: both; text-align: center;"><a href="https://1.bp.blogspot.com/-TPdwYw1I2J8/V__yTw-2ZDI/AAAAAAAABWg/lTkuA_PcDJQSYjuShXWDbiJ5swEH7ufVACLcB/s1600/mg.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://1.bp.blogspot.com/-TPdwYw1I2J8/V__yTw-2ZDI/AAAAAAAABWg/lTkuA_PcDJQSYjuShXWDbiJ5swEH7ufVACLcB/s1600/mg.png" data-original-width="381" data-original-height="318" /></a></div><br />
<a href=""></a><br />
Hi, readers,<br />
<br />
I was reviewing simple algorithms with a view to using some as examples or exercises in my <a href="https://jugad2.blogspot.com/p/training.html">Python programming course</a>. While doing so, I thought of enhancing simple <a href="https://en.wikipedia.org/wiki/Linear_search">linear search</a> for one item in a list, to make it search for multiple items.<br />
<br />
Here are a couple of program versions I wrote for that task. They use straightforward logic. There are just a few additional points: <br />
<br />
- In both programs, I use a generator to yield the values found (the index and the item).<br />
- In the first program, I print out the index and item for each item found.<br />
- In the second program, I mark where the items are found with text "arrows".<br />
<br />
This is the first program, <b>mult_item_search_unsorted_list.py</b>:<br />
<pre># mult_item_search_unsorted_list.py
# Purpose: To search for multiple items in an unsorted list.
# Prints each item found and its index.
# Author: Vasudev Ram
# Copyright 2019 Vasudev Ram
# Training: https://jugad2.blogspot.com/p/training.html
# Blog: https://jugad2.blogspot.com
# Web site: https://vasudevram.github.io
# Product store: https://gumroad.com/vasudevram
from __future__ import print_function
import sys
from random import sample, shuffle
def mult_item_search_unsorted_list(dlist, slist):
for didx, ditem in enumerate(dlist):
for sitem in slist:
if sitem == ditem:
yield (didx, ditem)
def main():
# Create the search list (slist) with some items that will be found
# and some that will not be found in the data list (dlist) below.
slist = sample(range(0, 10), 3) + sample(range(10, 20), 3)
# Create the data list.
dlist = range(10)
for i in range(3):
# Mix it up, DJ.
shuffle(slist)
# MIX it up, DEK.
shuffle(dlist)
print("\nSearching for:", slist)
print(" in:", dlist)
for didx, ditem in mult_item_search_unsorted_list(dlist, slist):
print(" found {} at index {}".format(ditem, didx))
main()
</pre>Output of a run:<br />
<pre>$ python mult_item_search_unsorted_list.py
Searching for: [1, 18, 3, 15, 19, 4]
in: [8, 9, 1, 2, 0, 7, 5, 3, 6, 4]
found 1 at index 2
found 3 at index 7
found 4 at index 9
Searching for: [4, 19, 18, 15, 1, 3]
in: [7, 5, 8, 2, 9, 4, 0, 3, 6, 1]
found 4 at index 5
found 3 at index 7
found 1 at index 9
Searching for: [1, 3, 4, 18, 19, 15]
in: [9, 6, 1, 8, 7, 4, 3, 0, 2, 5]
found 1 at index 2
found 4 at index 5
found 3 at index 6
</pre>And this is the second program, <b>mult_item_search_unsorted_list_w_arrows.py</b>:<br />
<pre># mult_item_search_unsorted_list_w_arrows.py
# Purpose: To search for multiple items in an unsorted list.
# Marks the position of the items found with arrows.
# Author: Vasudev Ram
# Copyright 2019 Vasudev Ram
# Training: https://jugad2.blogspot.com/p/training.html
# Blog: https://jugad2.blogspot.com
# Web site: https://vasudevram.github.io
# Product store: https://gumroad.com/vasudevram
from __future__ import print_function
import sys
from random import sample, shuffle
def mult_item_search_unsorted_list(dlist, slist):
for didx, ditem in enumerate(dlist):
for sitem in slist:
if sitem == ditem:
yield (didx, ditem)
def main():
# Create the search list (slist) with some items that will be found
# and some that will not be found in the data list (dlist) below.
slist = sample(range(10), 4) + sample(range(10, 20), 4)
# Create the data list.
dlist = range(10)
for i in range(3):
# Mix it up, DJ.
shuffle(slist)
# MIX it up, DEK.
shuffle(dlist)
print("\nSearching for: {}".format(slist))
print(" in: {}".format(dlist))
for didx, ditem in mult_item_search_unsorted_list(dlist, slist):
print("---------{}^".format('---' * didx))
main()
</pre>Output of a run:<br />
<pre>$ python mult_item_search_unsorted_list_w_arrows.py
Searching for: [16, 0, 15, 4, 6, 1, 10, 12]
in: [8, 9, 0, 1, 5, 4, 7, 2, 6, 3]
---------------^
------------------^
------------------------^
---------------------------------^
Searching for: [6, 16, 10, 0, 1, 4, 12, 15]
in: [2, 7, 0, 8, 1, 4, 6, 3, 9, 5]
---------------^
---------------------^
------------------------^
---------------------------^
Searching for: [0, 12, 4, 10, 6, 16, 1, 15]
in: [8, 1, 0, 7, 9, 6, 2, 5, 4, 3]
------------^
---------------^
------------------------^
---------------------------------^
</pre><br />
In a recent post, <a href="https://jugad2.blogspot.com/2018/12/dynamic-function-creation-at-run-time_23.html">Dynamic function creation at run time with Python's eval built-in</a>, I had said:<br />
<br />
"Did you notice any pattern to the values of g(i)? The values are 1, 4, 9, 16, 25 - which are the squares of the integers 1 to 5. But the formula I entered for g was not x * x, rather, it was x * x + 2 * x + 1. Then why are squares shown in the output? Reply in the comments if you get it, otherwise I will answer next time."<br />
<br />
No reader commented with a solution. So here is a hint to figure it out: <br />
<br />
What is the expansion of (a + b) ** 2 (a plus b the whole squared) in algebra?<br />
<br />
Heh.<br />
<br />
The drawing of the magnifying glass at the top of the post is by:<br />
<br />
<i>Yours truly.</i><br />
<br />
( The same one that I used in this post: <br />
<a href="https://jugad2.blogspot.com/2016/10/command-line-d-utility-find-files.html">Command line D utility - find files matching a pattern under a directory</a> )<br />
<br />
I'll leave you with another question: What, if any, could be the advantage of using Python generators in programs like these?<br />
Notice that I said "<b>programs like these</b>", not "<b>these programs</b>".<br />
<br />
Enjoy.<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
<a href="https://www.a2hosting.com/?aid=vasudevram">Get a fast web site with A2 Hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com1tag:blogger.com,1999:blog-6692866151143183230.post-23282996617649149692019-01-01T02:23:00.002+05:302019-01-01T02:23:25.872+05:30A Happy New Year to all my readers<br />
Dear readers,<br />
<br />
Wishing all of you a happy new year.<br />
<br />
Cheers,<br />
<br />
- <a href="https://jugad2.blogspot.in/p/about-vasudev-ram.html">Vasudev Ram</a><br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-28703566480095957452018-12-29T23:56:00.000+05:302018-12-30T00:41:40.213+05:30The Zen of Python is well sed :)<br />
<a href="https://en.wikipedia.org/wiki/Zen" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://media.istockphoto.com/photos/black-zen-stones-in-shallow-water-picture-id155725093?k=6&m=155725093&s=612x612&w=0&h=9F-ZIsGuKWOh7I4NQaOi3frpX9KaAy17jPdXvbIkL9c=" data-original-width="612" data-original-height="459" /></a><br />
<br />
<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<a href=""></a><br />
<pre>$ python -c "import this" | sed -n "4,4p;15,16p"
Explicit is better than implicit.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
</pre><br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Or if you're a self-starter, check out my <a href="https://gumroad.com/l/Python-Course-01">Python programming course by email</a>.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-65002423705371710892018-12-23T00:04:00.002+05:302018-12-23T00:20:26.171+05:30Dynamic function creation at run time with Python's eval built-in<a href="https://vasudevram.github.io/">By Vasudev Ram</a><br />
<br />
<a href="https://en.wikipedia.org/wiki/Lambda" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/df/NAMA_Alphabet_grec.jpg/549px-NAMA_Alphabet_grec.jpg" data-original-width="549" data-original-height="480" /></a><br />
<br />
Hi, readers,<br />
<br />
A few days ago, I had published this post:<br />
<br />
<a href="https://jugad2.blogspot.com/2018/12/dynamic-function-creation-at-run-time.html">Dynamic function creation at run time with Python's exec built-in</a><br />
<br />
In today's post I'll show another way of dynamically creating functions at run time - this time using Python's <i>eval</i> built-in instead of <i>exec</i>.<br />
<br />
I'll show the code (<i>dyn_func_with_eval.py</i>), followed by its output.<br />
<pre># dyn_func_with_eval.py
# Purpose: To dynamically create (and run) a function at run time,
# using Python's eval built-in.
# Author: Vasudev Ram
# Copyright 2018 Vasudev Ram
# Web site: https://vasudevram.github.io
# Product store: https://gumroad.com/vasudevram
# Twitter: https://twitter.com/vasudevram
from __future__ import print_function
expr = raw_input("Enter a function of x: ")
print("expr: ", expr)
g = eval("lambda x: " + expr)
print("g:", g)
print("g.func_code.co_argcount:", g.func_code.co_argcount)
print("g.func_code.co_varnames:", g.func_code.co_varnames)
print("g(0):", g(0))
old_gi = 0
for i in range(5):
gi = g(i)
diff = gi - old_gi
print("i = {}, g({}) = {}, diff = {}".format(i, i, gi, diff))
old_gi = gi
</pre>As you can see, after prefixing the expression (that was input by the user) with "lambda x: ", to make it a complete <i>lambda function definition</i>, the program uses <i>eval()</i> (instead of <i>exec()</i> like last time), to <i>dynamically evaluate</i> the entered expression (which should represent a <i>function of x</i>).<br />
<br />
The end result is that the <i>lambda function</i> object is created and then bound to the name <i>g</i>. Then g is used in the remaining code.<br />
<br />
The values of g and g(0) are printed.<br />
<br />
Then, in a loop, g is evaluated for i ranging from 0 to 4. For each such value, i, g(i) and the difference between the old g(i) and the current one is printed. (No meaningful value can be given for the previous value of g(i) before g(0), so I used 0 arbitrarily; ignore that first difference).<br />
<br />
Now, the output:<br />
<pre>$ python dyn_func_with_eval.py
Enter a function of x: <i>x * x + 2 * x + 1</i>
expr: x * x + 2 * x + 1
g: <function <lambda> at 0x022D0A70>
g.func_code.co_argcount: 1
g.func_code.co_varnames: ('x',)
g(0): 1
i = 0, g(0) = 1, diff = 1
i = 1, g(1) = 4, diff = 3
i = 2, g(2) = 9, diff = 5
i = 3, g(3) = 16, diff = 7
i = 4, g(4) = 25, diff = 9
</pre><br />
Note that I used <i>Python introspection</i> to print the <i>argument count</i> and the <i>local variable names</i> of the generated function.<br />
<br />
So, it worked. We could enter a <i>function of x</i> via the keyboard, use <i>eval()</i> to <i>dynamically create</i> a Python function that uses it, and evaluate that function for some range of values. Are there any uses of this technique, other than to show that it is possible, and interesting? Sure, I can think of at least one: a <i>graphing calculator</i>. We could have a GUI window with a pane that can draw graphics, such as curves in the 2D plane (using one of the Python GUI toolkits like <i>wxPython</i> or <i>PyQt</i> that support this), and then repeatedly prompt the user for a function of x, eval() it as above, then <i>plot</i> the <i>values of x and y</i> (= g(x)) for a range, in a loop, to <i>draw a curve</i> that represents the function entered.<br />
<br />
Note: Use of exec and eval can be a <b>security risk</b>, so only use them in a trusted environment. The optional arguments globals and locals, which I did not use in these two posts, may be of use to control the environment in which they run, but user input is also important.<br />
<br />
In fact, the graphing calculator could probably be done as a <i>web app</i> too, using some Python web framework, such as <i>Flask, Bottle, Django</i> or other (a lightweight one may be better here, or even plain CGI), and a web form with an <i>HTML5 canvas</i> and some <i>JavaScript</i> on the front-end. The user could enter the formula (some function of x) in a text box, submit it, the back-end Python app could eval() it to create the function, evaluate that function for a range of points like I did above, and send the list of (x, y) pairs to the browser, where the JavaScript could draw a curve representing those points, on the canvas.<br />
<br />
Did you notice any pattern to the values of <i>g(i)</i>? The values are 1, 4, 9, 16, 25 - which are the <i>squares</i> of the integers 1 to 5. But the formula I entered for g was not <i>x * x</i>, rather, it was <i>x * x + 2 * x + 1</i>. Then why are squares shown in the output? Reply in the <br />
comments if you get it, otherwise I will answer next time.<br />
<br />
The image at the top of the post is from the <a href="https://en.wikipedia.org/wiki/Lambda">Wikipedia page about lambda</a> (the Greek letter) and is of the Greek alphabet on a <a href="https://en.wikipedia.org/wiki/Black-figure_pottery">black figure</a> vessel. Check out the many meanings and uses of the symbol/letter lambda in various fields (see that Wikipedia page).<br />
<br />
- Enjoy.<br />
<br />
<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">Vasudev Ram - online Python training and consulting</a><br />
<br />
<hr/>I conduct online courses on <i>Python</i> programming, <i>Unix / Linux</i> commands and shell scripting and <i>SQL</i> programming and <i>database design</i>, with <i>course material</i> and <i>personal coaching</i> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <i>most ubiquitous text editors around</i>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><br />
<div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-45700223169726809082018-12-21T02:18:00.000+05:302019-01-10T03:36:59.949+05:30FizzBuzz in Python with nested conditional expressions and a generator expression<hr/>- <a href="https://jugad2.blogspot.com/p/training.html">By Vasudev Ram - Online Python training / SQL training / Linux training</a><br />
<hr/><a href=""></a><br />
The <a href="https://en.wikipedia.org/wiki/Fizz_buzz">FizzBuzz</a> problem [1] is known to those who test/interview programming candidates, as one simple way to filter out unsuitable people early. One keeps on coming across mentions of it on tech sites.<br />
<br />
Here is a way of doing FizzBuzz in Python, not the most obvious way (which would be to use a for loop with an if/elif/else statement in it - although, of course, other ways are possible too). Instead, this way uses Python's language feature of conditional expressions:<br />
<pre># Fizzbuzz version using nested Python conditional expressions:
# Author: Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: https://jugad2.blogspot.com
# Twitter: https://mobile.twitter.com/vasudevram
for i in range(1, 101):
print "FizzBuzz" if i % 15 == 0 else "Buzz" if i % 5 == 0 \
else "Fizz" if i % 3 == 0 else str(i),
</pre>Output (formatted a bit to fit on the screen):<br />
<pre>$ python fizzbuzz_w_cond_expr.py
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz \
16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz \
31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz \
46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz \
61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz \
76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz \
91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
</pre><br />
Here's another use of such conditional expressions:<br />
<br />
<a href="https://jugad2.blogspot.com/2017/04/using-nested-conditional-expressions-to.html">Using nested conditional expressions to classify characters</a><br />
<br />
Here is another Fizzbuzz version that uses both nested Python conditional expressions and a generator expression (again, formatted):<br />
<pre># FizzBuzz with a Python nested conditional expression and
# a generator expression.
# Author: Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: https://jugad2.blogspot.com
# Twitter: https://mobile.twitter.com/vasudevram
print(" ".join("FizzBuzz" if i % 15 == 0 else "Buzz" if i % 5 == 0 else "Fizz" if i % 3 == 0 \
else str(i) for i in range(1, 101)))
</pre>It gives the same output as the earlier version above.<br />
<br />
What's the subtle aspect of the FizzBuzz problem that can trip up a naive candidate?<br />
<br />
The post by Jeff Atwood about FizzBuzz (below) is interesting.<br />
<br />
- Enjoy.<br />
<br />
[1] References:<br />
<br />
<a href="https://en.wikipedia.org/wiki/Fizz_buzz">Fizz Buzz (Wikipedia)</a><br />
<br />
<a href="http://www.codinghorror.com/blog/archives/000781.html">Jeff Atwood (2007-02-26): Why Can't Programmers.. Program?</a><br />
<br />
<a href="http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding">Imran Ghory (2007-01-24): "Using FizzBuzz to Find Developers who Grok Coding."</a><br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
<a href="https://www.sendowl.com/?r=c7f16">Sell More Digital Products With SendOwl</a>.<br />
<br />
<a href="https://www.a2hosting.com/?aid=vasudevram">Get a fast web site with A2 Hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
<a href="http://share.getf.ly/p35s5a">Managed WordPress hosting with Flywheel</a>.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-28799731422772391112018-12-16T20:02:00.005+05:302018-12-16T20:59:30.826+05:30Dynamic function creation at run time with Python's exec built-inBy <a href="https://jugad2.blogspot.in/p/about-vasudev-ram.html">Vasudev Ram</a><br />
<hr/>Hi, readers,<br />
I was browsing <a href="http://www.paulgraham.com/onlisp.html">Paul Graham's essay</a> about his book <a href="http://www.paulgraham.com/onlisptext.html">"On Lisp"</a>. It's about advanced uses of Lisp and some of the features that make it unique.<br />
<br />
In it, he talks about many Lisp features, like the ability to <b>treat code as data</b>, the fact that functions are <b>first-class objects</b>, so, just like other objects such as scalar variables, lists, maps, etc., they too can be passed as arguments to functions, returned from functions, stored in variables, etc., and the fact that <b>Lisp programs can <i>write</i> Lisp programs</b>. (There's a lot more to the book, of course.) This made me think of experimenting a bit with Python's dynamic features, whether similar to Lisp or not. One man's Lisp is another man's Python ...<br />
<a href=""></a><br />
I did know from a while ago that Python has many dynamic features, and have blogged about some of them in the past. (Search my blog for topics like <a href="https://jugad2.blogspot.com/search/label/Python-tricks">Python tricks</a>, the <a href="https://jugad2.blogspot.com/2013/06/pythons-trace-module-and-chained.html"></a>trace module and chained decorators, <a href="https://jugad2.blogspot.com/search/label/introspection"></a>Python introspection, the inspect module, finding the caller of a Python function, <a href="https://jugad2.blogspot.com/search/label/generators">Python generators are pluggable</a>, <a href="https://jugad2.blogspot.com/2017/04/implementing-and-using-callbacks-in.html">function-based callbacks</a>, <a href="https://jugad2.blogspot.com/2017/04/python-callbacks-using-classes-and.html">class-based callbacks</a>, and other fun stuff. Try using 'site:jugad2.blogspot.com' and suchlike search engine techniques.) This is one more such exploration.<br />
<br />
I got the idea of writing a program that can <b>dynamically</b> create a <b>function</b> at <b>run time</b>, based on some user input, and then run that function. The program uses the <a href="https://docs.python.org/2/reference/simple_stmts.html#the-exec-statement">exec built-in</a> of Python.<br />
<br />
Here is the program, <b>dyn_func_with_exec.py</b>:<br />
<pre># dyn_func_with_exec.py
# Purpose: To dynamically create (and run) a function at run time.
# Author: Vasudev Ram
# Copyright 2018 Vasudev Ram
# Web site: https://vasudevram.github.io
# Product store: https://gumroad.com/vasudevram
from __future__ import print_function
import sys
major = sys.version_info.major
if major == 2:
input_func = raw_input
elif major == 3:
input_func = input
else:
print("Unsupported version, go back to the future.")
sys.exit(0)
func_name = input_func("Enter name of function to create dynamically: ")
func_def = """
def {}(args):
print("In function", func_name, ": args:", args)
""".format(func_name)
exec(func_def)
print(func_name, ":", eval(func_name))
args1 = (1, "a"); args2 = (2, "b")
# Two ways of calling the dynamically created function:
print("\nCalling {} via eval():".format(func_name))
eval(func_name + "(args1)")
print("\nCalling {} via globals() dict:".format(func_name))
globals()[func_name](args2)
</pre>Here is the output of 3 runs:<br />
(<b>py</b> is <a href="https://jugad2.blogspot.com/2013/04/py-python-launcher-for-windows.html">the Python launcher for Windows</a>.)<br />
<pre>$ py -2 dyn_func_with_exec.py
Enter name of function to create dynamically: mu
mu : <function mu at 0x0000000002340518>
Calling mu via eval():
In function mu : args: (1, 'a')
Calling mu via globals() dict:
In function mu : args: (2, 'b')
$ py -3 dyn_func_with_exec.py
Enter name of function to create dynamically: _
_ : <function _ at 0x000000000039C1E0>
Calling _ via eval():
In function _ : args: (1, 'a')
Calling _ via globals() dict:
In function _ : args: (2, 'b')
$ py dyn_func_with_exec.py
Enter name of function to create dynamically: |
Traceback (most recent call last):
File "dyn_func_with_exec.py", line 28, in <module>
exec(func_def)
File "<string> line 2
def |(args):
^
SyntaxError: invalid syntax
</pre>So it works in both Python 2 and 3. The last run (with an invalid function name) shows how the user input gets interpolated into the function definition string <i>func_def</i>.<br />
<br />
The if statement used shows another <b>dynamic aspect of Python</b>: the ability to call different functions (via <b>the same name, input_func</b>), based on some condition which is only known at run time (the Python version, in this case).<br />
<br />
Why <b>mu</b> for the input? Well, if foo, why not mu? :)<br />
See <a href="https://news.ycombinator.com/item?id=18642983">my HN comment here</a><br />
<br />
Another way to dynamically decide which function to run:<br />
<br />
<a href="https://jugad2.blogspot.com/2016/06/driving-python-function-execution-from.html">Driving Python function execution from a text file</a><br />
<br />
Enjoy.<br />
<a href=""></a><br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><br />
<hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<br />
<br />
<a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><br />
<br />
<a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<br />
<br />
Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<br />
<br />
Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<br />
<br />
Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<br />
<br />
Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>. I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<br />
<br />
<a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<br />
<br />
Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<br />
<br />
Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<br />
<br />
<a href="https://www.a2hosting.com/?aid=vasudevram">Get a fast web site with A2 Hosting</a>.<br />
<br />
Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><br />
<br />
<a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><br />
<br />
Follow me on:<br />
<ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-722238647916220252018-12-03T02:52:00.002+05:302018-12-03T04:29:20.560+05:30Tower of Hanoi program in Higher-Order Perl book, ported to Python<a href=""></a><br />
Hi, readers,<br />
<br />
I was reading the book <a href="https://hop.perl.plover.com/book/">Higher Order Perl</a> (<a href="https://en.wikipedia.org/wiki/Higher-Order_Perl">Wikipedia entry</a>). It is by Mark Jason Dominus, a well-known figure in the Perl community. I've only read a bit of it so far, but it already looks very good. There are also many reviews of it, all of which say that it is a good book, including one by <a href="https://en.wikipedia.org/wiki/Damian_Conway">Damian Conway</a>, another well-known Perl figure.<br />
<br />
Early in the book, in chapter 1 - Recursion and Callbacks, there is a nice example program showing how to solve the <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi">Tower of Hanoi</a> problem. I had come across the problem earlier, but had not seen a Perl solution before. It's not really any different from the same kind of solution written in other languages, except for some points related to Perl's syntax and semantics, such as the use of local (Perl's <b>my</b>) vs. global variables, specifically with regard to a recursive function, which is what Mark uses for Hanoi. <br />
<br />
Anyway, since I had not implemented Hanoi before, I thought of porting Mark's <b>hanoi</b> function from Perl to Python. It's an easy <a href="https://jugad2.blogspot.com/2013/12/google-gets-recursion.html">recursive</a> algorithm. (The Wikipedia article has multiple algorithms for Hanoi, some non-recursive too.)<br />
<br />
I wrote two versions: the first is hard-coded to solve it for a tower with <b>n</b> equal to 3, where n is the number of disks, and the second does it in a loop for <b>n</b> ranging from 1 to 4, with a prompt and a pause after each one.<p/>If you press <b>q</b> at any of the prompts, the program quits. If you press any other key, it goes on to the next iteration, until the last one. For reading a keypress without needing to press <b>Enter</b>, I used the <b>getch</b> function (get character) from the msvcrt module that comes with Python. MSVCRT stands for Microsoft Visual C Run Time.<p/>So this program is <b>Windows-specific</b>. There are equivalent ways of reading a character without needing to press Enter, for Linux too, but they usually involve some low-level fiddling with the <b>tty / terminal</b> settings, <b>termios</b>, etc. I think <a href="http://code.activestate.com/recipes/">ActiveState Code</a> has a recipe for a <b>getch-like function</b> that works on <b>Linux</b>.<p/>Here is the first version, <b>hanoi_01.py</b>: <br />
<pre>from __future__ import print_function
"""
This is the code for the Perl version by Mark Jason Dominus:
sub hanoi {
my ($n, $start, $end, $extra) = @_;
if ($n == 1) {
print "Move disk #1 from $start to $end.\n"; # Step 1
} else {
hanoi($n-1, $start, $extra, $end); # Step 2
print "Move disk #$n from $start to $end.\n"; # Step 3
hanoi($n-1, $extra, $end, $start); # Step 4
}
}
"""
# This is my Python version ported from the Perl version above:
def hanoi(n, start, end, extra):
"""
Function hanoi(n, start, end, extra)
Solve Tower of Hanoi problem for a tower of n disks,
of which the largest is disk #n. Move the entire tower from
peg 'start' to peg 'end', using peg 'extra' as a work space.
"""
if n == 1:
print("Move disk #1 from {} to {}.\n".format(start, end))
else:
# Recursive call #1
hanoi(n - 1, start, extra, end)
print("Move disk #{} from {} to {}.\n".format(n, start, end))
# Recursive call #2
hanoi(n - 1, extra, end, start)
# Call to hanoi() with 3 disks, i.e. n = 3:
hanoi(3, 'A', 'C', 'B')
</pre>Here is the output on running it:<br />
<pre>$ python hanoi_01.py
Move disk #1 from A to C.
Move disk #2 from A to B.
Move disk #1 from C to B.
Move disk #3 from A to C.
Move disk #1 from B to A.
Move disk #2 from B to C.
Move disk #1 from A to C.
</pre>Here is the second version, <b>hanoi_02.py</b>: <br />
<pre>from __future__ import print_function
from msvcrt import getch
"""
Tower of Hanoi program
---
By Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
Twitter: https://mobile.twitter.com/vasudevram
Product store: https://gumroad.com/vasudevram
---
Translated to Python from the Perl version in the book Higher-Order Perl
by Mark Jason Dominus: https://hop.perl.plover.com/book/ , with some
minor enhancements related to interactivity.
"""
def hanoi(n, start, end, extra):
"""
Function hanoi(N, start, end, extra)
Solve Tower of Hanoi problem for a tower of N disks,
of which the largest is disk #N. Move the entire tower from
peg 'start' to peg 'end', using peg 'extra' as a work space.
"""
assert n > 0
if n == 1:
print("Move disk #1 from {} to {}.".format(start, end))
else:
hanoi(n - 1, start, extra, end)
print("Move disk #{} from {} to {}.".format(n, start, end))
hanoi(n - 1, extra, end, start)
for n in range(1, 5):
print("\nTower of Hanoi with n = {}:".format(n))
hanoi(n, 'A', 'C', 'B')
if n < 4:
print("\nPress q to quit, any other key for next run: ")
c = getch()
if c.lower() == 'q':
break
</pre>Here is the output on running it - I pressed q after 3 iterations:<br />
<pre>$ python hanoi_02.py
Tower of Hanoi with n = 1:
Move disk #1 from A to C.
Press q to quit, any other key for next run:
Tower of Hanoi with n = 2:
Move disk #1 from A to B.
Move disk #2 from A to C.
Move disk #1 from B to C.
Press q to quit, any other key for next run:
Tower of Hanoi with n = 3:
Move disk #1 from A to C.
Move disk #2 from A to B.
Move disk #1 from C to B.
Move disk #3 from A to C.
Move disk #1 from B to A.
Move disk #2 from B to C.
Move disk #1 from A to C.
Press q to quit, any other key for next run:
</pre>Note that <b>getch</b> does not echo the key that is pressed to the screen. If you want that, use <b>getche</b>, from the same module <b>msvcrt</b>.<br />
<br />
Viewing the output, I observed that for 1 disk, it takes 1 move, for 2 disks, it takes 3 moves, and for 3 disks, it takes 7 moves. From this, by informally applying <a href="https://en.wikipedia.org/wiki/Mathematical_induction">mathematical induction</a>, we can easily figure out that for n disks, it will take 2 ** n - 1 moves. The Wikipedia article about the Tower of Hanoi confirms this.<p/>That same Wikipedia article (linked above) also shows that the Tower of Hanoi has some interesting applications:<p/>Excerpts:<p/>[ The Tower of Hanoi is frequently used in psychological research on problem solving. There also exists a variant of this task called Tower of London for neuropsychological diagnosis and treatment of executive functions. ]<p/>[ Zhang and Norman[10] used several isomorphic (equivalent) representations of the game to study the impact of representational effect in task design. ]<p/>[ The Tower of Hanoi is also used as a Backup rotation scheme when performing computer data Backups where multiple tapes/media are involved. ]<p/>[ The Tower of Hanoi is popular for teaching recursive algorithms to beginning programming students. ]<p/>And this application is possibly the most interesting of the lot - ants solving the Tower of Hanoi problem :)<p/>[ In 2010, researchers published the results of an experiment that found that the <b>ant species Linepithema humile</b> were successfully able to <b>solve the 3-disk version</b> of the <b>Tower of Hanoi problem</b> through non-linear dynamics and pheromone signals. ]<p/>Also check out the section in that Wikipedia article with the title:<p/>"General shortest paths and the number 466/885"<p/>Not directly related, but similar to the above ratio, did you know that there is an easy-to-remember and better approximation to the <b><a href="https://en.wikipedia.org/wiki/Pi">number pi</a></b>, than the ratio <b>22/7</b> that many of us learned in school?<p/>Just take the <b>1st 3 odd numbers</b>, i.e. 1, 3, 5, repeat each of them once, and join all those 6 digits, to get <b>113355</b>, split that number in the middle, and divide the 2nd half by the 1st half, i.e <b>355/113</b>, which gives <b>3.1415929203539823008849557522124</b>. (See the section titled "Approximate value and digits" in the Wikipedia article about pi linked above, for this and other approximations for pi).<p/>Pressing the <b>pi</b> button in <b>Windows CALC.EXE</b> gives </b>3.1415926535897932384626433832795, and comparing that with the ratio 355/113 above, shows that the ratio is accurate to 6 decimal places. I've read somewhere that this ratio was used by mathematicians in ancient India.<p/>Here are some interesting excerpts from the Wikipedia article about pi:<p/>[ The number pi is a mathematical constant. Originally defined as the ratio of a circle's circumference to its diameter, it now has various equivalent definitions and appears in many formulas in all areas of mathematics and physics. It is approximately equal to 3.14159. It has been represented by the Greek letter "p" since the mid-18th century, though it is also sometimes spelled out as "pi". It is also called Archimedes' constant. ]<p/>[ Being an irrational number, pi cannot be expressed as a common fraction (equivalently, its decimal representation never ends and never settles into a permanently repeating pattern). Still, fractions such as 22/7 and other rational numbers are commonly used to approximate pi. The digits appear to be randomly distributed. In particular, the digit sequence of pi is conjectured to satisfy a specific kind of statistical randomness, but to date, no proof of this has been discovered. Also, pi is a transcendental number; that is, it is not the root of any polynomial having rational coefficients. ]<p/>[ Being an irrational number, pi cannot be expressed as a common fraction (equivalently, its decimal representation never ends and never settles into a permanently repeating pattern). Still, fractions such as 22/7 and other rational numbers are commonly used to approximate p. The digits appear to be randomly distributed. In particular, the digit sequence of pi is conjectured to satisfy a specific kind of statistical randomness, but to date, no proof of this has been discovered. Also, pi is a transcendental number; that is, it is not the root of any polynomial having rational coefficients. This transcendence of pi implies that it is impossible to solve the ancient challenge of squaring the circle with a compass and straightedge. ]<p/>[ Ancient civilizations required fairly accurate computed values to approximate pi for practical reasons, including the Egyptians and Babylonians. Around 250 BC the Greek mathematician Archimedes created an algorithm for calculating it. In the 5th century AD Chinese mathematics approximated pi to seven digits, while <a href="https://en.wikipedia.org/wiki/Indian_mathematics">Indian mathematics</a> made a five-digit approximation, both using geometrical techniques. The historically first exact formula for p, based on infinite series, was not available until a millennium later, when in the 14th century the Madhava–Leibniz series was discovered in Indian mathematics. ]<p/>(Speaking of <b>Indian mathematics</b>, check out this earlier post by me:<p/><a href="https://jugad2.blogspot.com/2010/06/bhaskaracharya-and-man-who-found-zero.html">Bhaskaracharya and the man who found zero</a>.)<p/>[ Because its most elementary definition relates to the circle, pi is found in many formulae in trigonometry and geometry, especially those concerning circles, ellipses, and spheres. In more modern mathematical analysis, the number is instead defined using the spectral properties of the real number system, as an eigenvalue or a period, without any reference to geometry.<p/>It appears therefore in areas of mathematics and the sciences having little to do with the geometry of circles, such as number theory and statistics, as well as in almost all areas of physics.<p/>The <b>ubiquity of pi</b> makes it one of the most widely known mathematical constants both inside and outside the scientific community. Several books devoted to pi have been published, and record-setting calculations of the digits of pi often result in news headlines. Attempts to memorize the value of pi with increasing precision have led to records of over 70,000 digits. ]<br />
<br />
- Enjoy.<br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><p/><hr/>I conduct online courses on <b>Python</b> programming, <b>Unix / Linux</b> commands and shell scripting and <b>SQL</b> programming and <b>database design</b>, with <b>course material</b> and <b>personal coaching</b> sessions.<p/><a href="https://jugad2.blogspot.com/p/training.html">The course details and testimonials are here.</a><p/><a href="http://vasudevram.github.io/contact.html">Contact me</a> for details of course content, terms and schedule.<p/>Try <a href="https://www.shareasale.com/r.cfm?u=849702&m=52946&b=593723">FreshBooks</a>: Create and send professional looking invoices in less than 30 seconds.<p/>Getting a new web site or blog, and want to help preserve the environment at the same time? Check out <a href="https://www.greengeeks.com/track/vasudevram">GreenGeeks.com</a> web hosting.<p/>Sell your digital products via <a href="https://getdpd.com/?afmc=90">DPD: Digital Publishing for Ebooks and Downloads</a>.<p/>Learning Linux? Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>.<p/>I wrote it at the request of two Windows system administrator friends who were given additional charge of some Unix systems. They later told me that it helped them to quickly start using vi to edit text files on Unix. Of course, vi/vim is one of the <b>most ubiquitous text editors around</b>, and works on most other common operating systems and on some uncommon ones too, so the knowledge of how to use it will carry over to those systems too.<p/>Check out <a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">WP Engine, powerful WordPress hosting</a>.<p/><a href="https://www.sendowl.com/?r=c7f16">Sell More Digital Products With SendOwl</a>.<p/><p/><a href="https://www.a2hosting.com/?aid=vasudevram">Get a fast web site with A2 Hosting</a>.<p/>Creating online products for sale? <a href="http://mbsy.co/convertkit/28519854">Check out ConvertKit</a>, email marketing for online creators.<p/><a href="http://sendmeto.teachable.com/ph6RQ">Teachable: feature-packed course creation platform</a>, with unlimited video, courses and students.<p/>Posts about: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a><p/><a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a><p/>Follow me on:<p/><ul><li><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">My blog jugad2</a></li>
<li><a href="https://gumroad.com/vasudevram/follow/">Gumroad</a></li>
<li><a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></li>
<li><a href="https://mobile.twitter.com/vasudevram">Twitter</a></li>
</ul><p/><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0tag:blogger.com,1999:blog-6692866151143183230.post-18163408286444655932018-12-02T00:04:00.000+05:302018-12-02T00:04:20.507+05:30Bjarne Stroustrup's FAQBy <a href="https://jugad2.blogspot.in/p/about-vasudev-ram.html">Vasudev Ram</a><br />
<a href=""></a><br />
<br />
<a href="http://www.stroustrup.com/bs_faq.html#decline">Bjarne Stroustrup's FAQ</a><br />
<br />
Educational and entertaining.<br />
<br />
<hr/>- <a href="https://vasudevram.github.io/">Vasudev Ram - Online Python training and consulting</a><p/>Hit the ground running with my <a href="https://gumroad.com/l/vi_quick/">vi quickstart tutorial</a>, vetted by two Windows system administrator friends.</p>Jump to posts: <a href="http://jugad2.blogspot.com/search/label/python">Python</a> * <a href="http://jugad2.blogspot.com/search/label/DLang">DLang</a> * <a href="http://jugad2.blogspot.com/search/label/xtopdf">xtopdf</a></p><a href="https://jugad2.blogspot.com/p/training.html">Interested in a Python, SQL or Linux course?</a></p><a href="https://www.shareasale.com/r.cfm?u=849702&m=41388&b=394686">Get WP Engine, powerful managed WordPress hosting.</a></p><a href="https://feedburner.google.com/fb/a/mailverify?uri=Jugad2-VasudevRamOnSoftwareInnovation&loc=en_US">Subscribe to my blog (jugad2.blogspot.com) by email</a></p><a href="https://code.activestate.com/recipes/users/4173351/">My ActiveState Code recipes</a></p><hr/>Follow me on:</p>* <a href="https://gumroad.com/vasudevram/follow">Gumroad</a> * <a href="https://www.linkedin.com/in/vasudevram?trk=nav_responsive_tab_profile">LinkedIn</a></p> * <a href="https://mobile.twitter.com/vasudevram">Twitter</a></p>Do you create online products? Get Convertkit:</p><a href="http://mbsy.co/convertkit/28519854">Email marketing for digital product creators</a></p><hr/><div class="blogger-post-footer"><a href="http://vasudevram.github.io">Vasudev Ram</a>
<br/></div>Vasudev Ramhttp://www.blogger.com/profile/13568740634188042591noreply@blogger.com0