0% found this document useful (0 votes)
44 views

Python Solve CAT2

The document discusses linear and binary search algorithms. Linear search checks each element of an array sequentially until the target is found, while binary search first sorts the array and then checks the middle element, narrowing the search space with each iteration until the target is found or the entire array has been searched. Examples of linear and binary search functions in Python are provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Python Solve CAT2

The document discusses linear and binary search algorithms. Linear search checks each element of an array sequentially until the target is found, while binary search first sorts the array and then checks the middle element, narrowing the search space with each iteration until the target is found or the entire array has been searched. Examples of linear and binary search functions in Python are provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1. Describe the Binary and Linear search with Example.

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.

Here is an example of a linear search func on in Python:

def linear_search(arr, target):


for i in range(len(arr)):
if arr[i] == target:
return i
return -1

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.

Here is an example of a binary search func on in Python:

def binary_search(arr, target):


low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

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

# create array with values between 10 and 60


arr = np.arange(10, 61)

# 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.

3. Explain Crea on and Dele on of files with proper example.


Crea ng a file in Python can be done using the built-in `open()` func on. It requires a
filename as a parameter and also a mode in which the file should be opened. The
mode can be `r` for reading, `w` for wri ng, or `a` for appending.

Example of crea ng a file:

file = open("example.txt", "w")


file.write("This is an example file.")
file.close()

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.

Example of dele ng a file:

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.

NumPy is a powerful numerical compu ng library for Python. It provides a


mul dimensional array object, various derived objects such as masked arrays and
matrices, and an extensive range of rou nes for fast opera ons on arrays, including
mathema cal, logical, shape manipula on, sor ng, selec ng, I/O, discrete Fourier
transforms, basic linear algebra, basic sta s cal opera ons, random simula on, and
much more.

Some of the main features of NumPy are:


- Mul dimensional arrays: NumPy provides an efficient way to work with arrays of any
dimensionality.
- Broadcas ng: NumPy can broadcast opera ons on arrays of different shapes and
sizes.
- Vectorized opera ons: NumPy allows vectorized opera ons on arrays, which means
that you can apply a func on to every element of an array without wri ng any loops.
- Indexing and slicing: NumPy allows indexing and slicing of arrays in many different
ways, including Boolean indexing and fancy indexing.
- Fast opera ons: NumPy is designed for fast opera ons on arrays, and many of its
opera ons are implemented in C or Fortran to ensure maximum speed.

Overall, NumPy is a very useful library for scien fic compu ng, data analysis, and
machine learning in Python.

5. List the uses of NumPy.

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.

Some of the main uses of NumPy are:

1. Mathema cal opera ons on arrays, such as trigonometric, logarithmic, and


exponen al func ons.
2. Manipula on of arrays and matrices, such as transposing, reshaping, and
concatena ng arrays.
3. Mathema cal opera ons between arrays, such as dot products and element-wise
opera ons.
4. Linear algebra opera ons, such as compu ng eigenvalues and eigenvectors of a
matrix, and solving linear systems of equa ons.
5. Random number genera on using NumPy's random module.

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.

6. Construct a line in a diagram from posi on (0,0) to (6,250) using


matplotlib.

To construct a line in a diagram from posi on (0,0) to (6,250) using matplotlib, you can
use the following code:

import matplotlib.pyplot as plt

# create x and y arrays


x = [0, 6]
y = [0, 250]

# plot the line


plt.plot(x, y)

# add labels and tle


plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt. tle('Line Plot')

# show the plot


plt.show()

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.

Here's an example code:

file = open("example.txt", "w")


file.write("This is an example file created using Python!")
file.close()

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.

Here's an example code:

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:

1. 1D Array: A 1D array is a simple list of values. It can be created using the


`numpy.array()` func on and passing a list of values as an argument. For example:

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]]

3. 3D Array: A 3D array is like a stack of 2D arrays. It can be created using the


`numpy.array()` func on and passing a list of 2D arrays as an argument. For example:

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:

file = open("file.txt", "r")


print(file.read())
file.close()

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":

file = open("file.txt", "w")


file.write("Hello, world!")
file.close()

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":

file = open("file.txt", "a")


file.write("Hello, again!")
file.close()

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":

file = open("file.txt", "x")


file.write("This is a new file!")
file.close()

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()

10.Develop a python code to find determinant of matrix (take matrix as user


input).

Here's a Python code to find the determinant of a matrix:

# define a func on to find the determinant of a matrix


def det(matrix):
size = len(matrix)
if size == 1:
return matrix[0][0]
elif size == 2:
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
else:
determinant = 0
for col in range(size):
sub_matrix = [row[:col]+row[col+1:] for row in matrix[1:]]
sub_determinant = det(sub_matrix)
sign = (-1)**col
determinant += sign*matrix[0][col]*sub_determinant
return determinant

# take matrix as input from user


n = int(input("Enter the size of the matrix: "))
matrix = []
for i in range(n):
row = list(map(int, input(f"Enter row {i+1}: ").split()))
matrix.append(row)

# calculate determinant and print the result


d = det(matrix)
print("The determinant of the matrix is:", d)

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.

11. Create a Numpy array filled with all zeros | Python

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

# Create a 1D array filled with zeros


arr1 = np.zeros(5)
print(arr1)

# Create a 2D array filled with zeros


arr2 = np.zeros((3, 4))
print(arr2)

# Create a 3D array filled with zeros


arr3 = np.zeros((2, 3, 4))
print(arr3)

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.

12.Iden fy various plots which can be created using python matplotlib.

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:

import matplotlib.pyplot as plt

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.

13.Discuss the applica ons of Pandas and Series func on.

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.

The applica ons of Pandas and Series func on are:


- Data Cleaning: Pandas provides various func ons and methods to clean and
preprocess the data before analysis. For example, removing duplicates, handling
missing values, and handling inconsistent data.

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.

14.Make a Pandas DataFrame with two-dimensional list.

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

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # two-dimensional list

df = pd.DataFrame(data, columns=['col1', 'col2', 'col3'])

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.

The output of this code will be:

col1 col2 col3


0 1 2 3
1 4 5 6
2 7 8 9
As you can see, the DataFrame has three columns named 'col1', 'col2', and 'col3', and
three rows with the values from the `data` list.

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')

# read the contents of the file


content = file.read()

# print the contents


print(content)

# close the file


file.close()

- 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')

# write to the file


file.write('This is some text that will be wri en to the file')

# close the file


file.close()

- 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')

# write to the file


file.write('\nThis is some new text that will be added to the end of the file')

# close the file


file.close()

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

# Create a list of data


data = [3, 7, 2, 1, 9]

# Create a Series object


s = pd.Series(data)

# Print the Series object


print(s)

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.

17.Explain constants in Scipy, with the help of a program.

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

# Define the mass of the objects in kilograms


m1 = 5.0
m2 = 10.0

HARSHIT MCA 9
# Define the distance between the objects in meters
r = 2.0

# Calculate the gravita onal force between the objects


force = const.G * m1 * m2 / r**2

print("Gravita onal force between the objects:", force, "N")

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`.

18.Illustrate the use of interpola on? implement it in Scipy, with example.

Interpola on is a technique of es ma ng the value of a func on for any intermediate


value of the independent variable. It is a method of construc ng new data points from
the exis ng data points. In SciPy, interpola on can be performed using the `interp1d`
func on.

Here's an example of how to use `interp1d` func on:

import numpy as np
from scipy.interpolate import interp1d

# Create some sample data


x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 8, 10])

# Create a func on object to perform linear interpola on


f = interp1d(x, y)

# Evaluate the func on at some new points


new_x = np.array([1.5, 2.5, 3.5, 4.5])
new_y = f(new_x)

# Print the new values


print(new_y)

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.

19.Summarize the OS path module in detail, with example.

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.

Here's an example of how to use the OS path module:

import os

# get current directory


current_dir = os.getcwd()
print("Current Directory:", current_dir)

# 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!")

# join two paths


path1 = "/home/user"
path2 = "Documents"
doc_path = os.path.join(path1, path2)
print("Document Path:", doc_path)

# get file name and directory name from path


file_path = "/home/user/Documents/sample.txt"
file_name = os.path.basename(file_path)
dir_name = os.path.dirname(file_path)
print("File Name:", file_name)
print("Directory Name:", dir_name)

# check if file exists


if os.path.exists(file_path):
print(f"{file_path} exists!")

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.

20.Determine the shelve module in detail, with example.

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.

Here's an example of how to use the `shelve` module to store data:

import shelve

# create a new shelf object


shelf = shelve.open("my_data")

# store some data


shelf["key1"] = "value1"
shelf["key2"] = [1, 2, 3, 4]

# close the shelf object


shelf.close()

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

# open the shelf


shelf = shelve.open("my_data")

# retrieve some data


value1 = shelf["key1"]
value2 = shelf["key2"]

# close the shelf object


shelf.close()

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

You might also like