Training, Open Source Programming Languages

This is page

Our email: • Phone: 01144 1225 708225

For 2021 - online Python 3 training - see ((here)).

Our plans were to retire in summer 2020 and see the world, but Coronavirus has lead us into a lot of lockdown programming in Python 3 and PHP 7.
We can now offer tailored online training - small groups, real tutors - works really well for groups of 4 to 14 delegates. Anywhere in the world; course language English.

Please ask about private 'maintenance' training for Python 2, Tcl, Perl, PHP, Lua, etc.
Recursion and special collections in Python
Applying OO design techniques and best practise example from a Well House Consultants training course
More on Applying OO design techniques and best practise [link]

This example is described in the following article(s):
   • A good example of recursion - a real use in Python - [link]

This example references the following resources:

Source code: Module: Y116
# Recursion and special collections in Python

""" This is an example written to correlate family tree data (at ) and
produce an ancestor tree for any individual who's data is present. This is posted at an early stage of
development (a "spike solution") as it illustrated a good use of recursion in Python, and also the use of
a man-dimentional collection - both theings which will often feature in your larger progras, but which are
rarely found in practical short demonstration pieces """

import re
import sys

class person(object):

        field_defs = \

        # In order to avoid the need for lots of accessors, I've chosen to keep all of my
        # attributes in a dict and refer to them by field name

        def __init__(this,record):
       = {}
                stuff = record.split('\t')
                for k in range(len(person.field_defs)):
                        fname = person.field_defs[k]
              [fname] = stuff[k].strip()

        # Our data has "unknown date in year" marked as 1st January. Yuk - what if someone
        # really arrived or left on 1st January - but this is the data I have. These methods
        # clean up the data for presentation

        def getdeathYear(this):
                val = this.get("deathYear")
                val = re.sub("^1/1/","",val)
                return val
        def getbirthYear(this):
                val = this.get("birthYear")
                val = re.sub("^1/1/","",val)
                return val

        def get(this,what):

        # How a person rcord is to be displayed - for user purposes (__str__) and for
        # debug / programmer purposes (__repr__).

        def __str__(this):
                return (this.get("personID") + " " + this.get("name") +
                        " (" + this.getbirthYear() + " to " + this.getdeathYear() + " )")
        def __repr__(this):
                return (this.get("personID") + " " + this.get("name"))

        # Getting parent tree
        # recursive routine - note internal call of function back to itself

        def getParentTree(this,pool):
                p = ["*","*",this]
                for pNumber in range(2):
                        each = ("fatherID","motherID")[pNumber]
                        if[each] == "":
                                p[pNumber] = None
                                p[pNumber] = person.locate([each],pool).getParentTree(pool)
                return p

        # For effiency, this routine should set up a cached dict keyed on personID
        # This first spike solution is horrible inefficient!

        def locate(finding,pool):
                found = None
                if finding:
                        for p in pool:
                                if["personID"] == finding:
                                        found = p
                return found

class ancestorTree(object):

""" Object to handle collection of people (ancestor tree) """

        def __init__(this,base,pool):
                this.tree = base.getParentTree(pool)

        def __str__(this):
                result = ancestorTree.parentPrint(this.tree,0)
                result = re.sub("\n+","\n",result)
                return result

        # Note that "parentPrint" is recursive - generating insets at each level of recursion for pretty display

        def parentPrint(triplet,generation):
                if triplet:
                        result = str(generation) + ": " + ("\t" * generation) +str(triplet[2]) + "\n"
                        if triplet[0]:
                                result += ancestorTree.parentPrint(triplet[0],generation+1) + "\n"
                                result += str(generation+1) + ": " + ("\t" * (generation+1)) + "[away] " + triplet[2].get("fatherOverride") + "\n"
                        if triplet[1]:
                                result += ancestorTree.parentPrint(triplet[1],generation+1) + "\n"
                                result += str(generation+1) + ": " + ("\t" * (generation+1)) + "[away] " + triplet[2].get("motherOverride") + "\n"
                        result = (str(generation) + ": " + ("\t" * generation) + '-' + "\n")
                return result

        def getFullName(this):
                return this.tree[2].get("name")

# ----------------- And here's the program that actually uses our family tree / ancestor logic

# Read in all the people into a pool. No particular order, so just buffer them

pool = []
for p in open("family.tsv"):

# Handle command line paramaters

names = sys.argv[1:]
if not names:
        print "usage " + sys.argv[0] + " name [name [name]]"
        print " " + sys.argv[0] + " -a"
        print " " + sys.argv[0] + " -s"

# Allow for "-a" option for "all"
if len(names) == 1 and names[0] == "-a":
                names = []

# Allow for "-s" option for "summary"
summary = 0
if len(names) == 1 and names[0] == "-s":
                names = []
                summary = 1

# Either print a summary (list of all people for whom we have data) or ancestor tree(s) for all or some people

if summary:
        for p in pool:
                print p
        for p in pool:
                ptree = ancestorTree(p,pool)
                called = ptree.getFullName()
                for name in names:
                        if not re.findall(name,called,re.I): break
                        print ptree
Learn about this subject
This module and example are covered on the following public courses:
 * Learning to program in Python
 * Python Programming
 * Intermediate Python
Also available on on site courses for larger groups

Books covering this topic
Yes. We have over 700 books in our library. Books covering Python are listed here and when you've selected a relevant book we'll link you on to Amazon to order.

Other Examples
This example comes from our "Applying OO design techniques and best practise" training module. You'll find a description of the topic and some other closely related examples on the "Applying OO design techniques and best practise" module index page.

Full description of the source code
You can learn more about this example on the training courses listed on this page, on which you'll be given a full set of training notes.

Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License.

Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre.
The Horse's mouth provides a daily tip or thought.
• Further resources are available via the resources centre.
• All of these resources can be searched through through our search engine
• And there's a global index here.

Web site author
This web site is written and maintained by Well House Consultants.

Purpose of this website
This is a sample program, class demonstration or answer from a training course. It's main purpose is to provide an after-course service to customers who have attended our public private or on site courses, but the examples are made generally available under conditions described below.

Conditions of use
Past attendees on our training courses are welcome to use individual examples in the course of their programming, but must check the examples they use to ensure that they are suitable for their job. Remember that some of our examples show you how not to do things - check in your notes. Well House Consultants take no responsibility for the suitability of these example programs to customer's needs.

This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details.

Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request.

© WELL HOUSE CONSULTANTS LTD., 2022: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: • WEB: • SKYPE: wellho

PAGE: • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb