Chapter 11: Structuring Data

Program 11.1, page no. 403

In [1]:
class Horse:
    age = 0
    height = 0
    name = ""
    father = ""
    mother = ""

my_horse = Horse()
print "Enter the name of the horse: ",
my_horse.name = raw_input()
 
print "How old is %s? " % my_horse.name,
my_horse.age = int(raw_input())
 
print "How high is %s ( in hands )? " %my_horse.name,
my_horse.height = int(raw_input())
 
print "Who is %s's father? " %my_horse.name,
my_horse.father = raw_input()
 
print "Who is %s's mother? " %my_horse.name,
my_horse.mother = raw_input()
 
print "%s is %d years old, %d hands high, " %(my_horse.name, my_horse.age, my_horse.height),
print "and has %s and %s as parents. " %(my_horse.father, my_horse.mother)
Enter the name of the horse: Neddy
 How old is Neddy? 12
 How high is Neddy ( in hands )? 14
 Who is Neddy's father? Bertie
 Who is Neddy's mother? Nellie
 Neddy is 12 years old, 14 hands high,  and has Bertie and Nellie as parents. 

Program 11.2, page no. 436

In [4]:
class Horse:
    age = 0
    height = 0
    name = ""
    father = ""
    mother = ""
 
my_horses = []
test = ''
hcount = 0

while(True):
    print "Do you want to enter details of a horse (Y or N)? "
    choice = raw_input()
    if(choice.lower() == 'n'):
        break
    my_horse = Horse()
    print "Enter the name of the horse: ",
    my_horse.name = raw_input()
    print "How old is %s? " % my_horse.name,
    my_horse.age = int(raw_input())
    print "How high is %s ( in hands )? " %my_horse.name,
    my_horse.height = int(raw_input())
    print "Who is %s's father? " %my_horse.name,
    my_horse.father = raw_input()
    print "Who is %s's mother? " %my_horse.name,
    my_horse.mother = raw_input()
    my_horses.append(my_horse)
    hcount += 1

for i in range(hcount):
    print "%s is %d years old, %d hands high, " %(my_horses[i].name, my_horses[i].age, my_horses[i].height),
    print "and has %s and %s as parents. " %(my_horses[i].father, my_horses[i].mother)
Do you want to enter details of a horse (Y or N)? 
y
Enter the name of the horse: Neddy
 How old is Neddy? 12
 How high is Neddy ( in hands )? 14
 Who is Neddy's father? Bertie
 Who is Neddy's mother? Nellie
 Do you want to enter details of a horse (Y or N)? 
y
Enter the name of the horse: Stallion
 How old is Stallion? 10
 How high is Stallion ( in hands )? 15
 Who is Stallion's father? Father Stallion
 Who is Stallion's mother? Mother Stallion
 Do you want to enter details of a horse (Y or N)? 
n
Neddy is 12 years old, 14 hands high,  and has Bertie and Nellie as parents. 
Stallion is 10 years old, 15 hands high,  and has Father Stallion and Mother Stallion as parents. 

Program 11.3, page no. 440

In [5]:
class Horse:
    age = 0
    height = 0
    name = ""
    father = ""
    mother = ""
 
my_horses = []
test = ''
hcount = 0

while(True):
    print "Do you want to enter details of a horse (Y or N)? "
    choice = raw_input()
    if(choice.lower() == 'n'):
        break
    my_horse = Horse()
    print "Enter the name of the horse: ",
    my_horse.name = raw_input()
    print "How old is %s? " % my_horse.name,
    my_horse.age = int(raw_input())
    print "How high is %s ( in hands )? " %my_horse.name,
    my_horse.height = int(raw_input())
    print "Who is %s's father? " %my_horse.name,
    my_horse.father = raw_input()
    print "Who is %s's mother? " %my_horse.name,
    my_horse.mother = raw_input()
    my_horses.append(my_horse)
    hcount += 1

ptr_my_horses = my_horses

for i in range(hcount):
    print "%s is %d years old, %d hands high, " %(ptr_my_horses[i].name, ptr_my_horses[i].age, ptr_my_horses[i].height),
    print "and has %s and %s as parents. " %(ptr_my_horses[i].father, ptr_my_horses[i].mother)
Do you want to enter details of a horse (Y or N)? 
y
Enter the name of the horse: Neddy
 How old is Neddy? 12
 How high is Neddy ( in hands )? 14
 Who is Neddy's father? Bertie
 Who is Neddy's mother? Nellie
 Do you want to enter details of a horse (Y or N)? 
n
Neddy is 12 years old, 14 hands high,  and has Bertie and Nellie as parents. 

Program 11.4, page no. 445

In [6]:
class Horse:
    age = 0
    height = 0
    name = ""
    father = ""
    mother = ""
    next = None
    prev = None

first = None
previous = None

while(True):
    print "Do you want to enter details of a horse (Y or N)? ",
    choice = raw_input()
    if(choice.lower() == 'n'):
        break
    current = Horse()
    if(first == None):
        first = current
    if(previous != None):
        previous.next = current
    print "Enter the name of the horse: ",
    current.name = raw_input()
    print "How old is %s? " %current.name,
    current.age = int(raw_input())
    print "How high is %s ( in hands )? " %(current.name),
    current.height = int(raw_input())
    print "Who is %s's father? " %current.name,
    current.father = raw_input()
    print "Who is %s's mother? " %current.name,
    current.mother = raw_input()
    current.next = None
    previous = current

current = first
while (current != None):
    print "%s is %d years old, %d hands high," %(current.name, current.age, current.height),
    print "and has %s and %s as parents." %(current.father, current.mother)
    previous = current
    current = current.next
    previous = None
    first = None
Do you want to enter details of a horse (Y or N)? y
 Enter the name of the horse: Neddy
 How old is Neddy? 12
 How high is Neddy ( in hands )? 14
 Who is Neddy's father? Brtie
 Who is Neddy's mother? Nellie
 Do you want to enter details of a horse (Y or N)? n
 Neddy is 12 years old, 14 hands high, and has Brtie and Nellie as parents.

Program 11.5, page no. 450

In [20]:
first = None
current = None
last = None

class Horse:
    age = 0
    height = 0
    name = ""
    father = ""
    mother = ""
    next = None
    prev = None


while(True):
    print "Do you want to enter details of a horse (Y or N)? ",
    choice = raw_input()
    if(choice.lower() == 'n'):
        break 

    current = Horse()
    if(first == None):
        first = current
        last = current
    else:
        last.next = current
        current.previous = last
        last = current
    print "Enter the name of the horse: ",
    current.name = raw_input()
    print "How old is %s? " %current.name,
    current.age = int(raw_input())
    print "How high is %s ( in hands )? " %(current.name),
    current.height = int(raw_input())
    print "Who is %s's father? " %current.name,
    current.father = raw_input()
    print "Who is %s's mother? " %current.name,
    current.mother = raw_input()

current = first
while(current):
    print "%s is %d years old, %d hands h1igh," %(current.name, current.age, current.height),
    print "and has %s and %s as parents." %(current.father, current.mother)
    current = current.next
Do you want to enter details of a horse (Y or N)? y
 Enter the name of the horse: neddy
 How old is neddy? 13
 How high is neddy ( in hands )? 14
 Who is neddy's father? bertie
 Who is neddy's mother? nellie
 Do you want to enter details of a horse (Y or N)? y
 Enter the name of the horse: stallion
 How old is stallion? 14
 How high is stallion ( in hands )? 18
 Who is stallion's father? father stallio
 Who is stallion's mother? mother stallion
 Do you want to enter details of a horse (Y or N)? n
 neddy is 13 years old, 14 hands h1igh, and has bertie and nellie as parents.
stallion is 14 years old, 18 hands h1igh, and has father stallio and mother stallion as parents.

Program 11.6, page no. 456

In [22]:
class Date:
    day = 0
    month = 0
    year = 0
 
class Family:
    dob = Date()
    name = ""
    father = ""
    mother = ""
    next = None
    previous = None
    
def get_person():
    temp = Family()
    print "Enter the name of the person: ",
    temp.name = raw_input()
    print "Enter %s's date of birth (day month year) " %temp.name,
    temp.dob.day = int(raw_input("Day: "))
    temp.dob.month = int(raw_input("Month: "))
    temp.dob.year = int(raw_input("Year: "))
    print "Who is %s's father? " %temp.name
    temp.father = raw_input()
    print "Who is %s's mother? " %temp.name
    temp.mother = raw_input()
    temp.next = None
    temp.previous = None
    return temp
 
def show_people(pfirst):
    current = pfirst
    while(current):
        print "%s was born %d/%d/%d and has %s and %s as parents. " %(current.name, current.dob.day, current.dob.month, current.dob.year, current.father, current.mother)
        current = current.next

first = None
current = None
last = None
 
while(True):
    print "Do you want to enter details of a person (Y or N)? ",
    choice = raw_input()
    if(choice.lower() == 'n'):
        break
    current = get_person()
    if(first == None):
        first = current
        current.previous = None
        last = current
    else:
        last.next = current
        current.previous = last
    last = current
show_people(first)
first = None
last = None
 Do you want to enter details of a person (Y or N)? y
 Enter the name of the person: Ricky
 Enter Ricky's date of birth (day month year) Day: 5
Month: 6
Year: 1970
 Who is Ricky's father? 
Michael
Who is Ricky's mother? 
Rachel
Do you want to enter details of a person (Y or N)? y
 Enter the name of the person: Mitchel
 Enter Mitchel's date of birth (day month year) Day: 5
Month: 9
Year: 1967
 Who is Mitchel's father? 
Martin
Who is Mitchel's mother? 
Hingies
Do you want to enter details of a person (Y or N)? n
 Ricky was born 5/9/1967 and has Michael and Rachel as parents. 
Mitchel was born 5/9/1967 and has Martin and Hingies as parents. 

Program 11.7, page no. 466

In [1]:
class Node:
    item = 0.0
    count = 0
    pLeft = None
    pRight = None
 
def create_node(value):
    pNode = Node()
    pNode.item = value
    pNode.count = 1
    return pNode

def add_node(value, pNode):
    if(pNode is None):
        return create_node(value)
    if(value == pNode.item):
        pNode.count += 1
        return pNode
    if(value < pNode.item):
        if(pNode.pLeft is None):
            pNode.pLeft = create_node(value);
            return pNode.pLeft
        else:
            return add_node(value, pNode.pLeft)
    else:
        if(pNode.pRight is None):
            pNode. pRight = create_node(value)
            return pNode.pRight
        else:
            return add_node(value, pNode.pRight)


def list_nodes(pNode):
    if(pNode.pLeft):
        list_nodes(pNode.pLeft)
    print "%10d x %10ld" %(pNode.count, pNode.item)
    if(pNode.pRight):
        list_nodes(pNode.pRight)


pRoot = None
answer = 'n'
while(True):
    print "Enter the node value: ",
    newvalue = float(raw_input())
    if(pRoot is None):
        pRoot = create_node(newvalue)
    else:
        add_node(newvalue, pRoot)
    print "Do you want to enter another (y or n)? ",
    answer = raw_input()
    if answer == "n":
        break
print "The values in ascending sequence are: "
list_nodes(pRoot)
Enter the node value: 56
 Do you want to enter another (y or n)? y
 Enter the node value: 33
 Do you want to enter another (y or n)? y
 Enter the node value: 77
 Do you want to enter another (y or n)? y
 Enter the node value: -10
 Do you want to enter another (y or n)? y
 Enter the node value: 200
 Do you want to enter another (y or n)? y
 Enter the node value: -10
 Do you want to enter another (y or n)? y
 Enter the node value: -5
 Do you want to enter another (y or n)? n
 The values in ascending sequence are: 
         2 x        -10
         1 x         -5
         1 x         33
         1 x         56
         1 x         77
         1 x        200

Program 11.8, page no. 470

In [3]:
def print_date(date):
    if date.format == 0:
        print "The date is %d/%d/%d." %(date.date.nDate.day, date.date.nDate.month, date.date.nDate.year)
    elif date.format == 1:
        print "The date is %s. " %date.date.date_str
    elif date.format == 2:
        print "The date is %s %s %d. " %(date.date.day_date.day, date.date.day_date.date, date.date.day_date.year)
    else:
        print "Invalid date format."

class Date_Format:
    numeric = 0
    text = 1
    mixed = 2

class MixedDate:
    def __init__(self, d="", dt="", yr=0):
        self.day = d
        self.date = dt
        self.year = yr

class NumericDate:
    def __init__(self, d=0, mnt=0, yr=0):
        self.day = d
        self.month = mnt
        self.year = yr

class UDate:
    date_str = ""
    day_date = MixedDate()
    nDate = NumericDate()

class Date:
    format = Date_Format()
    date = UDate()

form = Date_Format()
yesterday = NumericDate(11, 11, 2012)
today = MixedDate("Monday", "12th November", 2012)
tomorrow = UDate()
tomorrow.date_str = "Tues 13th Nov 2012"

udate = tomorrow
the_date = Date()
the_date.date = udate
the_date.format = form.text
print_date(the_date)

the_date.date.nDate = yesterday
the_date.format = form.numeric
print_date(the_date)
 
the_date.date.day_date = today
the_date.format = form.mixed
print_date(the_date)
The date is Tues 13th Nov 2012. 
The date is 11/11/2012.
The date is Monday 12th November 2012. 

Program 11.9, page no. 482

In [2]:
import numpy
import sys


PAGE_HEIGHT = 41
PAGE_WIDTH = 75
 
class Bar:
    value = 0
    pNext = None
 
def create_bar_list():
    pFirst = None
    pBar = None
    pCurrent = None
    pBar = new_bar()
    while(pBar != None):
        if(pCurrent):
            pCurrent.pNext = pBar
            pCurrent = pBar
        else:
            pFirst = pCurrent = pBar
            #pCurrent = pBar
        pBar = new_bar()
    return pFirst
    
def new_bar():
    print "Enter the value of the Bar, or Enter quit to end: ",
    value = raw_input()
    if(value == "quit"):
        return None
    pBar = Bar()
    if(pBar is None):
        print "Oops! Couldn't allocate memory for a bar."
        sys.exit()
    pBar.value = float(value)
    pBar.pNext = None
    return pBar

def bar_chart(pFirst, page_width, page_height, title):
    pLast = pFirst;
    max = pFirst.value
    min = pFirst.value
    vert_step = 0.0
    bar_count = 1
    bar_width = 0
    space = 2
    column = None
    blank = None
    position = 0.0
    axis = False
    while(pLast.pNext):
        bar_count += 1
        max = pLast.value if (max < pLast.value) else max
        min = pLast.value if (min > pLast.value) else min
        pLast = pLast.pNext
    if(max < 0.0):
        max = 0.0
    if(min > 0.0):
        min = 0.0
    vert_step = (max - min)/page_height
    bar_width = page_width/bar_count - space
    if(bar_width < 1):
        print "Page width too narrow. "
        sys.exit()
    column = chart_string(space, bar_width, '#')
    if(not (column)):
        print "Failed to allocate memory in bar_chart() - terminating program."
        sys.exit()
    blank = chart_string(space, bar_width, ' ')
    if(not (blank)):
        print "Failed to allocate memory in bar_chart() - terminating program."
        sys.exit(1)
    print "\n^ %s " %title
    position = max
    for i in range(page_height):
        if(position <= 0.0 and not(axis)):
            draw_x_axis(bar_count*(bar_width + space))
            axis = True
        print "|",
        pLast = pFirst
        for bars in range(1, bar_count+1):
            print "%s" %(column if((position <= pLast.value and position > 0.0) or (position >= pLast.value and position <= 0.0)) else blank),
            pLast = pLast.pNext
        print ""
        position -= vert_step
    if(not axis):
        draw_x_axis(bar_count*(bar_width + space))
    else:
        print "v\n",


def chart_string(space, bar_width, ch):
    mystr = []
    for i in range(space+bar_width):
        mystr.append("")
    for i in range(space):
        mystr[i] =' '
    for j in range(space,space+bar_width):
        mystr[j] = ch
    return ''.join(mystr)

def draw_x_axis(length):
    print "+",
    for x in range(length):
        print "-",
    print ">"

pFirst = None
print "Enter the chart title: ",
title = raw_input()
pFirst = create_bar_list()
p = pFirst
while (p):
    print p.value
    p = p.pNext
bar_chart(pFirst, PAGE_WIDTH, PAGE_HEIGHT, title)
Enter the chart title: Average Temperatures
 Enter the value of the Bar, or Enter quit to end: -12
 Enter the value of the Bar, or Enter quit to end: -15
 Enter the value of the Bar, or Enter quit to end: 2
 Enter the value of the Bar, or Enter quit to end: 5
 Enter the value of the Bar, or Enter quit to end: 13
 Enter the value of the Bar, or Enter quit to end: 20
 Enter the value of the Bar, or Enter quit to end: 26
 Enter the value of the Bar, or Enter quit to end: 32
 Enter the value of the Bar, or Enter quit to end: 23
 Enter the value of the Bar, or Enter quit to end: 17
 Enter the value of the Bar, or Enter quit to end: -1
 Enter the value of the Bar, or Enter quit to end: -4
 Enter the value of the Bar, or Enter quit to end: quit
 -12.0
-15.0
2.0
5.0
13.0
20.0
26.0
32.0
23.0
17.0
-1.0
-4.0

^ Average Temperatures 
|                                                    ####                             
|                                                    ####                             
|                                                    ####                             
|                                                    ####                             
|                                                    ####                             
|                                                    ####                             
|                                             ####   ####                             
|                                             ####   ####                             
|                                             ####   ####   ####                      
|                                             ####   ####   ####                      
|                                             ####   ####   ####                      
|                                      ####   ####   ####   ####                      
|                                      ####   ####   ####   ####                      
|                                      ####   ####   ####   ####                      
|                                      ####   ####   ####   ####   ####               
|                                      ####   ####   ####   ####   ####               
|                                      ####   ####   ####   ####   ####               
|                               ####   ####   ####   ####   ####   ####               
|                               ####   ####   ####   ####   ####   ####               
|                               ####   ####   ####   ####   ####   ####               
|                               ####   ####   ####   ####   ####   ####               
|                               ####   ####   ####   ####   ####   ####               
|                               ####   ####   ####   ####   ####   ####               
|                               ####   ####   ####   ####   ####   ####               
|                        ####   ####   ####   ####   ####   ####   ####               
|                        ####   ####   ####   ####   ####   ####   ####               
|                        ####   ####   ####   ####   ####   ####   ####               
|                 ####   ####   ####   ####   ####   ####   ####   ####               
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >
|   ####   ####                                                           ####   #### 
|   ####   ####                                                                  #### 
|   ####   ####                                                                  #### 
|   ####   ####                                                                  #### 
|   ####   ####                                                                       
|   ####   ####                                                                       
|   ####   ####                                                                       
|   ####   ####                                                                       
|   ####   ####                                                                       
|   ####   ####                                                                       
|   ####   ####                                                                       
|          ####                                                                       
|          ####                                                                       
v