Chapter 11: Structures and Unions

Example 11.1, Page number: 388

In [1]:
# Structure declaration
class student :
	id_no = ''
	name = ''
	address = ''
	age = ''
	
newstudent = student()

print ('Enter the student information ')
newstudent.id_no = int(raw_input('Enter student id_no : '))
newstudent.name = raw_input('Enter name of the student : ')
newstudent.address = raw_input('Enter the address of the student : ')
newstudent.age = int(raw_input('Enter the age of the student : '))

print ('You have entered following information...')
print ('Student id_number = %d ' % newstudent.id_no)
print ('Student name = %s ' % newstudent.name)
print ('Student address = %s ' % newstudent.address)
print ('Age of student = %d ' % newstudent.age)
Enter the student information 
Enter student id_no : 1
Enter name of the student : Amanjeet
Enter the address of the student : Delhi
Enter the age of the student : 20
You have entered following information...
Student id_number = 1 
Student name = Amanjeet 
Student address = Delhi 
Age of student = 20 

Example 11.2, Page number: 390

In [2]:
# Structure declaration
class student :
	id_no = ''
	name = ''
	address = ''
	age = ''
	
newstudent = student()

def putdata (newstudent) : 
   print ('You have entered following information...')
   print ('Student id_number = %d ' % newstudent.id_no)
   print ('Student name = %s ' % newstudent.name)
   print ('Student address = %s ' % newstudent.address)
   print ('Age of student = %d ' % newstudent.age)
    
print ('Enter the student information ')    
newstudent.id_no = int(raw_input('Enter student id_no : '))
newstudent.name = raw_input('Enter name of the student : ')
newstudent.address = raw_input('Enter the address of the student : ')
newstudent.age = int(raw_input('Enter the age of the student : '))

putdata (newstudent)
Enter the student information 
Enter student id_no : 2
Enter name of the student : Deepti
Enter the address of the student : Noida
Enter the age of the student : 23
You have entered following information...
Student id_number = 2 
Student name = Deepti 
Student address = Noida 
Age of student = 23 

Example 11.3, Page number: 392

In [3]:
# Structure declaration
class student :
	id_no = ''
	name = ''
	address = ''
	age = ''
	
newstudent = student()

def putdata (idno, name, add, age) :
   print ('You have entered following information...')
   print ('Student id_number = %d ' % idno)
   print ('Student name = %s ' % name)
   print ('Student address = %s ' % add)
   print ('Age of student = %d ' % age)
    
print ('Enter the student information ')
newstudent.id_no = int(raw_input('Enter student id_no : '))
newstudent.name = raw_input('Enter name of the student : ')
newstudent.address = raw_input('Enter the address of the student : ')
newstudent.age = int(raw_input('Enter the age of the student : '))

putdata (newstudent.id_no, newstudent.name, newstudent.address, newstudent.age)
Enter the student information 
Enter student id_no : 3
Enter name of the student : Kushagra
Enter the address of the student : Bangalore
Enter the age of the student : 21
You have entered following information...
Student id_number = 3 
Student name = Kushagra 
Student address = Bangalore 
Age of student = 21 

Example 11.4, Page number: 395

In [4]:
# Structure declaration
class student :
	id_no = 0
	name = 'Unknown'
	address = 'Unknown'
	age = 0
	
newstudent = student()

def readdata (newstudent) :
   print ('Enter the student information ')
   newstudent.id_no = int(raw_input('Enter student id_no : '))
   newstudent.name = raw_input('Enter name of the student : ')
   newstudent.address = raw_input('Enter the address of the student : ')
   newstudent.age = int(raw_input('Enter the age of the student : '))

readdata (newstudent)
print ('You have entered following information...')
print ('Student id_number = %d ' % newstudent.id_no)
print ('Student name = %s ' % newstudent.name)
print ('Student address = %s ' % newstudent.address)
print ('Age of student = %d ' % newstudent.age)
Enter the student information 
Enter student id_no : 4
Enter name of the student : Vipul
Enter the address of the student : Chandigarh
Enter the age of the student : 25
You have entered following information...
Student id_number = 4 
Student name = Vipul 
Student address = Chandigarh 
Age of student = 25 

Example 11.5, Page number: 397

In [6]:
# Structure declaration
class student :
	id_no = 0
	name = 'Unknown'
	address = 'Unknown'
	age = 0
	
def readdata () :
   x = student()
   print ('Enter the student information ')
   x.id_no = int(raw_input('Enter student id_no : '))
   x.name = raw_input('Enter name of the student : ')
   x.address = raw_input('Enter the address of the student : ')
   x.age = int(raw_input('Enter the age of the student : '))
   return x

newstudent = readdata()

print ('You have entered following information...')
print ('Student id_number = %d ' % newstudent.id_no)
print ('Student name = %s ' % newstudent.name)
print ('Student address = %s ' % newstudent.address)
print ('Age of student = %d ' % newstudent.age)
Enter the student information 
Enter student id_no : 5
Enter name of the student : Ujjwal
Enter the address of the student : Jaipur
Enter the age of the student : 20
You have entered following information...
Student id_number = 5 
Student name = Ujjwal 
Student address = Jaipur 
Age of student = 20 

Example 11.6, Page number: 400

In [8]:
# Structure declaration
class student :
	id_no = 0
	name = 'Unknown'
	address = 'Unknown'
	age = 0
	
x = student()

def readdata (x) :
   print ('Enter the student information ')
   x.id_no = int(raw_input('Enter student id_no : '))
   x.name = raw_input('Enter name of the student : ')
   x.address = raw_input('Enter the address of the student : ')
   x.age = int(raw_input('Enter the age of the student : '))

readdata(x)    
print ('You have entered following information...')
print ('Student id_number = %d ' % x.id_no)
print ('Student name = %s ' % x.name)
print ('Student address = %s ' % x.address)
print ('Age of student = %d ' % x.age)
Enter the student information 
Enter student id_no : 6
Enter name of the student : Karan
Enter the address of the student : Chennai
Enter the age of the student : 24
You have entered following information...
Student id_number = 6 
Student name = Karan 
Student address = Chennai 
Age of student = 24 

Example 11.7, Page number: 403

In [8]:
# Structure declaration
class student (object) :
	def __init__(self, roll=None, name=None, gender=None, marks=[0]*3) :
		self.roll = roll
		self.name = name
		self.gender = gender
		self.marks = marks

def putdata (stud, count) :
	print ('RollNo\t   Name\t\t   Gender\t   Sub1\t      Sub2\t Sub3 ')
	print ('---------------------------------------------------------------------')
	
	for i in range (0, count) :
		print ('%-10d' % stud[i].roll),
		print ('%-15s' % stud[i].name),
		
		if stud[i].gender == 0 :
			print ('%-15s' % 'Female'),
		else :
			print ('%-15s' % 'Male'),
		
		for j in range (0, 3) :
			print ('%-10d' % stud[i].marks[j]),
		print

def calculateper (stud, count) :
	average = 0
	for i in range (0, count) :
		sum = 0
		for j in range (0, 3) :
			sum = sum + stud[i].marks[j]
		average = average + sum/3
	return average/count

stud = []	
stud.append (student (1, 'Kapildev', 1, (45, 56, 67)))
stud.append (student (2, 'Vidya', 0, (87, 45, 23)))
stud.append (student (3, 'Sharada', 0, (67, 94, 56)))
stud.append (student (4, 'Saismaran', 1, (56, 38, 84)))
stud.append (student (5, 'Reshma', 0, (67, 98, 76)))

average_percentage = calculateper (stud, 5)
putdata (stud, 5)
print ('\nAverage percentage of the class is : %.2f ' % average_percentage)
RollNo	   Name		   Gender	   Sub1	      Sub2	 Sub3 
---------------------------------------------------------------------
1          Kapildev        Male            45         56         67        
2          Vidya           Female          87         45         23        
3          Sharada         Female          67         94         56        
4          Saismaran       Male            56         38         84        
5          Reshma          Female          67         98         76        

Average percentage of the class is : 63.00 

Example 11.8, Page number: 406

In [11]:
# Structure declaration
class student (object) :
	def __init__(self, roll=None, name=None, gender=None, marks=[0]*3) :
		self.roll = roll
		self.name = name
		self.gender = gender
		self.marks = marks
	
def putdata (stud, count) :
	print ('\nRollNo\t   Name\t\t   Gender\t   Sub1\t      Sub2\t Sub3 ')
	print ('---------------------------------------------------------------------')
	
	for i in range (0, count) :
		print ('%-10d' % stud[i].roll),
		print ('%-15s' % stud[i].name),
		
		if stud[i].gender == 0 :
			print ('%-15s' % 'Female'),
		else :
			print ('%-15s' % 'Male'),
		
		for j in range (0, 3) :
			print ('%-10d' % stud[i].marks[j]),
		print

def calculateper (stud, count) :
	average = 0
	for i in range (0, count) :
		sum = 0
		for j in range (0, 3) :
			sum = sum + stud[i].marks[j]
		average = average + sum/3
	return average/count

count = int(raw_input('Enter the number of students in a class : '))
stud = [student() for i in range (0, count)]

for i in range (0, count) :
	stud[i].roll = int(raw_input('\nEnter roll number of student %d: ' % (i+1)))
	stud[i].name = raw_input('Enter name of student %d: ' % (i+1))
	stud[i].gender = int(raw_input('Enter gender[0/1] of student %d: ' % (i+1)))
	print ('Enter marks of three subjects of student %d: ' % (i+1))
	for j in range (0, 3) :
		stud[i].marks[j] = int(raw_input('Subject %d: ' % (j+1)))

putdata (stud, count)
average_percentage = calculateper (stud, count)
print ('\nAverage percentage of the class is : %.2f ' % average_percentage)
Enter the number of students in a class : 1

Enter roll number of student 1: 24
Enter name of student 1: Vidya
Enter gender[0/1] of student 1: 0
Enter marks of three subjects of student 1: 
Subject 1: 78
Subject 2: 96
Subject 3: 75

RollNo	   Name		   Gender	   Sub1	      Sub2	 Sub3 
---------------------------------------------------------------------
24         Vidya           Female          78         96         75        

Average percentage of the class is : 83.00 

Example 11.9, Page number: 408

In [13]:
# Structure declaration
class student (object) :
	def __init__(self, roll=None, name=None, gender=None, marks=[0]*3) :
		self.roll = roll
		self.name = name
		self.gender = gender
		self.marks = marks

def readdata (stud, count) :
	for i in range (0, count) :
		stud[i].roll = int(raw_input('\nEnter roll number of student %d: ' % (i+1)))
		stud[i].name = raw_input('Enter name of student %d: ' % (i+1))
		stud[i].gender = int(raw_input('Enter gender[0/1] of student %d: ' % (i+1)))
		print ('Enter marks of three subjects of student %d: ' % (i+1))
		for j in range (0, 3) :
			stud[i].marks[j] = int(raw_input('Subject %d: ' % (j+1)))
	
def putdata (stud, count) :
	print ('\nRollNo\t   Name\t\t   Gender\t   Sub1\t      Sub2\t Sub3 ')
	print ('---------------------------------------------------------------------')
	
	for i in range (0, count) :
		print ('%-10d' % stud[i].roll),
		print ('%-15s' % stud[i].name),
		
		if stud[i].gender == 0 :
			print ('%-15s' % 'Female'),
		else :
			print ('%-15s' % 'Male'),
		
		for j in range (0, 3) :
			print ('%-10d' % stud[i].marks[j]),
		print

def calculateper (stud, count) :
	average = 0
	for i in range (0, count) :
		sum = 0
		for j in range (0, 3) :
			sum = sum + stud[i].marks[j]
		average = average + sum/3
	return average/count

count = int(raw_input('Enter the number of students in a class : '))
stud = [student() for i in range (0, count)]
readdata (stud, count)

average_percentage = calculateper (stud, count)
putdata (stud, count)
print ('\nAverage percentage of the class is : %.2f ' % average_percentage)
Enter the number of students in a class : 1

Enter roll number of student 1: 25
Enter name of student 1: Kapildev
Enter gender[0/1] of student 1: 1
Enter marks of three subjects of student 1: 
Subject 1: 45
Subject 2: 70
Subject 3: 93

RollNo	   Name		   Gender	   Sub1	      Sub2	 Sub3 
---------------------------------------------------------------------
25         Kapildev        Male            45         70         93        

Average percentage of the class is : 69.00 

Example 11.10, Page number: 412

In [14]:
# Structure declaration
class time (object) :
	def __init__(self, hours=None, minutes=None, seconds=None) :
		self.hours = hours
		self.minutes = minutes
		self.seconds = seconds

def AcceptTime (t) :
	print ('Enter the time in hh mm ss format: ')
	t.hours = int(raw_input('Hours = '))
	t.minutes = int(raw_input('Minutes = '))
	t.seconds = int(raw_input('Seconds = '))

def ValidateTime (t) :
	if t.hours < 0 or t.hours > 23 :
		return 0
	if t.minutes < 0 or t.minutes > 60 :
		return 0
	if t.seconds < 0 or t.seconds > 60 :
		return 0
	return 1

def DisplayTime (t) :
	print ('Time you entered is %d:%d:%d ' % (t.hours, t.minutes, t.seconds))
	
condition = True
while condition :
	t = time ()
	AcceptTime (t)
	
	if ValidateTime (t) == 1 :
		condition = False
	else :
		print ('\nTime is incorrect. Enter again ')
		
DisplayTime (t)
Enter the time in hh mm ss format: 
Hours = 13
Minutes = 45
Seconds = 53
Time you entered is 13:45:53 

Example 11.11, Page number: 414

In [15]:
# Structure declaration
class date (object) :
	def __init__(self, dd=None, mm=None, yy=None) :
		self.dd = dd
		self.mm = mm
		self.yy = yy

def AcceptDate (d) :
	print ('Enter date in dd mm yy format: ')
	d.dd = int(raw_input('Date = '))
	d.mm = int(raw_input('Month = '))
	d.yy = int(raw_input('Year = '))

def isleap (val) :
	if val % 4 == 0 and val % 100 or val % 400 == 0 :
		return 1
	return 0
	
def ValidateDate (d) :
	if d.dd < 1 or d.dd > 31 :
		return 0
	if d.mm < 1 or d.mm > 12 :
		return 0
	if d.yy < 1 :
		return 0
	if d.mm == 2 :
		if isleap (d.yy) :
			if d.dd > 29 :
				return 0
		elif d.dd > 28 :
			return 0
	if d.mm == 4 or d.mm == 6 or d.mm == 9 or d.mm == 11 and d.dd > 30 :
		return 0
	return 1

def DisplayMsg (d1, d2) :
	if d1.dd == d2.dd and d1.mm == d2.mm and d1.yy == d2.yy :
		print ('Both dates are Equal ')
	else :
		print ('Both dates are Not Equal ')
	
condition = True
while condition :
	d1 = date ()
	AcceptDate (d1)
	
	if ValidateDate (d1) == 1 :
		condition = False
	else :
		print ('\nDate is incorrect. Enter again ')

condition = True
while condition :
	d2 = date ()
	AcceptDate (d2)
	
	if ValidateDate (d2) == 1 :
		condition = False
	else :
		print ('\nDate is incorrect. Enter again ')
		
DisplayMsg (d1, d2)
Enter date in dd mm yy format: 
Date = 12
Month = 11
Year = 92
Enter date in dd mm yy format: 
Date = 12
Month = 11
Year = 92
Both dates are Equal 

Example 11.12, Page number: 415

In [16]:
# Structure declaration
class date (object) :
	def __init__(self, dd=None, mm=None, yy=None) :
		self.dd = dd
		self.mm = mm
		self.yy = yy

def AcceptDate (d) :
	print ('Enter date in dd mm yy format: ')
	d.dd = int(raw_input('Date = '))
	d.mm = int(raw_input('Month = '))
	d.yy = int(raw_input('Year = '))

def isleap (val) :
	if val % 4 == 0 and val % 100 or val % 400 == 0 :
		return 1
	return 0
	
def ValidateDate (d) :
	if d.dd < 1 or d.dd > 31 :
		return 0
	if d.mm < 1 or d.mm > 12 :
		return 0
	if d.yy < 1 :
		return 0
	if d.mm == 2 :
		if isleap (d.yy) :
			if d.dd > 29 :
				return 0
		elif d.dd > 28 :
			return 0
	if d.mm == 4 or d.mm == 6 or d.mm == 9 or d.mm == 11 and d.dd > 30 :
		return 0
	return 1

def CalcDate (d1, d2) :
	date1 = date2 = 0
	for i in range (-d1.yy, d1.yy) :
		date1 = date1 + 366 if isleap (d1.yy) else 365
		d1.yy = d1.yy - 1
		
	for i in range (-d1.mm, d1.mm) :
		date1 = date1 + (30 if (d1.mm==4 or d1.mm==6 or d1.mm==9 or d1.mm==11) else ((29 if isleap(d1.yy) else 28) if (d1.mm==2) else 31))
	
	date1 = date1 + d1.dd
	
	for i in range (-d2.yy, d2.yy) :
		date2 = date2 + 366 if isleap(d2.yy) else 365
	
	for i in range (-d2.mm, d2.mm) :
		date2 = date2 + (30 if (d2.mm==4 or d2.mm==6 or d2.mm==9 or d2.mm==11) else ((29 if isleap(d2.yy) else 28) if d2.mm==2 else 31))
	
	date2 = date2 + d2.dd
	
	return (date2 - date1)/2
		
def DisplayMsg (d1, d2, diff) :
	print ('The difference between %d %d %d and %d %d %d is %d days ' % (d1.dd, d1.mm, -d1.yy, d2.dd, d2.mm, d2.yy, diff))
	
condition = True
while condition :
	print ('\nEnter first date: ')
	d1 = date ()
	AcceptDate (d1)
	
	if ValidateDate (d1) == 1 :
		condition = False
	else :
		print ('\nDate is incorrect. Enter again ')

condition = True
while condition :
	print ('\nEnter second date: ')
	d2 = date ()
	AcceptDate (d2)
	
	if ValidateDate (d2) == 1 :
		condition = False
	else :
		print ('\nDate is incorrect. Enter again ')

diff = CalcDate (d1, d2)
DisplayMsg (d1, d2, diff)
Enter first date: 
Enter date in dd mm yy format: 
Date = 01
Month = 01
Year = 01

Enter second date: 
Enter date in dd mm yy format: 
Date = 25
Month = 12
Year = 08
The difference between 1 1 1 and 25 12 8 is 2915 days 

Example 11.13, Page number: 419

In [17]:
from ctypes import *

# Structure declaration
class stream (Union) :
	_fields_ = [('grade', c_char), 
					('class_std', c_int), 
					('percentage', c_float)]
	
class student (Structure) :
	_fields_ = [('roll', c_int), 
					('name', c_char_p), 
					('gender', c_int), 
					('marks', c_int * 3), 
					('st_stream', c_char), 
					('st', stream)]
	
def putdata (stud, count) :
	print ('\nStream\t   Roll\t  Name\t        Gender\t  Result\t ')
	print ('---------------------------------------------------------------------')
	
	for i in range (0, count) :
		if stud[i].st_stream == 'A' :
			print ('Arts\t  '),
		elif stud[i].st_stream == 'S' :
			print ('Science\t  '),
		else :
			print ('Commerce  '),
			
		print ('%-5d ' % stud[i].roll),
		print ('%-3s ' % stud[i].name),
		
		if stud[i].gender == 0 :
			print ('\tFemale'),
		else :
			print ('\tMale  '),
		
		if stud[i].st_stream == 'A' :
			print ('   %d Class ' % stud[i].st.class_std),
		elif stud[i].st_stream == 'S' :
			print ('   %c Grade ' % stud[i].st.grade),
		else :
			print ('   %.2f Percent ' % stud[i].st.percentage),
		print

def calculateper (stud, count) :
	average = 0
	for i in range (0, count) :
		sum = 0
		for j in range (0, 3) :
			sum = sum + stud[i].marks[j]
		average = (float)(sum/3)
		
		if stud[i].st_stream == 'A' :
			if average >= 60 :
				stud[i].st.class_std = 1
			else :
				stud[i].st.class_std = 2
				
		elif stud[i].st_stream == 'S' :
			if average >= 60 :
				stud[i].st.grade = 'A'
			else :
				stud[i].st.class_std = 'B'
		else : 
			stud[i].st.percentage = average

count = int(raw_input('Enter the number of students in a class : '))
stud = [student() for i in range (0, count)]

for i in range (0, count) :
	stud[i].st_stream = raw_input('\nEnter stream of student %d (A/C/S) : ' % (i+1))
	stud[i].roll = int(raw_input('Enter roll number of student %d : ' % (i+1)))
	stud[i].name = raw_input('Enter name of student %d : ' % (i+1))
	stud[i].gender = int(raw_input('Enter gender of student %d [0/1] : ' % (i+1)))
	print ('Enter marks of three subjects of student %d : ' % (i+1))
	for j in range (0, 3) :
		stud[i].marks[j] = int(raw_input('Subject %d : ' % (j+1)))
	
calculateper (stud, count)
putdata (stud, count)
Enter the number of students in a class : 3

Enter stream of student 1 (A/C/S) : A
Enter roll number of student 1 : 1
Enter name of student 1 : Saismaran
Enter gender of student 1 [0/1] : 1
Enter marks of three subjects of student 1 : 
Subject 1 : 65
Subject 2 : 83
Subject 3 : 59

Enter stream of student 2 (A/C/S) : C
Enter roll number of student 2 : 2
Enter name of student 2 : Vidya
Enter gender of student 2 [0/1] : 0
Enter marks of three subjects of student 2 : 
Subject 1 : 84
Subject 2 : 75
Subject 3 : 93

Enter stream of student 3 (A/C/S) : S
Enter roll number of student 3 : 3
Enter name of student 3 : Pranav
Enter gender of student 3 [0/1] : 1
Enter marks of three subjects of student 3 : 
Subject 1 : 84
Subject 2 : 95
Subject 3 : 83

Stream	   Roll	  Name	        Gender	  Result	 
---------------------------------------------------------------------
Arts	   1      Saismaran  	Male      1 Class 
Commerce   2      Vidya  	Female    84.00 Percent 
Science	   3      Pranav  	Male      A Grade