Python Solve CAT2
Python Solve CAT2
Binary search and linear search are two common algorithms used to search for an
element in an array. The main difference between them is the way they search for the
element.
Linear Search:
In linear search, each element of the array is checked one by one un l the target
element is found. It is a simple and straigh orward algorithm but it can be slow for
large arrays.
Binary Search:
In binary search, the array is first sorted and then the middle element is selected. If
the middle element is not equal to the target, then the search is con nued either in
the le or right half of the array. This process is repeated un l the target element is
found or the en re array has been searched.
In both of the above examples, `arr` is the array to be searched, and `target` is the
element to be searched for. The func on returns the index of the element if it is found,
and -1 if it is not found.
HARSHIT MCA 9
2. Write a program for crea ng an integer array with values belonging to
the range 10 and 60.
Sure, here's an example Python program to create an integer array with values
between 10 and 60:
import numpy as np
# print array
print(arr)
This program uses the `arange` func on from NumPy to create an array with values
between 10 and 60 (inclusive). The `arr` variable holds the resul ng array, which is
printed to the console using the `print` func on.
In the above example, we are crea ng a file named "example.txt" in write mode,
wri ng some text to it and then closing the file.
Dele on of a file can be done using the `os` module in Python. The `os` module
provides a func on called `remove()` which takes the filename as a parameter and
deletes it.
import os
os.remove("example.txt")
In the above example, we are impor ng the `os` module and using the `remove()`
func on to delete the file named "example.txt".
HARSHIT MCA 9
4. Explain are the various features of NumPy.
Overall, NumPy is a very useful library for scien fic compu ng, data analysis, and
machine learning in Python.
NumPy is a library for the Python programming language, adding support for large,
mul -dimensional arrays and matrices, along with a large collec on of high-level
mathema cal func ons to operate on these arrays. NumPy is a fundamental package
for scien fic compu ng in Python.
HARSHIT MCA 9
6. Integra on with other scien fic compu ng libraries, such as Pandas, SciPy, and
Matplotlib.
Overall, NumPy is widely used in scien fic compu ng, data analysis, machine learning,
and other fields that involve numerical computa ons with large amounts of data.
To construct a line in a diagram from posi on (0,0) to (6,250) using matplotlib, you can
use the following code:
This code imports the `matplotlib.pyplot` module, creates `x` and `y` arrays to
represent the points of the line, plots the line using the `plt.plot()` func on, and adds
labels and a tle to the plot using `plt.xlabel()`, `plt.ylabel()`, and `plt. tle()`. Finally, it
displays the plot using `plt.show()`.
HARSHIT MCA 9
7. Explain Crea on and Dele on of files with proper example.
Crea on of file:
To create a new file in Python, you can use the built-in `open()` func on with the "w"
(write) mode, which creates a new file if it doesn't exist and overwrites the file if it
already exists.
In this code, we create a new file named "example.txt" and write the string "This is an
example file created using Python!" into it using the `write()` method. Finally, we close
the file using the `close()` method.
Dele on of file:
To delete a file in Python, you can use the built-in `os.remove()` func on.
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted successfully!")
else:
print("The file does not exist.")
In this code, we first check if the file "example.txt" exists using the `os.path.exists()`
method. If the file exists, we delete it using the `os.remove()` method and print a
message indica ng that the file was deleted successfully. If the file does not exist, we
print a message indica ng that the file does not exist.
HARSHIT MCA 9
8. Describe the ways of crea ng 1D, 2D and 3D arrays in NumPy with
proper example.
In NumPy, arrays can be created in various dimensions. The following are the ways of
crea ng 1D, 2D and 3D arrays in NumPy:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
2. 2D Array: A 2D array is like a table with rows and columns. It can be created using
the `numpy.array()` func on and passing a list of lists as an argument. Each list inside
the main list represents a row. For example:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr)
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr)
Output:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
HARSHIT MCA 9
9. Dis nguish between different file modes. Explain each with the help of
an example.
In Python, files can be opened in different modes depending on what opera on needs
to be performed on the file. The following are the different file modes available in
Python:
1. "r": This mode is used for reading files. If the file does not exist, it will give an error.
Example: To read a file named "file.txt" and print its contents:
2. "w": This mode is used for wri ng to files. If the file does not exist, it will be created.
If it does exist, it will be overwri en.
Example: To write to a file named "file.txt":
3. "a": This mode is used for appending to files. If the file does not exist, it will be
created. If it does exist, data will be appended to the end of the file.
Example: To append to a file named "file.txt":
4. "x": This mode is used for crea ng a new file. If the file already exists, it will give an
error.
Example: To create a new file named "file.txt":
5. "b": This mode is used to open a file in binary mode. This is typically used for reading
and wri ng non-text files such as images or audio files.
Example: To read a binary file named "image.jpg":
file = open("image.jpg", "rb")
data = file.read()
HARSHIT MCA 9
file.close()
6. "t": This mode is used to open a file in text mode. This is typically used for reading
and wri ng text files.
Example: To read a text file named "file.txt":
file = open("file.txt", "rt")
data = file.read()
file.close()
In this code, we first define a func on `det` to find the determinant of a matrix. We
check the size of the matrix, and if it's a 1x1 matrix, we simply return the value of the
HARSHIT MCA 9
only element. If it's a 2x2 matrix, we apply the formula for finding the determinant of
a 2x2 matrix. For larger matrices, we use a recursive approach where we calculate the
determinant of a submatrix by calling the `det` func on recursively. We then use this
sub-determinant to calculate the determinant of the current matrix. Finally, we return
the determinant of the matrix.
We then take the matrix as input from the user using the `input` func on, and convert
the input into a 2D list. We pass this matrix to the `det` func on to find the
determinant, and print the result.
To create a NumPy array filled with all zeros, you can use the `zeros` func on from the
NumPy library. Here's an example code snippet:
import numpy as np
In the above code, `np.zeros` func on is used to create a NumPy array filled with zeros.
The argument to the func on specifies the shape of the array. The first example creates
a 1D array of length 5, the second example creates a 2D array with 3 rows and 4
columns, and the third example creates a 3D array with 2 blocks, 3 rows, and 4
columns.
Matplotlib is a plo ng library for the Python programming language and can be used
to create a wide variety of plots. Some of the plots that can be created using Matplotlib
include:
1. Line plots
2. Sca er plots
HARSHIT MCA 9
3. Bar plots
4. Histograms
5. Pie charts
6. Box plots
7. Heatmaps
8. Contour plots
9. 3D plots
10. Polar plots
11. Subplots
Line plots, sca er plots, bar plots, histograms, and pie charts are some of the most
commonly used types of plots in data analysis and visualiza on.
To create these plots using Matplotlib, you can use the `plot()`, `sca er()`, `bar()`,
`hist()`, and `pie()` func ons, respec vely. For example, to create a line plot, you can
use the following code:
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt. tle('Line Plot')
plt.show()
This code creates a line plot with x-values `[1, 2, 3, 4, 5]` and y-values `[2, 4, 6, 8, 10]`.
The `xlabel()`, `ylabel()`, and ` tle()` func ons are used to add labels to the x-axis, y-
axis, and tle of the plot, respec vely. The `show()` func on is used to display the plot.
Pandas is a data analysis library for Python that provides various data structures and
func ons for working with structured data, primarily in the form of data frames. The
Series func on in Pandas is used to create a one-dimensional labeled array capable of
holding data of any type.
HARSHIT MCA 9
- Data Manipula on: Pandas provides several ways to manipulate data, such as
filtering, sor ng, merging, and grouping. These opera ons are essen al to prepare
data for analysis.
- Data Analysis: Pandas provides various sta s cal func ons that can be used to
perform data analysis, such as mean, median, mode, standard devia on, and
correla on.
- Data Visualiza on: Pandas integrates well with Matplotlib, a data visualiza on
library. It allows for easy visualiza on of data using various graphs and charts.
The Series func on is useful when working with data that has a single column or when
you want to extract a single column from a larger data frame. It provides various
methods for manipula ng and analyzing data, such as sor ng, filtering, and
aggrega on. It also allows for easy labeling and indexing of the data.
To make a Pandas DataFrame with a two-dimensional list in Python, you can use the
`pd.DataFrame()` constructor. Here's an example code snippet:
import pandas as pd
print(df)
In this example, we first create a two-dimensional list called `data` with three rows and
three columns. Then, we pass this list to the `pd.DataFrame()` constructor, along with
a list of column names. The constructor creates a new DataFrame object and assigns
it to the variable `df`. Finally, we print the contents of the DataFrame using the `print()`
func on.
HARSHIT MCA 9
15.List the three modes in which, file can be opened in python.
In Python, a file can be opened in one of three modes: read mode (default), write
mode, or append mode.
- Read mode: The 'r' mode is used to open a file in read mode. It allows you to read
the file but not modify it. For example, if you want to read the contents of a text file,
you can use read mode.
Example:
# open the file in read mode
file = open('example.txt', 'r')
- Write mode: The 'w' mode is used to open a file in write mode. It allows you to write
to the file and overwrite its exis ng contents. If the file does not exist, it will be created.
Example:
# open the file in write mode
file = open('example.txt', 'w')
- Append mode: The 'a' mode is used to open a file in append mode. It allows you to
add new data to the end of the file without overwri ng the exis ng data. If the file
does not exist, it will be created.
Example:
# open the file in append mode
file = open('example.txt', 'a')
HARSHIT MCA 9
16.Create and display a one-dimensional array-like object using Pandas in
Python
To create a one-dimensional array-like object using Pandas in Python, we can use the
`Series` func on. Here's an example:
import pandas as pd
Output:
0 3
1 7
2 2
3 1
4 9
dtype: int64
In this example, we first create a list of data. Then we use the `pd.Series()` func on to
create a Pandas Series object. Finally, we print the Series object to the console.
In Scipy, constants are pre-defined mathema cal constants that can be used in various
scien fic calcula ons and simula ons. The scipy.constants module provides many
important physical constants such as the speed of light, the gravita onal constant, the
Planck constant, etc. These constants are useful in various scien fic and engineering
applica ons.
Here is an example of using the Scipy constants module to calculate the gravita onal
force between two objects:
import scipy.constants as const
HARSHIT MCA 9
# Define the distance between the objects in meters
r = 2.0
In this example, we import the Scipy constants module and use the gravita onal
constant `const.G` to calculate the gravita onal force between two objects with
masses `m1` and `m2` separated by a distance `r`.
import numpy as np
from scipy.interpolate import interp1d
Output:
[2.5 4. 6.5 9. ]
HARSHIT MCA 9
In this example, we first create some sample data for x and y. We then create a func on
object `f` that can perform linear interpola on on the data. We evaluate the func on
`f` at some new points `new_x` and store the results in `new_y`. Finally, we print the
new y values.
The OS path module in Python provides func ons for working with file paths and
directories. It includes various methods to interact with file paths like joining and
spli ng file paths, ge ng the directory name and file name from the path, and
checking whether a given path exists or not.
import os
# create a directory
new_dir = "test_dir"
if not os.path.exists(new_dir):
os.mkdir(new_dir)
print(f"Directory {new_dir} created successfully!")
HARSHIT MCA 9
else:
print(f"{file_path} does not exist!")
# remove directory
os.rmdir(new_dir)
print(f"Directory {new_dir} removed successfully!")
In this example, we have imported the OS path module and used various func ons to
work with file paths and directories. We have first obtained the current directory using
the `os.getcwd()` func on. Then, we have created a new directory using the
`os.mkdir()` func on, but only if it does not already exist. We have used the
`os.path.join()` func on to join two paths, and the `os.path.basename()` and
`os.path.dirname()` func ons to get the file name and directory name from a given
path. We have also checked whether a file exists using the `os.path.exists()` func on.
Finally, we have removed the directory using the `os.rmdir()` func on.
The `shelve` module in Python is used for storing and retrieving objects from a
persistent storage space. It is similar to a dic onary object in Python, but instead of
storing data in memory, it allows you to store data on disk. The `shelve` module
provides an easy way to store, retrieve, and update data in a persistent manner.
import shelve
In this example, we create a new shelf object by calling the `shelve.open()` func on
and passing it a filename. We then store some data in the shelf using dic onary-like
syntax, and finally close the shelf object.
To retrieve data from the shelf, we can open the shelf again and access the data by
key:
HARSHIT MCA 9
import shelve
In this example, we open the shelf again by calling `shelve.open()` with the same
filename, and then retrieve the data we stored earlier using dic onary-like syntax.
Finally, we close the shelf object again.
The `shelve` module can be a useful tool for storing data that you want to persist across
mul ple program execu ons. However, it should be noted that the `shelve` module
has some limita ons, such as not being thread-safe and not allowing mul ple
processes to access the same shelf simultaneously. If you need more advanced
features, you may want to consider using a more robust database system.
HARSHIT MCA 9