Questions Classes
Questions Classes
Questions Classes
Write a Python program to import a built-in array module and display the
namespace of the said module.
import array
for name in array.__dict__:
print(name)
2. Write a Python program to create a class and display the namespace of that
class.
class py_solution:
def sub_sets(self, sset):
return self.subsetsRecur([], sorted(sset))
def subsetsRecur(self, current, sset):
if sset:
return self.subsetsRecur(current, sset[1:]) +
self.subsetsRecur(current + [sset[0]], sset[1:])
return [current]
for name in py_solution.__dict__:
print(name)
3. Write a Python program to create an instance of a specified class and display the
namespace of the said instance.
class Student:
def __init__(self, student_id, student_name, class_name):
self.student_id = student_id
self.student_name = student_name
self.class_name = class_name
student = Student('V12', 'Frank Gibson', 'V')
print(student.__dict__)
8. Write a Python program to create two empty classes, Student and Marks. Now
create some instances and check whether they are instances of the said classes
or not. Also, check whether the said classes are subclasses of the built-in object
class or not.
class Student:
pass
class Marks:
pass
student1 = Student()
marks1 = Marks()
print(isinstance(student1, Student))
print(isinstance(marks1, Student))
print(isinstance(marks1, Marks))
print(isinstance(student1, Marks))
print(issubclass(Student, object))
print(issubclass(Marks, object))
9. Write a Python class named Student with two attributes student_name, marks.
Modify the attribute values of the said class and print the original and modified
values of the said attributes.
class Student:
student_name = 'Terrance Morales'
marks = 93
print(f"Student Name: {getattr(Student, 'student_name')}")
print(f"Marks: {getattr(Student, 'marks')}")
setattr(Student, 'student_name', 'Angel Brooks')
setattr(Student, 'marks', 95)
print(f"Student Name: {getattr(Student, 'student_name')}")
print(f"Marks: {getattr(Student, 'marks')}")
10. Write a Python class named Student with two attributes student_id,
student_name. Add a new attribute student_class and display the entire attribute
and the values of the class. Now remove the student_name attribute and display
the entire attribute with values.
class Student:
student_id = 'V10'
student_name = 'Jacqueline Barnett'
print("Original attributes and values of the Student class:")
for attr, value in Student.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
print("\nnew attributes and values with the said class:")
Student.student_class = 'V'
for attr, value in Student.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
print("\nremoving, attributes and values from the class:")
del Student.student_name
#delattr(Student, 'student_name')
for attr, value in Student.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
11. Write a Python class named Student with two attributes: student_id,
student_name. Add a new attribute: student_class. Create a function to display all
attributes and their values in the Student class.
class Student:
student_id = 'V10'
student_name = 'Jacqueline Barnett'
def display():
print(f'Student id: {Student.student_id}\nStudent Name:
{Student.student_name}')
print("Original attributes and values of the Student class:")
Student.display()
12. Write a Python class named Student with two instances student1, student2
and assign values to the instances' attributes. Print all the attributes of the
student1, student2 instances with their values in the given format.
Input values of the instances:
student_1:
student_id = "V12"
student_name = "Ernesto Mendez"
student_2:
student_id = "V12"
marks_language = 85
marks_science = 93
marks_math = 95
Expected Output:
student_id -> V12
student_name -> Ernesto Mendez
student_id -> V12
marks_language -> 85
marks_science -> 93
marks_math -> 95
class Student:
school = 'Forward Thinking'
address = '2626/Z Overlook Drive, COLUMBUS'
student1 = Student()
student2 = Student()
student1.student_id = "V12"
student1.student_name = "Ernesto Mendez"
student2.student_id = "V12"
student2.marks_language = 85
student2.marks_science = 93
student2.marks_math = 95
students = [student1, student2]
for student in students:
print('\n')
for attr in student.__dict__:
print(f'{attr} -> {getattr(student, attr)}')
13. Write a Python class to convert an integer to a Roman numeral.
class py_solution:
def int_to_Roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i = 0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
print(py_solution().int_to_Roman(1))
print(py_solution().int_to_Roman(4000))
14. Write a Python class to convert a Roman numeral to an integer.
class py_solution:
def roman_to_int(self, s):
rom_val = {'I':1,'V':5,'X':10,'L': 50, 'C': 100, 'D': 500,
'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
else:
int_val += rom_val[s[i]]
return int_val
print(py_solution().roman_to_int('MMMCMLXXXVI'))
print(py_solution().roman_to_int('MMMM'))
print(py_solution().roman_to_int('C'))
15. Write a Python class to check the validity of a string of parentheses, '(', ')',
'{', '}', '[' and ']. These brackets must be closed in the correct order, for example
"()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid.
class py_solution:
def is_valid_parenthese(self, str1):
stack, pchar = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in str1:
if parenthese in pchar:
stack.append(parenthese)
elif len(stack) == 0 or pchar[stack.pop()] !=
parenthese:
return False
return len(stack) == 0
print(py_solution().is_valid_parenthese("(){}[]"))
print(py_solution().is_valid_parenthese("()[{)}"))
print(py_solution().is_valid_parenthese("()"))
16. Write a Python class to get all possible unique subsets from a set of distinct
integers.
Input : [4, 5, 6]
Output : [[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]
class py_solution:
def sub_sets(self, sset):
return self.subsetsRecur([], sorted(sset))
print(py_solution().sub_sets([4,5,6]))
17. Write a Python class to find a pair of elements (indices of the two numbers)
from a given array whose sum equals a specific target number.
Note: There will be one solution for each input and do not use the same element
twice.
Input: numbers= [10,20,10,40,50,60,70], target=50
Output: 3, 4
class py_solution:
def twoSum(self, nums, target):
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return (lookup[target - num], i )
lookup[num] = i
print("index1=%d, index2=%d" %
py_solution().twoSum((10,20,10,40,50,60,70),50))
18. Write a Python class to find the three elements that sum to zero from a set
of n real numbers.
Input array : [-25, -10, -7, -3, 2, 4, 8, 10]
Output : [[-10, 2, 8], [-7, -3, 10]]
class py_solution:
def threeSum(self, nums):
nums, result, i = sorted(nums), [], 0
while i < len(nums) - 2:
j, k = i + 1, len(nums) - 1
while j < k:
if nums[i] + nums[j] + nums[k] < 0:
j += 1
elif nums[i] + nums[j] + nums[k] > 0:
k -= 1
else:
result.append([nums[i], nums[j], nums[k]])
j, k = j + 1, k - 1
while j < k and nums[j] == nums[j - 1]:
j += 1
while j < k and nums[k] == nums[k + 1]:
k -= 1
i += 1
while i < len(nums) - 2 and nums[i] == nums[i - 1]:
i += 1
return result
class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
print(py_solution().pow(2, -3))
print(py_solution().pow(3, 5))
print(py_solution().pow(100, 0))
20. Write a Python class to reverse a string word by word.
Input string : 'hello .py'
Expected Output : '.py hello'
class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
print(py_solution().reverse_words('hello .py'))
21. Write a Python class that has two methods: get_String and print_String ,
get_String accept a string from the user and print_String prints the string in upper
case.
class IOString():
def __init__(self):
self.str1 = ""
def get_String(self):
self.str1 = input()
def print_String(self):
print(self.str1.upper())
str1 = IOString()
str1.get_String()
str1.print_String()
22. Write a Python class named Rectangle constructed from length and width
and a method that will compute the area of a rectangle.
class Rectangle():
def __init__(self, l, w):
self.length = l
self.width = w
def rectangle_area(self):
return self.length*self.width
newRectangle = Rectangle(12, 10)
print(newRectangle.rectangle_area())
23. Write a Python class named Circle constructed from a radius and two
methods that will compute the area and the perimeter of a circle.
class Circle():
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14
NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())
24. Write a Python program to get the class name of an instance in Python.
import itertools
x = itertools.cycle('ABCD')
print(type(x).__name__)
1. Write a Python class Employee with attributes like emp_id, emp_name, emp_salary,
and emp_department and methods like calculate_emp_salary,
emp_assign_department, and print_employee_details.
Sample Employee Data:
"ADAMS", "E7876", 50000, "ACCOUNTING"
"JONES", "E7499", 45000, "RESEARCH"
"MARTIN", "E7900", 50000, "SALES"
"SMITH", "E7698", 55000, "OPERATIONS"
def print_employee_details(self):
print("\nName: ", self.name)
print("ID: ", self.id)
print("Salary: ", self.salary)
print("Department: ", self.department)
print("----------------------")
class Restaurant:
def __init__(self):
self.menu_items = {}
self.book_table = []
self.customer_orders = []
def print_menu_items(self):
for item, price in self.menu_items.items():
print("{}: {}".format(item, price))
def print_table_reservations(self):
for table in self.book_table:
print("Table {}".format(table))
def print_customer_orders(self):
for order in self.customer_orders:
print("Table {}: {}".format(order['table_number'],
order['order']))
restaurant = Restaurant()
# Add items
restaurant.add_item_to_menu("Cheeseburger", 9.99)
restaurant.add_item_to_menu("Caesar Salad", 8)
restaurant.add_item_to_menu("Grilled Salmon", 19.99)
restaurant.add_item_to_menu("French Fries", 3.99)
restaurant.add_item_to_menu("Fish & Chips:", 15)
# Book table
restaurant.book_tables(1)
restaurant.book_tables(2)
restaurant.book_tables(3)
# Order items
restaurant.customer_order(1, "Cheeseburger")
restaurant.customer_order(1, "Grilled Salmon")
restaurant.customer_order(2, "Fish & Chips")
restaurant.customer_order(2, "Grilled Salmon")
def print_customer_details(self):
print("Name:", self.customer_name)
print("Account Number:", self.account_number)
print("Date of opening:", self.date_of_opening)
print(f"Balance: ${self.balance}\n")
print("Customer Details:")
ac_no_1.print_customer_details()
ac_no_2.print_customer_details()
ac_no_3.print_customer_details()
ac_no_4.print_customer_details()
ac_no_5.print_customer_details()
print("=============================")
ac_no_4.print_customer_details()
# Current balance is $3000.
# $1000 has been deposited in your account.
ac_no_4.deposit(1000)
ac_no_4.check_balance()
# Your current balance $4000.
# You want to withdraw $5000
ac_no_4.withdraw(5000)
# Output:
# Insufficient balance.
#The customer withdraw $3400.
ac_no_4.withdraw(3400)
ac_no_4.check_balance()
4. Write a Python class Inventory with attributes like item_id, item_name, stock_count,
and price, and methods like add_item, update_item, and check_item_details.
Use a dictionary to store the item details, where the key is the item_id and the value is a
dictionary containing the item_name, stock_count, and price.
class Inventory:
def __init__(self):
self.inventory = {}
def add_item(self, item_id, item_name, stock_count, price):
self.inventory[item_id] = {"item_name": item_name, "stock_count":
stock_count, "price": price}
inventory = Inventory()