Monday, January 21, 2019

Factorial function using Python's reduce function


- By Vasudev Ram - Online Python training / SQL training / Linux training



[This is a beginner-level Python post. I label such posts as "python-beginners" in the Blogger labels at the bottom of the post. You can get a sub-feed of all such posts for any label using the label (case-sensitive) in a URL of the form:

https://jugad2.blogspot.com/search/label/label_name where label_name is to be replaced by an actual label,

such as in:

jugad2.blogspot.com/search/label/python-beginners

and

jugad2.blogspot.com/search/label/python
]

Hi, readers,

The factorial function (Wikipedia article) is often implemented in programming languages as either an iterative or a recursive function. Both are fairly simple to implement.

For the iterative version, to find the value of n factorial (written n! 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.

For the recursive version, you define the base case as 0! = 1, and then for all higher values of n factorial, you compute them recursively as the product of n with (n - 1) factorial.

[ Wikipedia article about Iteration. ]

[ Wikipedia article about Recursion in computer_science. ]

Here is another way of doing it, which is also iterative, but uses no explicit loop; instead it uses Python's built-in reduce() function, which is part of the functional programming paradigm or style:
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
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 reduce with operator.mul (which is a functional version of the multiplication operator). In more detail: the function call range(1, 11) 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.

The Python docstring for reduce:
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.
Did you know that there are many different kinds of factorials? To learn more, check out this post:

Permutation facts

- Enjoy.


- Vasudev Ram - Online Python training and consulting

I conduct online courses on Python programming, Unix / Linux commands and shell scripting and SQL programming and database design, with course material and personal coaching sessions.

The course details and testimonials are here.

Contact me for details of course content, terms and schedule.

Try FreshBooks: Create and send professional looking invoices in less than 30 seconds.

Getting a new web site or blog, and want to help preserve the environment at the same time? Check out GreenGeeks.com web hosting.

Learning Linux? Hit the ground running with my vi quickstart tutorial. 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 most ubiquitous text editors around, 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.

Check out WP Engine, powerful WordPress hosting.

Sell More Digital Products With SendOwl.

Creating online products for sale? Check out ConvertKit, email marketing for online creators.

Teachable: feature-packed course creation platform, with unlimited video, courses and students.

Posts about: Python * DLang * xtopdf

My ActiveState Code recipes

Follow me on:


Friday, January 18, 2019

Announcing PIaaS - Python Interviewing as a Service



Hello, readers,

Announcing Python Interviewing as a Service:

I'm now officially offering PIaaS - Python Interviewing as a Service. 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 consulting (software design and development, code review, technology evaluation and recommendation) and software training.

I can help your organization interview and hire Python developer candidates, offloading (some of) that work from your core technical and HR / recruitment staff.

I can also interview on related areas like SQL and RDBMS, and Unix and Linux commands and shell scripting.

I have long-term experience in all the above areas.

To hire me for PIaaS or to learn more about it, contact me via the Gmail address on my site's contact page.

- Vasudev Ram

My Codementor profile: Vasudev Ram on Codementor


Tuesday, January 8, 2019

The Teachable Full-time Creator Masterclass 2019


- By Vasudev Ram - Online Python training / SQL training / Linux training

Hi, readers,

As I said a few days ago in this post:

Great Teachable offer coming in a few days ...

, here are the details for the Teachable Full-time Creator Masterclass 2019.

It will go on from 14th to 21st January 2019.

What’s the Full-time Creator masterclass?

The Full-time Creator is a free, 4-part masterclass that Teachable is hosting over the course of a week - consisting of 4 jam-packed video trainings that will be dripped out over 7 days. The ideal audience for this event includes creators (think: bloggers, coaches, experts, authors, consultants, influencers, hobbyists, offline trainers, etc.) who want to create a profitable online course, using the knowledge they already have. After the week-long masterclass, they'll be offered an opportunity to buy Teachable's service — and when they do they'll receive $4K+ in valuable bonuses for free.

After the week-long masterclass, you will be invited to sign up for Teachable.

Sign up for the Teachable Full-time Creator Masterclass 2019 here.

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.

See you there.

- Vasudev.

- Vasudev Ram - Online Python training and consulting

I conduct online courses on Python programming, Unix / Linux commands and shell scripting and SQL programming and database design, with course material and personal coaching sessions.

The course details and testimonials are here.

Contact me for details of course content, terms and schedule.

Try FreshBooks: Create and send professional looking invoices in less than 30 seconds.

Getting a new web site or blog, and want to help preserve the environment at the same time? Check out GreenGeeks.com web hosting.

Sell your digital products via DPD: Digital Publishing for Ebooks and Downloads.

Learning Linux? Hit the ground running with my vi quickstart tutorial. 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 most ubiquitous text editors around, 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.

Creating online products for sale? Check out ConvertKit, email marketing for online creators.

Check out WP Engine, powerful WordPress hosting.

Sell More Digital Products With SendOwl.

Get a fast web site with A2 Hosting.

Posts about: Python * DLang * xtopdf

My ActiveState Code recipes

Follow me on:


Sunday, January 6, 2019

Thursday, January 3, 2019

Multiple item search in an unsorted list in Python


- By Vasudev Ram - Online Python training / SQL training / Linux training



Hi, readers,

I was reviewing simple algorithms with a view to using some as examples or exercises in my Python programming course. While doing so, I thought of enhancing simple linear search for one item in a list, to make it search for multiple items.

Here are a couple of program versions I wrote for that task. They use straightforward logic. There are just a few additional points:

- In both programs, I use a generator to yield the values found (the index and the item).
- In the first program, I print out the index and item for each item found.
- In the second program, I mark where the items are found with text "arrows".

This is the first program, mult_item_search_unsorted_list.py:
# 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()
Output of a run:
$ 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
And this is the second program, mult_item_search_unsorted_list_w_arrows.py:
# 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()
Output of a run:
$ 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]
------------^
---------------^
------------------------^
---------------------------------^

In a recent post, Dynamic function creation at run time with Python's eval built-in, I had said:

"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."

No reader commented with a solution. So here is a hint to figure it out:

What is the expansion of (a + b) ** 2 (a plus b the whole squared) in algebra?

Heh.

The drawing of the magnifying glass at the top of the post is by:

Yours truly.

( The same one that I used in this post:
Command line D utility - find files matching a pattern under a directory )

I'll leave you with another question: What, if any, could be the advantage of using Python generators in programs like these?
Notice that I said "programs like these", not "these programs".

Enjoy.

- Vasudev Ram - Online Python training and consulting

I conduct online courses on Python programming, Unix / Linux commands and shell scripting and SQL programming and database design, with course material and personal coaching sessions.

The course details and testimonials are here.

Contact me for details of course content, terms and schedule.

Try FreshBooks: Create and send professional looking invoices in less than 30 seconds.

Getting a new web site or blog, and want to help preserve the environment at the same time? Check out GreenGeeks.com web hosting.

Sell your digital products via DPD: Digital Publishing for Ebooks and Downloads.

Learning Linux? Hit the ground running with my vi quickstart tutorial. 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 most ubiquitous text editors around, 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.

Check out WP Engine, powerful WordPress hosting.

Get a fast web site with A2 Hosting.

Creating online products for sale? Check out ConvertKit, email marketing for online creators.

Teachable: feature-packed course creation platform, with unlimited video, courses and students.

Posts about: Python * DLang * xtopdf

My ActiveState Code recipes

Follow me on: