Chapter 9: Working with structures

Program 9.1, Page number: 167

In [1]:
def main():

        #Class Declaration
        class date:
                'python classes are equivalent to C structures'
                def __init__(self):                     #Class Constructor
                        #Set default values
                        self.month=0
                        self.day=0
                        self.year=0


        #Creating instance
        today=date()     
 
        #Modifying values
        today.month=9       
        today.day=25
        today.year=2004

        #Result
        print("Today's date is {0}/{1}/{2}".format(today.month,today.day,today.year%100));


if __name__=='__main__':
        main()
Today's date is 9/25/4

Program 9.2, Page number: 169

In [2]:
def main():
        #Class Declaration
        class date:
                def __init__(self):   #Class Constructor
                        #Default values
                        month=0
                        day=0
                        year=0
        #creating instances
        today=date()
        tomorrow=date()

        #List Declaration
        daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
        
        print("Enter today's date (mm/dd/yyyy):")
        today.month,today.day,today.year=map(int,"12/17/2004".split('/'))
        #today.month,today.day,today.year=map(int,raw_input().split('/'))

        #Calculations
        if( today.day != daysPerMonth[today.month - 1] ):
                tomorrow.day = today.day + 1;
                tomorrow.month = today.month;
                tomorrow.year = today.year;
        elif( today.month == 12 ):
                tomorrow.day = 1;
                tomorrow.month = 1;
                tomorrow.year = today.year + 1;
        else:
                tomorrow.day = 1;
                tomorrow.month = today.month + 1;
                tomorrow.year = today.year;

        #Result
        print("Tomorrow's date is {0}/{1}/{2}\n".format(tomorrow.month,tomorrow.day,tomorrow.year));


if __name__=='__main__':
        main()
Enter today's date (mm/dd/yyyy):
Tomorrow's date is 12/18/2004

Program 9.3, Page number: 171

In [3]:
class date:
        def __init__(self):   #Class Constructor
                #Default values
                month=0
                day=0
                year=0
 

def main():
       #creating instances
        today=date()
        tomorrow=date()

        print("Enter today's date (mm/dd/yyyy):")
        today.month,today.day,today.year=map(int,"2/28/2004".split('/'))
        #today.month,today.day,today.year=map(int,raw_input().split('/'))

        #Calculations
        if( today.day != numberOfDays(today) ):
                tomorrow.day = today.day + 1;
                tomorrow.month = today.month;
                tomorrow.year = today.year;
        elif( today.month == 12 ):
                tomorrow.day = 1;
                tomorrow.month = 1;
                tomorrow.year = today.year + 1;
        else:
                tomorrow.day = 1;
                tomorrow.month = today.month + 1;
                tomorrow.year = today.year;

        #Result
        print("Tomorrow's date is {0}/{1}/{2}\n".format(tomorrow.month,tomorrow.day,tomorrow.year));


def numberOfDays(d):
        
        #List Declaration
        daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
        if(isLeapYear(d)==True and d.month==2):
                days=29
        else:
                days = daysPerMonth[d.month - 1];

        return days


def isLeapYear(d):
        if ( (d.year % 4 == 0 and d.year % 100 != 0) or  d.year % 400 == 0 ):
                leapYearFlag = True        # Its a leap year
        else:
                leapYearFlag = False       # Not a leap year
        
        return leapYearFlag;



if __name__=='__main__':
        main()
Enter today's date (mm/dd/yyyy):
Tomorrow's date is 2/29/2004

Program 9.4, Page number: 174

In [4]:
class date:
        def __init__(self):   #Class Constructor
                #Default values
                month=0
                day=0
                year=0
 
        def dateUpdate(self,today):
                #Calculations                
                tomorrow=date()
                if( today.day != numberOfDays(today) ):
                        tomorrow.day = today.day + 1;
                        tomorrow.month = today.month;
                        tomorrow.year = today.year;
                elif( today.month == 12 ):
                        tomorrow.day = 1;
                        tomorrow.month = 1;
                        tomorrow.year = today.year + 1;
                else:
                        tomorrow.day = 1;
                        tomorrow.month = today.month + 1;
                        tomorrow.year = today.year;
             
                return tomorrow



def main():
       #creating instances
        thisDay=date()
        nextDay=date()
        
        print("Enter today's date (mm/dd/yyyy):")
        thisDay.month,thisDay.day,thisDay.year=map(int,"2/22/2004".split('/'))
        #thisDay.month,thisDay.day,thisDay.year=map(int,raw_input().split('/'))
        nextDay=thisDay.dateUpdate(thisDay)

        #Result
        print("Tomorrow's date is {0}/{1}/{2}\n".format(nextDay.month,nextDay.day,nextDay.year));




def numberOfDays(d):
        
        #List Declaration
        daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
        if(isLeapYear(d)==True and d.month==2):
                days=29
        else:
                days = daysPerMonth[d.month - 1];

        return days



def isLeapYear(d):
        if ( (d.year % 4 == 0 and d.year % 100 != 0) or  d.year % 400 == 0 ):
                leapYearFlag = True        # Its a leap year
        else:
                leapYearFlag = False       # Not a leap year
        
        return leapYearFlag;



if __name__=='__main__':
        main()
Enter today's date (mm/dd/yyyy):
Tomorrow's date is 2/23/2004

Program 9.5, Page number: 178

In [6]:
class time:
        def __init__(self):
                hour=0
                minutes=0
                seconds=0
        def timeUpdate(self,now):
                #Calculation
                now.seconds+=1
                if ( now.seconds == 60):             #next minute
                        now.seconds = 0
                        now.minutes+=1   
                        if ( now.minutes == 60 ):            #next hour
                                now.minutes = 0
                                now.hour+=1;
                                if ( now.hour == 24 ):                 #  midnight
                                        now.hour = 0
        

                return now

def main():
        #Creating instances
        currentTime=time()
        nextTime=time()
        #User Input
        print("Enter the time (hh:mm:ss):")
        currentTime.hour,currentTime.minutes,currentTime.seconds=map(int,"16:14:59".split(':'))
        #currentTime.hour,currentTime.minutes,currentTime.seconds=map(int,raw_input().split(':'))
        
        nextTime =currentTime.timeUpdate (currentTime);
        
        #Result
        print("Updated time is {0}:{1}:{2}\n".format(nextTime.hour,nextTime.minutes,nextTime.seconds))



if __name__=='__main__':
        main()
Enter the time (hh:mm:ss):
Updated time is 16:15:0

Program 9.6, Page number: 183

In [2]:
import sys

class time:
        def __init__(self,h,m,s):
                #Variable Declarations
                self.hour=h
                self.minutes=m
                self.seconds=s
        def timeUpdate(self,now):
                #Calculation
                now.seconds+=1
                if ( now.seconds == 60):             #next minute
                        now.seconds = 0
                        now.minutes+=1   
                        if ( now.minutes == 60 ):            #next hour
                                now.minutes = 0
                                now.hour+=1;
                                if ( now.hour == 24 ):                 #  midnight
                                        now.hour = 0
        

                return now

def main():
        #Creating instances
        testTimes = []
        testTimes.append(time(11,59,59))
        testTimes.append(time(12,0,0))
        testTimes.append(time(1,29,59))
        testTimes.append(time(23,59,59))
        testTimes.append(time(19,12,27))

        #Result
        for i in range(0,5):
               
                sys.stdout.write("Time is {0:2}:{1:2}:{2:2}  ".format(testTimes[i].hour,testTimes[i].minutes,testTimes[i].seconds))

                nextTime =testTimes[i].timeUpdate(testTimes[i])
        
        
                sys.stdout.write("...one second later it's {0:2}:{1:2}:{2:2}\n".format(testTimes[i].hour,testTimes[i].minutes,testTimes[i].seconds))



if __name__=='__main__':
        main()
Time is 11:59:59  ...one second later it's 12: 0: 0
Time is 12: 0: 0  ...one second later it's 12: 0: 1
Time is  1:29:59  ...one second later it's  1:30: 0
Time is 23:59:59  ...one second later it's  0: 0: 0
Time is 19:12:27  ...one second later it's 19:12:28

Program 9.7, Page number: 188

In [3]:
def main():
        #Class Declaration
        class month:
                def __init__(self,n,na):                 #Class Constructor
                        self.numberOfDays=n
                        self.name=na

        #List Declaration
        months=[]
        months.append(month(31,['j','a','n']))
        months.append(month(28,['f','e','b']))
        months.append(month(31,['m','a','r']))
        months.append(month(30,['a','p','r']))
        months.append(month(31,['m','a','y']))
        months.append(month(30,['j','u','n']))
        months.append(month(31,['j','u','l']))
        months.append(month(31,['a','u','g']))
        months.append(month(30,['s','e','p']))
        months.append(month(31,['o','c','t']))
        months.append(month(30,['n','o','v']))
        months.append(month(31,['d','e','c']))
        
        
        #Result
        print("Month     NumberOfDays")
        print("-----     ------------")
        for i in range (0,12):
                 print("{0}{1}{2}           {3}\n".format(months[i].name[0],months[i].name[1],months[i].name[2], months[i].numberOfDays))


if __name__=='__main__':
        main()
Month     NumberOfDays
-----     ------------
jan           31

feb           28

mar           31

apr           30

may           31

jun           30

jul           31

aug           31

sep           30

oct           31

nov           30

dec           31