CST445 Python Exam Question Paper
CST445 Python Exam Question Paper
To create a histogram using matplotlib in Python, follow these steps: import the 'pyplot' module from 'matplotlib', prepare the data, and use the 'hist()' function of 'pyplot'. The 'hist()' function requires the data to be passed as an argument, and additional parameters such as 'bins' can be configured to specify the number of bins. For instance: ``` import matplotlib.pyplot as plt data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5] plt.hist(data, bins=5) plt.xlabel('Value') plt.ylabel('Frequency') plt.title('Histogram of Data') plt.show() ``` This code will create and display a histogram of the data with 5 bins .
Numpy arrays provide several advantages over traditional Python lists for numerical computations. First, they offer enhanced performance; operations over NumPy arrays are executed in C, allowing for faster code execution. Second, they provide better memory efficiency due to their homogeneous nature, storing items of the same data type. Third, NumPy arrays support element-wise operations, advanced slicing, and indexing, enabling complex mathematical operations to be performed with concise syntax. For instance, multiplying each element in an array by 2 is straightforward with NumPy: `array * 2`. Additionally, many scientific computing libraries, such as SciPy, are designed to work efficiently with NumPy arrays, further enhancing their utility .
Inheritance in Python allows one class (the child class) to inherit the attributes and methods of another class (the parent class), enabling code reuse and the creation of hierarchical class structures. Python supports multiple forms of inheritance: single inheritance (a child class inherits from one parent class), multiple inheritance (a child class inherits from more than one parent class), multilevel inheritance (a chain of inheritance where a class is derived from a class which is also derived from another class), and hierarchical inheritance (multiple child classes inherit from a single parent class). These are implemented using class definitions in Python, where a class is defined with another class as its base: `class Child(Parent):` .
Python provides several list methods for element manipulation. 'append()' adds a single element to the end of a list, altering the list in place. 'extend()' takes an iterable argument and appends each of its elements to the list, thus extending it. 'insert()' requires two arguments: an index and an element to insert at that specific index. These methods differ in their scope and flexibility: while 'append()' is used for single additions, 'extend()' is suitable for concatenating multiple elements, and 'insert()' provides control over the exact insertion point within the list, which may affect list performance for large datasets due to element shifting .
Numpy allows arithmetic operations to be applied element-wise across arrays, facilitating efficient computations. For example, consider creating two numpy arrays and performing addition: ``` import numpy as np array1 = np.array([1, 2, 3]) array2 = np.array([4, 5, 6]) result = array1 + array2 print(result) # Output: [5 7 9] ``` Each corresponding element of 'array1' and 'array2' is added together to produce 'result', demonstrating the straightforward syntax for vectorized operations in numpy .
File modes in Python specify the operations permitted on a file when it is opened. The read ('r') mode allows reading of a file's contents; it is the default mode when a file is opened and does not permit writing to the file. The write ('w') mode allows writing to a file and creates the file if it does not exist. If the file exists, 'w' mode truncates the file, erasing its content before writing new data. For example, opening a file in write mode: `with open('file.txt', 'w') as file: file.write('Hello, World!')`, writes 'Hello, World!' to 'file.txt', discarding any existing content .
Lambda functions are often used in Python for operations within lists, such as sorting, filtering, or mapping. For instance, to sort a list of tuples by the second element in each tuple, a lambda function can be used with 'sorted': ``` list_of_tuples = [(1, 3), (2, 2), (3, 1)] sorted_list = sorted(list_of_tuples, key=lambda x: x[1]) print(sorted_list) # Output: [(3, 1), (2, 2), (1, 3)] ``` The lambda function lambda x: x[1] specifies that the second element of each tuple x should be used for sorting .
The 'try except' block in Python is used to handle exceptions or runtime errors. The 'try' block contains code that might raise an exception, while the 'except' block contains code that executes if an exception occurs. This structure allows a program to continue running even when an error is encountered, preventing crashes. An example is: ``` try: division = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") ``` Here, if a ZeroDivisionError occurs, the except block is executed, printing "Cannot divide by zero" instead of terminating the program .
Python supports several forms of inheritance, which include: single inheritance, where a derived class inherits from only one base class; multiple inheritance, where a derived class can inherit from multiple base classes, leading to more complex class hierarchies; multilevel inheritance, where a derived class is a subclass of another derived class, creating a parent-child-grandchild relationship; and hierarchical inheritance, where one base class is inherited by multiple derived classes. These forms allow flexible class designs but also introduce potential complexities, such as the diamond problem in multiple inheritance, which can be managed using Python’s Method Resolution Order (MRO) and the super() function to control the inheritance chain .
Lambda functions in Python are used to create small, anonymous functions at runtime. They are defined using the lambda keyword, have no name, and can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions are commonly used for situations where a simple function is needed for a short period, typically as an argument to higher-order functions (functions that take other functions as arguments). For example, in sorting a list of tuples based on the second element, a lambda function can be used: sorted(list_of_tuples, key=lambda x: x[1]).