0% found this document useful (0 votes)
19 views24 pages

BME358A Py Pgs

Programs

Uploaded by

Akshatha M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views24 pages

BME358A Py Pgs

Programs

Uploaded by

Akshatha M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

text="Hello World World"

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)

print("The factorial of", num, "is", result)

The factorial of 7 is 5040


=================================================================================

2 b)

def Nmaxelements(list1, N):

final_list = []
for i in range(0, N):

max1 = 0

for j in range(len(list1)):

if list1[j] > max1:

max1 = list1[j]

list1.remove(max1)

final_list.append(max1)

print(final_list)

list1 = [2, 6, 41, 85, 0, 3, 7, 6, 10]

N=2

Nmaxelements(list1, N)

[85, 41]

2 c)

def calculate_area(name):

# converting all characters

# into lower cases

name = name.lower()

# check for the conditions

if name == "rectangle":
l = int(input("Enter rectangle's length: "))

b = int(input("Enter rectangle's breadth: "))

# calculate area of rectangle

rect_area = l * b

print(f"The area of rectangle is {rect_area}.")

elif name == "square":

s = int(input("Enter square's side length: "))

# calculate area of square

sqt_area = s * s

print(f"The area of square is {sqt_area}.")

elif name == "triangle":

h = int(input("Enter triangle's height length: "))

b = int(input("Enter triangle's breadth length: "))

# calculate area of triangle

tri_area = 0.5 * b * h

print(f"The area of triangle is {tri_area}.")

elif name == "circle":

r = int(input("Enter circle's radius length: "))

pi = 3.14

# calculate area of circle

circ_area = pi * r * r

print(f"The area of circle is {circ_area}.")


elif name == 'parallelogram':

b = int(input("Enter parallelogram's base length: "))

h = int(input("Enter parallelogram's height length: "))

# calculate area of parallelogram

para_area = b * h

print(f"The area of parallelogram is {para_area}.")

else:

print("Sorry! This shape is not available")

# driver cod

if __name__ == "__main__" :

print("Calculate Shape Area")

shape_name = input("Enter the name of shape whose area you want to find: ")

# function calling

calculate_area(shape_name)

Calculate Shape Area


Enter the name of shape whose area you want to find: circle
Enter circle's radius length: 59
The area of circle is 10930.340000000002.

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

def matrix_addition(matrix1, matrix2):


return [[matrix1[i][j] + matrix2[i][j] for j in range(3)] for i in range(3)]

def matrix_subtraction(matrix1, matrix2):


return [[matrix1[i][j] - matrix2[i][j] for j in range(3)] for i in range(3)]

def matrix_multiplication(matrix1, matrix2):


result = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
result[i][j] = sum(matrix1[i][k] * matrix2[k][j] for k in range(3))
return result

def are_identical(matrix1, matrix2):


return matrix1 == matrix2

# Main program
print("Matrix 1:")
matrix1 = input_matrix()

print("\n Matrix 2:")


matrix2 = input_matrix()

# Display the matrices


print("\nMatrix 1:")
print_matrix(matrix1)

print("\n\Matrix 2:")
print_matrix(matrix2)

# Find Transpose of both matrices


print("\nTranspose of Matrix 1:")
print_matrix(transpose(matrix1))

print("\nTranspose of Matrix 2:")


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

# Check if matrices are identical


if are_identical(matrix1, matrix2):
print("\nMatrix 1 and Matrix 2 are identical.")
else:
print("\nMatrix 1 and Matrix 2 are not identical.")
Matrix 1:
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 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]

Matrix 1 and Matrix 2 are identical.

PROGRAM 4

Implemening programs using Strings(reverse, palindrome,character count and replacing characters)

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]

input_string=input("Enter the string: ")

reverse_str=reverse_string(input_string)

print("reversed string: ",reverse_str)


old_string=input("enter characters to replace: ")

new_string=input("enter new character: ")

replaced_string=replace_characters(input_string,old_string,new_string)

print("string after replacement: ", replaced_string)

s="malayalam"

ans=isPalindrome(s)

if ans:

print(s,"its a palindrome:")

else:

print(s,"its not a palindrome:")

print("input string:",input_string)

character_count=len(input_string)

print("number of characters: ",character_count)

-------------------output-----------------------------------

Enter the string: meghana

reversed string: anahgem

enter characters to replace: n

enter new character: m

string after replacement: meghama

malayalam its a palindrome:

input string: meghana

number of characters: 7

PROGRAM 5

Implementing programms using conditionals and iterative loops


a) Number series

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)

nterms=int(input("how many terms?"))

n1,n2=0,1

count=0

if nterms<=0:

print("please enter a positive integer")

elif nterms==1:

print("Fibbonacci sequence upto ",nterms,":")


print(n1)

else:

print("Fibbonacci sequence: ")

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

how many terms?10

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

Numpy library:linear algebra


a) find rank, determinant and trace of an matrix

import numpy as np

n_array=np.array([[50,29],[30,44]])

print("Numpy matrix is:")

print(n_array)

det=np.linalg.det(n_array)

print("\n Determinant of given 2*2 matrix:")

print(int(det))

-------output-----------

Numpy matrix is:

[[50 29]

[30 44]]

Determinat of given 2*2 matrix:

1330

b)find eigen values of matrices

import numpy as np

from numpy.linalg import eig

a=np.array([[0,2],

[2,3]])

w,v=eig(a)
print('E-value:',w)

print('E-vector',v)

------output-----------

E-value: [-1. 4.]

E-vector [[-0.89442719 -0.4472136 ]

[ 0.4472136 -0.89442719]]

c) to solve a linear matrix equaion,or system of linear scalar equations

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 Deminesions of Array1...\n",arr1.ndim)

print("\n Deminesions of Array2...\n",arr2.ndim)

print("\n Shape of Array1...\n",arr1.shape)

print("\n Shape of Array2...\n",arr2.shape)

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

1)Consider the turtle object.Write functions to draw traingle,rectangle.polygon,circle,square and shpere,

use onject oriented approach

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

import matplotlib.pyplot as plt

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

Python program to implement Pandas series wih lables

import pandas as pd

data=[10,20,30,40,50]

labels=['A','B','C','D','E']

series = pd.Series(data,index=labels)

print("Pandas Series with Labels:")

print(series)

print("\n Accessing value by label 'C':")

print(series['C'])

print("\n Accessing value by position 2:")

print(series.iloc[2])

print("\n Adding 10 to each elements:")

print(series+10)

print("\n Multiplying eah element by 2:")

print(series*2)

series['B']=25

print("\n Modified series(after changing 'B' to 25):")

print(series)

series['F']=60

print("\n Series after adding new element(F:60):")

print(series)

del series['D']

print("\n Series after deleting 'D':")

print(series)
output

Pandas Series with Labels:

A 10

B 20

C 30

D 40

E 50

dtype: int64

Accessing value by label 'C':

30

Accessing value by position 2:

30

Adding 10 to each elements:

A 20

B 30

C 40

D 50

E 60

dtype: int64

Multiplying eah element by 2:

A 20

B 40

C 60
D 80

E 100

dtype: int64

Modified series(after changing 'B' to 25):

A 10

B 25

C 30

D 40

E 50

dtype: int64

Series after adding new element(F:60):

A 10

B 25

C 30

D 40

E 50

F 60

dtype: int64

Series after deleting 'D':

A 10

B 25

C 30

E 50

F 60

dtype: int64
PG10

def devide_numbers():

try:

numerator=float(input("enter numerator: "))

denominator=float(input("enter denominator: "))

result=numerator/denominator

except ZeroDivisionError:

print("Error: Invalid input. Please enter numeric values.")

else:

print(f"Result:{result}")

def check_voter_age():

try:

age=int(input("Enter your age: "))

if age<18:

raise ValueError("you mustbe at least 18 year old to vote.")

else:

print("you are eligble to vote.")

except ValueError as e:

print(f"Error:{e}")

except Exception as e:

print(f"an unexpected erro occured:{e}")

def validate_student_marks():

try:

marks=float(input("Enter the students marks(0 to 100):"))

if marks<0 or marks>100:

raise ValueError("Marks mus be between 1 and 100.")

else:
print("Valid marks entered:{marks}")

except ValueError as e:

print(f"error:{e}")

except Exception as e:

print(f"An unexpected error occured:{e}")

def main():

print("real-time application with exception handling ")

print("\n 1.Divide numbers:")

devide_numbers()

print("\n 2.Voters age validity:")

check_voter_age()

print("\n 3.students marks range vakidation:")

validate_student_marks()

if __name__=="__main__":

main()

output

real-time application with exception handling

1.Divide numbers:

enter numerator: 10

enter denominator: 2

Result:5.0

2.Voters age validity:

Enter your age: 17

Error:you mustbe at least 18 year old to vote.


3.students marks range vakidation:

Enter the students marks(0 to 100):35

Valid marks entered:{marks}

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