BME358A Py Pgs
BME358A Py Pgs
Words=("Hello","World")
print("1.len():",len(text))
print("2.strip():",text.strip())
print("3.rstrip():",text.rstrip())
print("4.lstrip():",text.lstrip())
print("5.find('World'):",text.find("World"))
print("6.rfind('World'):",text.rfind("World"))
try:
print("7.index('World'):",text.index("World"))
except valueError as e:
print("7.index('World'):Error",e)
try:
print("8.rindex('World'):",text.rindex("World"))
except valueError as e:
print("8.rindex('World'):Error",e)
print("9.count('World'):",text.count("World"))
print("10.replace('World','Python'):",text.replace("World","Python"))
print("11.split():",text.split())
print("13.upper():",text.upper())
print("14.lower():",text.lower())
print("15.swapcase():",text.swapcase())
print("16.title():",text.title())
print("17.capitalize():",text.capitalize())
print("18.startswith('Hello'):",text.startswith("Hello"))
print("19.endswith('World'):",text.endswith("World"))
print("12.join():","".join(Words))
1.len(): 17
2.strip(): Hello World World
3.rstrip(): Hello World World
4.lstrip(): Hello World World
5.find('World'): 6
6.rfind('World'): 12
7.index('World'): 6
8.rindex('World'): 12
9.count('World'): 2
10.replace('World','Python'): Hello Python Python
11.split(): ['Hello', 'World', 'World']
13.upper(): HELLO WORLD WORLD
14.lower(): hello world world
15.swapcase(): hELLO wORLD wORLD
16.title(): Hello World World
17.capitalize(): Hello world world
18.startswith('Hello'): True
19.endswith('World'): True
12.join(): HelloWorld
2 a)
def factorial(x):
if x == 1 or x == 0:
return 1
else:
return (x * factorial(x-1))
num = 7
result = factorial(num)
2 b)
final_list = []
for i in range(0, N):
max1 = 0
for j in range(len(list1)):
max1 = list1[j]
list1.remove(max1)
final_list.append(max1)
print(final_list)
N=2
Nmaxelements(list1, N)
[85, 41]
2 c)
def calculate_area(name):
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
rect_area = l * b
sqt_area = s * s
tri_area = 0.5 * b * h
pi = 3.14
circ_area = pi * r * r
para_area = b * h
else:
# driver cod
if __name__ == "__main__" :
shape_name = input("Enter the name of shape whose area you want to find: ")
# function calling
calculate_area(shape_name)
def input_matrix():
matrix = []
print("Enter the elements of 3x3 matrix row by row:")
for i in range(3):
row = list(map(int, input(f"Enter row {i+1}: ").split()))
matrix.append(row)
return matrix
def print_matrix(matrix):
for row in matrix:
print(row)
def transpose(matrix):
return [[matrix[j][i] for j in range(3)] for i in range(3)]
# Main program
print("Matrix 1:")
matrix1 = input_matrix()
print("\n\Matrix 2:")
print_matrix(matrix2)
# Matrix Addition
print("\nMatrix 1 + Matrix 2:")
print_matrix(matrix_addition(matrix1, matrix2))
# Matrix Subtraction
print("\nMatrix 1 - Matrix 2:")
print_matrix(matrix_subtraction(matrix1, matrix2))
# Matrix Multiplication
print("\nMatrix 1 * Matrix 2:")
print_matrix(matrix_multiplication(matrix1, matrix2))
Matrix 2:
Enter the elements of 3x3 matrix row by row:
Enter row 1: 1 2 3
Enter row 2: 4 5 6
Enter row 3: 7 8 9
Matrix 1:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
\Matrix 2:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transpose of Matrix 1:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Transpose of Matrix 2:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Matrix 1 + Matrix 2:
[2, 4, 6]
[8, 10, 12]
[14, 16, 18]
Matrix 1 - Matrix 2:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Matrix 1 * Matrix 2:
[30, 36, 42]
[66, 81, 96]
[102, 126, 150]
PROGRAM 4
def reverse_string(s):
return s[::-1]
def replace_characters(s,old_string,new_string):
return s.replace(old_string,new_string)
def isPalindrome(s):
return s==s[::-1]
reverse_str=reverse_string(input_string)
replaced_string=replace_characters(input_string,old_string,new_string)
s="malayalam"
ans=isPalindrome(s)
if ans:
print(s,"its a palindrome:")
else:
print("input string:",input_string)
character_count=len(input_string)
-------------------output-----------------------------------
number of characters: 7
PROGRAM 5
def printAP(a,d,n):
curr_term=a
for i in range(1,n+1):
print(curr_term,end=' ')
curr_term=curr_term+d
a=2
d=3
n=10
printAP(a,d,n)
print()
def printGP(a,r,n):
for i in range(0,n):
curr_term=a*pow(r,i)
print(curr_term,end=" ")
a=2
r=3
n=5
printGP(a,r,n)
n1,n2=0,1
count=0
if nterms<=0:
elif nterms==1:
else:
while count<nterms:
print(n1)
nth=n1+n2
n1=n2
n2=nth
count+=1
---------------------output----------------------------------------
2 5 8 11 14 17 20 23 26 29
2 6 18 54 162
Fibbonacci sequence:
13
21
34
b) different patterns
rows=10
for i in range(rows):
for j in range(i):
print(i,end='')
print('')
n=10
for i in range(n,0,-1):
for j in range(1,i+1):
print('*', end='')
print()
n=5
for i in range(1,n+1):
print(''*(n-i)+'*'*(2*i-1))
n=5
for i in range(1,n+1):
print(''*(n-i)+''.join(chr(64+i)for _ in range(i)))
-----------------output-----------------------
22
333
4444
55555
666666
7777777
88888888
999999999
**********
*********
********
*******
******
*****
****
***
**
***
*****
*******
*********
BB
CCC
DDDD
EEEEE
PROGRAM 6
import numpy as np
n_array=np.array([[50,29],[30,44]])
print(n_array)
det=np.linalg.det(n_array)
print(int(det))
-------output-----------
[[50 29]
[30 44]]
1330
import numpy as np
a=np.array([[0,2],
[2,3]])
w,v=eig(a)
print('E-value:',w)
print('E-vector',v)
------output-----------
[ 0.4472136 -0.89442719]]
import numpy as np
arr1=np.array([[1,2],[3,5]])
arr2=np.array([1,2])
print("Array1...\n",arr1)
print("\n Array2...\n",arr2)
print("\n Result...\n",np.linalg.solve(arr1,arr2))
-----------output---------------
Array1...
[[1 2]
[3 5]]
Array2...
[1 2]
Deminesions of Array1...
Deminesions of Array2...
Shape of Array1...
(2, 2)
Shape of Array2...
(2,)
Result...
[-1. 1.]
PG7
Graphics
import turtle
class ShapeDrawer:
def __init__(self):
self.t=turtle.Turtle()
def draw_circle(self,radius):
self.t.penup()
self.t.goto(0,-radius)
self.t.pendown()
self.t.circle(radius)
def draw_triangle(self,side_length):
for _ in range(3):
self.t.forward(side_length)
self.t.left(120)
def draw_rectangle(self,width,height):
for _ in range(2):
self.t.forward(width)
self.t.left(90)
self.t.forward(height)
self.t.left(90)
def draw_square(self,side_length):
self.draw_rectangle(side_length,side_length)
def draw_polygon(self,side_length,num_sides):
for _ in range(num_sides):
self.t.forward(side_length)
self.t.left(360/num_sides)
def reset(self):
self.t.penup()
self.t.goto(0,0)
self.t.pendown()
self.t.clear()
if __name__=="__main__":
screen=turtle.Screen()
screen.bgcolor("white")
drawer=ShapeDrawer()
drawer.draw_circle(100)
drawer.draw_rectangle(60,40)
drawer.draw_triangle(80)
drawer.draw_square(90)
drawer.draw_polygon(30,5)
turtle.done()
turtle.done()
Output
pg8
import numpy as np
height=10
width=50
image=np.zeros((height,width,3),dtype=np.uint8)
image[30:70,30:70,0]=255
image[30:70,30:70,1]=0
image[30:70,30:70,2]=0
image[:,:,0]=0
image[:,:,1]=0
image[:,:,2]=255
plt.imshow(image)
plt.axis('off')
plt.show()
PG 9
import pandas as pd
data=[10,20,30,40,50]
labels=['A','B','C','D','E']
series = pd.Series(data,index=labels)
print(series)
print(series['C'])
print(series.iloc[2])
print(series+10)
print(series*2)
series['B']=25
print(series)
series['F']=60
print(series)
del series['D']
print(series)
output
A 10
B 20
C 30
D 40
E 50
dtype: int64
30
30
A 20
B 30
C 40
D 50
E 60
dtype: int64
A 20
B 40
C 60
D 80
E 100
dtype: int64
A 10
B 25
C 30
D 40
E 50
dtype: int64
A 10
B 25
C 30
D 40
E 50
F 60
dtype: int64
A 10
B 25
C 30
E 50
F 60
dtype: int64
PG10
def devide_numbers():
try:
result=numerator/denominator
except ZeroDivisionError:
else:
print(f"Result:{result}")
def check_voter_age():
try:
if age<18:
else:
except ValueError as e:
print(f"Error:{e}")
except Exception as e:
def validate_student_marks():
try:
if marks<0 or marks>100:
else:
print("Valid marks entered:{marks}")
except ValueError as e:
print(f"error:{e}")
except Exception as e:
def main():
devide_numbers()
check_voter_age()
validate_student_marks()
if __name__=="__main__":
main()
output
1.Divide numbers:
enter numerator: 10
enter denominator: 2
Result:5.0