| ||||
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]
Source code: tree.py Module: Y116
# Recursion and special collections in Python
""" This is an example written to correlate family tree data (at http://www.wellho.net/data/family.tsv ) 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 = \ ("birthYear","deathYear","fatherID","gender","motherID","name","personID", "sp1ID","sp2ID","sp3ID","sp4ID", "fatherBirthYear","fatherOverride","fatherDeathYear", "motherBirthYear","motherOverride","motherDeathYear", "sp1name","sp2name","sp3name","sp4name") # 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): this.data = {} stuff = record.split('\t') for k in range(len(person.field_defs)): fname = person.field_defs[k] this.data[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): return this.data[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 this.data[each] == "": p[pNumber] = None else: p[pNumber] = person.locate(this.data[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! @staticmethod def locate(finding,pool): found = None if finding: for p in pool: if p.data["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 @staticmethod 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" else: result += str(generation+1) + ": " + ("\t" * (generation+1)) + "[away] " + triplet[2].get("fatherOverride") + "\n" if triplet[1]: result += ancestorTree.parentPrint(triplet[1],generation+1) + "\n" else: result += str(generation+1) + ": " + ("\t" * (generation+1)) + "[away] " + triplet[2].get("motherOverride") + "\n" else: 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"): pool.append(person(p)) # 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" exit() # 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 else: for p in pool: ptree = ancestorTree(p,pool) called = ptree.getFullName() for name in names: if not re.findall(name,called,re.I): break else: 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
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. | ||||
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho PAGE: http://www.wellho.net/resources/ex.php • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb |