0% found this document useful (0 votes)
71 views20 pages

CAE - 1 2024 Question Paper

The document outlines various programming tasks including data collection on a population's demographics, integer manipulation, two-factor authentication, Pascal's triangle generation, stock market data analysis, employee management system, and university administration management. Each task includes specific requirements and sample code implementations in Python. The tasks cover a range of topics such as data processing, class creation, and algorithm development.

Uploaded by

rithishsindhuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views20 pages

CAE - 1 2024 Question Paper

The document outlines various programming tasks including data collection on a population's demographics, integer manipulation, two-factor authentication, Pascal's triangle generation, stock market data analysis, employee management system, and university administration management. Each task includes specific requirements and sample code implementations in Python. The tasks cover a range of topics such as data processing, class creation, and algorithm development.

Uploaded by

rithishsindhuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Q. No.1.

Assume the population of a state consists of 'N' persons (both male and female) of
different age groups.
1. For the following queries, you are requested to collect the following data: name,
date of birth, gender.
2. Identify the number of male and female population in the given state
3. Compute the average age of the gender-based population based on the
following group:
a) lessthan 5 years
b) between 6 and 17 years
c) between 18 and 40 years
d) between 41 and 60 years
e) above 60 years
4. Display the gender-based count of people who are eligible to vote (Use
functions)
PROGRAM
from datetime import datetime
# Sample data of individuals
population_data = [
{"name": "John", "date_of_birth": "1990-05-15", "gender": "Male"},
{"name": "Emily", "date_of_birth": "2002-11-03", "gender": "Female"},
{"name": "Michael", "date_of_birth": "1985-07-22", "gender": "Male"},
# Add more data as needed
]

def calculate_age(dob):
today = datetime.today()
dob = datetime.strptime(dob, "%Y-%m-%d")
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
return age
def count_gender(population):
male_count = sum(1 for person in population if person['gender'] == 'Male')
female_count = sum(1 for person in population if person['gender'] == 'Female')
return male_count, female_count

def average_age_by_gender(population):
age_groups = {
'lessthan 5 years': [],
'between 6 and 17 years': [],
'between 18 and 40 years': [],
'between 41 and 60 years': [],
'above 60 years': []
}

for person in population:


age = calculate_age(person['date_of_birth'])
if age < 5:
age_groups['lessthan 5 years'].append(age)
elif 6 <= age <= 17:
age_groups['between 6 and 17 years'].append(age)
elif 18 <= age <= 40:
age_groups['between 18 and 40 years'].append(age)
elif 41 <= age <= 60:
age_groups['between 41 and 60 years'].append(age)
else:
age_groups['above 60 years'].append(age)

average_ages = {}
for group, ages in age_groups.items():
if ages:
average_ages[group] = sum(ages) / len(ages)
else:
average_ages[group] = 0

return average_ages

def count_eligible_voters(population):
eligible_voters = sum(1 for person in population if
calculate_age(person['date_of_birth']) >= 18)
return eligible_voters

# Test the functions


male_count, female_count = count_gender(population_data)
print("Number of males:", male_count)
print("Number of females:", female_count)

average_ages = average_age_by_gender(population_data)
print("\nAverage ages by gender group:")
for group, age in average_ages.items():
print(f"{group}: {age:.2f} years")

eligible_voters = count_eligible_voters(population_data)
print("\nNumber of eligible voters:", eligible_voters)
output
Number of males: 2
Number of females: 1

Average ages by gender group:


lessthan 5 years: 0.00 years
between 6 and 17 years: 0.00 years
between 18 and 40 years: 30.67 years
between 41 and 60 years: 0.00 years
above 60 years: 0.00 years

Number of eligible voters: 3

Q. No.2.
Integers when split into smaller digits, may exhibit the following behaviour
a) When split evenly, the resulting pattern will be either in increasing order or
decreasing order or unordered
b) May not be able to split evenly
For e.g
265263-> 2,6,5,2,6,3: Even Split Unordered
265263-> 26, 52, 63: Even Split-Increasing Order
265263-> 265, 263: Even Split - Decreasing Order
265263-> Cannot split beyond 3.
Prompt the user to input and display the possible combinations Note: Input digits
should be in any size
PROGRAM
def split_integer(integer):
integer_str = str(integer)
length = len(integer_str)

combinations = []

# Check for even split


for i in range(1, length):
split1 = integer_str[:i]
split2 = integer_str[i:]
combinations.append((split1, split2))
return combinations

def check_pattern(split):
split1, split2 = split
if split1 < split2:
return "Increasing Order"
elif split1 > split2:
return "Decreasing Order"
else:
return "Unordered"

# Prompt user input


input_integer = int(input("Enter an integer: "))

# Split the integer


combinations = split_integer(input_integer)

if combinations:
print("Possible combinations:")
for combination in combinations:
print(combination, "-", check_pattern(combination))
else:
print("Cannot split the integer beyond 1 digit.")

output
1. Enter an integer: 2
Cannot split the integer beyond 1 digit.
2. Enter an integer: 26
Possible combinations:
('2', '6') - Increasing Order
3. Enter an integer: 265
Possible combinations:
('2', '65') - Increasing Order
('26', '5') - Increasing Order
Q. No.3.
An organization is developing a two factor authentication system. The logic varies
between the first and the second level authentication. For the first level, it is
decided to permit 5 times for entering the passcode and should be blocked
thereafter. Similarly for the second level number of times to enter the passcode is
3.
a) For First Level:
Identify a number (minimum 4 digits) when multiplied by any digit 3. should
result in the reverse of the selected number For e.g. 2178 X 4 = 8712
b) For second level:
Identify three numbers that are relatively prime to each other and sum them
For e.g. GCD(8, 9, 19) = 1
Therefore, Key1: 2178 and Key2: 36
PROGRAM
import itertools
from math import gcd

def find_number_for_first_level():
for number in range(1000, 10000): # Minimum 4 digits
reverse_number = int(str(number)[::-1])
if reverse_number % 3 == 0 and number * 3 == reverse_number:
return number
return None

def find_numbers_for_second_level():
for numbers in itertools.combinations(range(2, 100), 3):
if gcd(numbers[0], gcd(numbers[1], numbers[2])) == 1:
return numbers
return None

# First Level
first_level_number = find_number_for_first_level()
if first_level_number:
print(f"First level number: {first_level_number}")
else:
print("No suitable number found for the first level.")

# Second Level
second_level_numbers = find_numbers_for_second_level()
if second_level_numbers:
key1, key2, key3 = second_level_numbers
print(f"Second level numbers: {key1}, {key2}, {key3}")
print(f"Sum of second level numbers: {sum(second_level_numbers)}")
else:
print("No suitable numbers found for the second level.")
output
No suitable number found for the first level.
Second level numbers: 2, 3, 4
Sum of second level numbers: 9
Q. No.4.
Print the PASCAL triangle in the following format (get the number of rows as
input)
1
121
1331
14641
1 5 10 5 1

PROGRAM
def generate_pascals_triangle(num_rows):
triangle = []
for row_num in range(num_rows):
row = [1] # First element is always 1
if row_num > 0:
prev_row = triangle[row_num - 1]
for j in range(1, row_num):
row.append(prev_row[j - 1] + prev_row[j])
row.append(1) # Last element is always 1
triangle.append(row)
return triangle

def print_pascals_triangle(triangle):
for row in triangle:
print(" ".join(map(str, row)).center(len(triangle[-1]) * 4))

num_rows = int(input("Enter the number of rows for Pascal's triangle: "))


triangle = generate_pascals_triangle(num_rows)
print_pascals_triangle(triangle)

output
Enter the number of rows for Pascal's triangle: 6
1
11
121
1331
14641
1 5 10 10 5 1
Q. No.5.
Consider the following dataset:
Date Open High Low Close Adj Close Volume 01-02-24 1122.26 1129.68 1097.44
1105.61 1105.61 2343100 02-02-24 1098.26 1126.85 1096.40 1120.83 1120.83
1964900
05-02-24 1119.01 1123.54 1079.81 1097.88 1097.88 2313400
06-02-24 1138.69 1194.66 1130.93 1186.92 1186.92 2664700 07-02-24 1221.45
1225.36 1182.22 1186.51 1186.51 2387300
08-02-24 1206.50 1219.06 1188.16 1210.28 1210.28 1975100
09-02-24 1224.07 1225.56 1196.73 1211.44 1211.44 2175400
For the above data set, plot a bar graph on adj. close, volume, thirty days and forty
days simple moving average between any two dates.

Q. No.6.
Write a Python class labelled as Employee
Class Attributes:
emp_id, emp_name, emp_salary, and emp_department
Class methods and their functions:
a) add_employee
Method to add a new employee (with all the relevant attributes and the input)
b) salary_calculation
Arguments: emp_salary, hours_worked
If the number of hours worked is over 40, overtime is computed and add it to the
salary.
overtime = hours_worked-40
ot_amount = (overtime (salary/40))
month_salary = salary + ot_amount 6.
c) department_change Method for Changing the employee department
d) display Method for displaying the employee details
Sample Employee Data:
emp_name, emp_id, emp_salary, emp_department
Emp1, E8021, 20000, HR
Emp2, E8059, 15000, SALES
Emp3, E9019, 30000, ACCOUNTS
Emp4, E9216, 45000, ADMINISTRATION
PROGRAM
class Employee:
def __init__(self, emp_id, emp_name, emp_salary, emp_department):
self.emp_id = emp_id
self.emp_name = emp_name
self.emp_salary = emp_salary
self.emp_department = emp_department

@classmethod
def add_employee(cls, emp_id, emp_name, emp_salary, emp_department):
return cls(emp_id, emp_name, emp_salary, emp_department)

def salary_calculation(self, hours_worked):


if hours_worked > 40:
overtime = hours_worked - 40
ot_amount = (overtime * self.emp_salary) / 40
month_salary = self.emp_salary + ot_amount
else:
month_salary = self.emp_salary
return month_salary

def department_change(self, new_department):


self.emp_department = new_department

def display(self):
print(f"Employee ID: {self.emp_id}")
print(f"Employee Name: {self.emp_name}")
print(f"Employee Salary: {self.emp_salary}")
print(f"Employee Department: {self.emp_department}")

# Sample Employee Data


emp1 = Employee.add_employee("E8021", "Emp1", 20000, "HR")
emp2 = Employee.add_employee("E8059", "Emp2", 15000, "SALES")
emp3 = Employee.add_employee("E9019", "Emp3", 30000, "ACCOUNTS")
emp4 = Employee.add_employee("E9216", "Emp4", 45000, "ADMINISTRATION")

# Display Employee Details


emp1.display()
print()

# Calculate Salary for emp1


hours_worked = 45
print(f"Monthly Salary for emp1 with {hours_worked} hours worked:
{emp1.salary_calculation(hours_worked)}")
print()

# Change Department for emp1


emp1.department_change("IT")
print("After department change:")
emp1.display()

Output
Employee ID: E8021
Employee Name: Emp1
Employee Salary: 20000
Employee Department: HR

Monthly Salary for emp1 with 45 hours worked: 22500.0

After department change:


Employee ID: E8021
Employee Name: Emp1
Employee Salary: 20000
Employee Department: IT

Q. No.7.
A system is developed for managing the university's administrative tasks. In this
system, the various entities are students, faculty, courses, and departments. Each
entity has specific attributes and behaviors, and there are relationships between
them.
 Define a class person with attributes name and age. Implement methods to
set and get these attributes.
 Create a class Student which inherits from Person, Student should have
additional attributes such as student_id, courses_taken, and GPA.
Implement methods to add courses, calculate GPA, and display student
information.
 Create a class Faculty which inherits from Person. Faculty should have
additional attributes such as employee_id, department, and position.
Implement methods to assign courses and display faculty information.
 Define a class Course with attributes course_code, course_name,
credit_hours, and faculty_assigned. Implement methods to assign faculty to
the course and display course information.
 Create a class Department with attributes department_name and
faculty_list. Implement methods to add faculty to the department, assign
courses to faculty, and display department information.
PROGRAM
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def set_name(self, name):
self.name = name

def get_name(self):
return self.name

def set_age(self, age):


self.age = age

def get_age(self):
return self.age

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
self.courses_taken = []
self.gpa = None

def add_course(self, course):


self.courses_taken.append(course)

def calculate_gpa(self):
if not self.courses_taken:
return None
total_credits = sum(course.credit_hours for course in self.courses_taken)
weighted_sum = sum(course.credit_hours * course.grade for course in
self.courses_taken)
self.gpa = weighted_sum / total_credits
return self.gpa

def display_info(self):
print("Student Information:")
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Student ID: {self.student_id}")
print(f"Courses Taken: {', '.join(course.course_name for course in
self.courses_taken)}")
print(f"GPA: {self.gpa}")

class Faculty(Person):
def __init__(self, name, age, employee_id, department, position):
super().__init__(name, age)
self.employee_id = employee_id
self.department = department
self.position = position
self.courses_assigned = []

def assign_course(self, course):


self.courses_assigned.append(course)

def display_info(self):
print("Faculty Information:")
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Employee ID: {self.employee_id}")
print(f"Department: {self.department}")
print(f"Position: {self.position}")
print(f"Courses Assigned: {', '.join(course.course_name for course in
self.courses_assigned)}")

class Course:
def __init__(self, course_code, course_name, credit_hours):
self.course_code = course_code
self.course_name = course_name
self.credit_hours = credit_hours
self.faculty_assigned = None

def assign_faculty(self, faculty):


self.faculty_assigned = faculty

def display_info(self):
print("Course Information:")
print(f"Course Code: {self.course_code}")
print(f"Course Name: {self.course_name}")
print(f"Credit Hours: {self.credit_hours}")
if self.faculty_assigned:
print(f"Faculty Assigned: {self.faculty_assigned.name}")
else:
print("Faculty Not Assigned")

class Department:
def __init__(self, department_name):
self.department_name = department_name
self.faculty_list = []
self.course_list = []
def add_faculty(self, faculty):
self.faculty_list.append(faculty)

def assign_course_to_faculty(self, faculty, course):


faculty.assign_course(course)

def add_course(self, course):


self.course_list.append(course)

def display_info(self):
print("Department Information:")
print(f"Department Name: {self.department_name}")
print("Faculty List:")
for faculty in self.faculty_list:
print(f" {faculty.name}")
print("Course List:")
for course in self.course_list:
print(f" {course.course_name}")

# Example Usage
student1 = Student("Alice", 20, "S12345")
course1 = Course("CSC101", "Introduction to Computer Science", 3)
course2 = Course("MAT101", "Calculus I", 4)
student1.add_course(course1)
student1.add_course(course2)
student1.calculate_gpa()
student1.display_info()
print()
faculty1 = Faculty("Dr. Smith", 45, "F98765", "Computer Science", "Professor")
faculty1.assign_course(course1)
faculty1.assign_course(course2)
faculty1.display_info()
print()

department1 = Department("Computer Science")


department1.add_faculty(faculty1)
department1.add_course(course1)
department1.add_course(course2)
department1.assign_course_to_faculty(faculty1, course1)
department1.display_info()
output

Q. No.8.
Consider the scenario for designing a drawing application. There are various
shapes such as circles, rectangles, and triangles. Implement a feature that allows
to calculate the total perimeter and total area of all shapes on the canvas.
However, it should be able to select specific types of shapes and perform
operations only on those shapes.
Consider the following structure:
1. Define a base class Shape with abstract methods area() and perimeter().
2. Create subclasses for different shapes such as Rectangle, Circle, and Triangle,
each inheriting from Shape.
3. Implement the abstract methods in each subclass to calculate the area and
perimeter specific to that shape.
4. Create a class Canvas to manage a collection of shapes.
5. Implement methods in the Canvas class to add shapes, calculate total area and
perimeter, and perform operations on specific types of shapes.
PROGRAM
import math
from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

@abstractmethod
def perimeter(self):
pass

class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

def perimeter(self):
return 2 * (self.width + self.height)

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius

class Triangle(Shape):
def __init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3

def area(self):
s = (self.side1 + self.side2 + self.side3) / 2
return math.sqrt(s * (s - self.side1) * (s - self.side2) * (s - self.side3))

def perimeter(self):
return self.side1 + self.side2 + self.side3

class Canvas:
def __init__(self):
self.shapes = []

def add_shape(self, shape):


self.shapes.append(shape)

def total_area(self):
return sum(shape.area() for shape in self.shapes)

def total_perimeter(self):
return sum(shape.perimeter() for shape in self.shapes)
def total_area_perimeter_of_shape(self, shape_type):
total_area = sum(shape.area() for shape in self.shapes if isinstance(shape,
shape_type))
total_perimeter = sum(shape.perimeter() for shape in self.shapes if
isinstance(shape, shape_type))
return total_area, total_perimeter

# Example usage:
canvas = Canvas()
canvas.add_shape(Rectangle(4, 5))
canvas.add_shape(Circle(3))
canvas.add_shape(Triangle(3, 4, 5))

print("Total area of all shapes on the canvas:", canvas.total_area())


print("Total perimeter of all shapes on the canvas:", canvas.total_perimeter())

rectangle_area, rectangle_perimeter = canvas.total_area_perimeter_of_shape(Rectangle)


print("Total area of rectangles on the canvas:", rectangle_area)
print("Total perimeter of rectangles on the canvas:", rectangle_perimeter)

output
Total area of all shapes on the canvas: 54.27433388230814
Total perimeter of all shapes on the canvas: 48.84955592153876
Total area of rectangles on the canvas: 20
Total perimeter of rectangles on the canvas: 18

You might also like