Bipin Python Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

PROGRAM – 01

 Write a program to find the roots of quadratic


equation
# import complex math module

import cmath
a=3
b = 12
c = 24
# calculate the discriminant
d = (b**2) - (4*a*c)

# find two solutions

sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

Output:

The solution are (-2-2j) and (-2+2j)


PROGRAM – 02

 Write a program to find and delete repeating


number in Given List

# Python code to remove duplicate elements

def Remove(duplicate):

final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list

# Driver Code
duplicate = [218, 412, 218, 116, 910, 412, 412, 218]
print(Remove(duplicate))

Output :
[218, 412, 116, 910]
PROGRAM – 03

 Write a program to input and print the elements sum


of user defined matrix.

X = [[8,8,6],
[4,9,12],
[6,8,18]]

Y = [[16,2,10],
[2,4,12],
[6,1,18]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)

Output:
PROGRAM – 04

 Program to multiply two matrices using list


comprehension.
A = [[16, 10, 2],
[18, 24, 3],
[16, 22, 6]]

B = [[10, 8, 7, 6],

[12, 20, 6, 8],


[8, 0, 7, 2]]
# result will be 3x4
result = [[sum(a * b for a, b in zip(A_row, B_col))
for B_col in zip(*B)]

for A_row in A]
for r in result:
print(r)

OUTPUT:
PROGRAM – 05

 Write a program to compute eigen value and vectorof a


given 3*3 matrix using NumPy.
import numpy as np
m = np.array([[12,16,14],
[0,6,12],
[24,4,2]])
print("Printing the Original square array:\n",m)
# finding eigenvalues and eigenvectors
w, v = np.linalg.eig(m)
# printing eigen values
print("Printing the Eigen values of the given square array:\n",w)
# printing eigen vectors
print("Printing Right eigenvectors of the given square array:\n",v)

OUTPUT:
PROGRAM – 06
 Write a program to find a solution of linear equations
in y‐mx+c.

Code 1: Import all the necessary Libraries.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error,
r2_score
import statsmodels.api as sm
Code 2: Generate the data. Calculate xmean, ymean, Sxx, Sxy to find the value of slope and
intercept of regression line.

x = np.array([5, 6, 7, 8, 9])
y = np.array([6, 13, 14, 17, 18])
n = np.size(x)

x_mean = np.mean(x)
y_mean = np.mean(y)
x_mean, y_mean

Sxy = np.sum(x * y) - n * x_mean * y_mean


Sxx = np.sum(x * x) - n * x_mean * x_mean

b1 = Sxy / Sxx
b0 = y_mean - b1 * x_mean
print('slope b1 is', b1)
print('intercept b0 is', b0)

plt.scatter(x, y)
plt.xlabel('Independent variable X')
plt.ylabel('Dependent variable y')

Code 3: Plot the given data points and fit the regression line.

y_pred = b1 * x + b0
plt.scatter(x, y, color='red')
plt.plot(x, y_pred, color='green')
plt.xlabel('X')
plt.ylabel('y')

plt.show()

OUTPUT:
PROGRAM – 07
 Write the program to determine the intersection
point of two line

class Point:

def __init__(self, x, y):


self.x = x
self.y = y

def displayPoint(self, p):

print(f"({p.x}, {p.y})")

def lineLineIntersection(A, B, C, D):


# Line AB represented as a1x + b1y = c1

a1 = B.y - A.y
b1 = A.x - B.x
c1 = a1 * (A.x) + b1 * (A.y)
# Line CD represented as a2x + b2y = c2
a2 = D.y - C.y

b2 = C.x - D.x
c2 = a2 * (C.x) + b2 * (C.y)

determinant = a1 * b2 - a2 * b1

if (determinant == 0):
return Point(10**9, 10**9)
else:
x = (b2 * c1 - b1 * c2) / determinant
y = (a1 * c2 - a2 * c1) / determinant

return Point(x, y)

A = Point(2, 4)
B = Point(6, 8)
C = Point(7, 9)

D = Point(8, 5)
intersection = lineLineIntersection(A, B, C, D)
if (intersection.x == 10**9 and intersection.y == 10**9):
print("The given lines AB and CD are parallel.")
else:

print("The intersection of the given lines AB and CD is: ")


intersection.displayPoint(intersection)

OUTPUT:
PROGRAM – 08
 Draw various types of charts using matplotlib

import matplotlib.pyplot as plt


x = [9,10,11]
y = [5,4,3]
plt.plot(x, y)
plt.xlabel('x - axis')

plt.ylabel('y - axis')
plt.title('My first graph!')
plt.show()

OUTPUT:
PROGRAM – 09
 Write a Program to plot two lines in same graph.
import matplotlib.pyplot as plt
x1 = [8,5,3]
y1 = [1,8,9]
x2 = [1,2,8]
y2 = [4,5,3]

plt.plot(x1, y1, label = "line 1")


plt.plot(x2, y2, label = "line 2")
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Two lines on same graph!')

plt.legend()
plt.show()

OUTPUT:
PROGRAM – 10
Write a Program to plot Some customization in same
graph.
import matplotlib.pyplot as plt
x = [6,7,8,5,4,3]

y = [1,2,3,4,5,6]
plt.plot(x, y, color='pink', linestyle='dashed', linewidth = 2, marker='o',
markerfacecolor='orange', markersize=12)
plt.ylim(1,8)
plt.xlim(1,8)
plt.xlabel('x - axis')
plt.ylabel('y - axis')

plt.title('Some cool customizations!')


plt.show()

OUTPUT:
PROGRAM – 11
 Write a program to plot bar graph in ascending order
from low to high with numbering in letter.
import matplotlib.pyplot as plt
left = [4, 2, 1, 9, 5] # x-coordinates of left sides of bars

height = [15, 25, 40, 45, 5] # heights of bars


tick_label = ['one', 'two', 'three', 'four', 'five'] # labels for bars
plt.bar(left, height, tick_label = tick_label, width = 0.8, color = ['red', 'green'])
plt.xlabel('x - axis') # naming the x-axis
plt.ylabel('y - axis') # naming the y-axis

plt.title('My bar chart!')


plt.show()

OUTPUT:
PROGRAM – 12
 Write a program to plot a histogram graph.
import matplotlib.pyplot as plt

ages = [12,50,79,41,35,45,50,48,43,40,44,60,7,12,57,18,90,77,80,21,90,40]
range = (0, 100) # setting the ranges and no. of intervals
bins = 10
plt.hist(ages, bins, range, color = 'green', histtype = 'bar', rwidth = 0.8)
plt.xlabel('age') # x-axis label

plt.ylabel('No. of people') # frequency label


plt.title('My histogram')
plt.show()

OUTPUT:
PROGRAM – 13
 Write a program to plot points as a scatter plot.
import matplotlib.pyplot as plt

x = [10,9,8,7,6,5,4,3,2,1] # x-axis values


y = [5,6,7,3,2,10,8,9,4,6] # y-axis values
plt.scatter(x, y, label= "stars", color= "brown",marker= "*", s=20)
plt.xlabel('x - axis') # x-axis label
plt.ylabel('y - axis') # frequency label

plt.title('My scatter plot!')


plt.legend()
plt.show()

OUTPUT:
PROGRAM – 14
 Write a program to plot a pie chart of a given data.
import matplotlib.pyplot as plt
activities = ['study', 'sleep', 'eat', 'play']
slices = [1, 2,4, 4] # portion covered by each label
colors = ['r', 'y', 'g', 'b'] # color for each label
plt.pie(slices, labels = activities, colors=colors, startangle=90, shadow = True, explode = (0,
0, 0.1,0),radius = 1.5, autopct = '%1.1f%%')
plt.legend()
plt.show()

OUTPUT:
PROGRAM – 15
 Write a program to plot the function to show plotting
curves of given equation.
import matplotlib.pyplot as plt
import numpy as np

# setting the x - coordinates


x = np.arange(0, 2*(np.pi), 0.2)
# setting the corresponding y - coordinates
y = np.sin(x)
# plotting the points

plt.plot(x, y)
# function to SHOW Plotting curves of given equation
plt.show()

OUTPUT:
PROGRAM – 16
 Write a program to represent a coordinate in
3Dsystem.
import matplotlib.pyplot as plt
from matplotlib import style

import numpy as np
style.use('ggplot') # setting a custom style to use
fig = plt.figure() # create a new figure for plotting
ax1 = fig.add_subplot(111, projection='3d') # create a new subplot on our figure and
set projection as 3d
x = np.random.randint(0, 20, size = 10) # defining x, y, z co-ordinates
y = np.random.randint(0, 20, size = 10)

z = np.random.randint(0, 20, size = 10)


ax1.set_xlabel('x-axis') # plotting the points on subplot and setting labels for the axes
ax1.set_ylabel('y-axis')
ax1.set_zlabel('z-axis')
plt.show()

OUTPUT:
PROGRAM – 17
 Write a program to represent the graph in 3d system.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot') # setting a custom style to use

fig = plt.figure() # create a new figure for plotting

ax1 = fig.add_subplot(111, projection='3d') # create a new subplot on our figure


x = [5,2,3,1,4,6,7,8,9,10] # defining x, y, z co-ordinates for bar position

y = [4,6,1,3,5,7,8,5,3,9]

z = np.zeros(10)
dx = np.ones(10) # size of bars
dy = np.ones(10) # length along x-axis
dz = [6,2,1,8,6,4,5,5,10,6] # length along y-axis
color = [] # setting color scheme

for h in dz:

if h > 5:

color.append('r')

else:
color.append('b')
ax1.bar3d(x, y, z, dx, dy, dz, color = color) # plotting the bars
ax1.set_xlabel('x-axis') # setting axes labels
ax1.set_ylabel('y-axis')
ax1.set_zlabel('z-axis')
plt.show()
OUTPUT:
PROGRAM – 18
 Write a program to perform equations of uniform motion of
kinematics:
#code we will find final velocity by using formula
“v = u + a*t”

initialVelocity = 40

acceleration = 9.8

time = 10

finalVelocity = initialVelocity + acceleration * time

print("Final velocity = ", finalVelocity)

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy