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

Python Sem-4 Codes - Ipynb - Colab

Uploaded by

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

Python Sem-4 Codes - Ipynb - Colab

Uploaded by

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

8/1/24, 8:23 PM Python Sem-4 codes.

ipynb - Colab

Q1. Average of best 2 out of three marks.

m1=int(input("Enter first marks:"))


m2=int(input("Enter secind marks:"))
m3=int(input("Enter third marks:"))
if m1<m2 & m1<m3:
avgmarks=(m2+m3)/2;
elif m2<m1 & m2<m3:
avgmarks=(m1+m3)/2;
else:
avgmarks=(m1+m2)/2;
print("The average of best of two is:",avgmarks)

Enter first marks:99


Enter secind marks:98
Enter third marks:97
The average of best of two is: 98.5

Q2. Fibanocci series

def f(n):
if n<=1:
return n;
else:
return f(n-1)+f(n-2);
num=int(input("Enter the number if terms:"))
for i in range(num):
print(f(i));

Enter the number if terms:10


0
1
1
2
3
5
8
13
21
34

Q3. Check if word or number is a palindrome

val=input("Enter a character:")
val_str=str(val);
if val_str==val_str[::-1]:
print("It is a palindrome")
else:
print("It is not a palindrome")

Enter a character:hhhaha
It is not a palindrome

val=int(input("Enter a number"))
val_string=str(val);
if val_string==val_string[::-1]:
print("It is a palindrome number")
else:
print("It is not a palindrome number")

Enter a number123
It is not a palindrome number

Q4. Number system conversion

#binary to decimal:
def bin2dec(n):
if n<=1:
return n;
else:
return((n%10)+2*bin2dec(n//10));
num=int(input("Enter binary number:"));
num1=bin2dec(num);
print("The number in decimal is:",num1);

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 1/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab

Enter binary number:1000


The number in decimal is: 8

#decimal to binary:
def dec2bin(n):
if n<=1:
return str(n);
else:
return((str(n%2))+str(dec2bin(n//2)));
num=int(input("Enter the decimal number:"))
num1=int(dec2bin(num)[::-1]);
print("The binary equivalent is:",num1)

Enter the decimal number:8


The binary equivalent is: 1000

#octal to decimal:
def oct2dec(n):
if n<8:
return n;
else:
return((n%10)+8*(oct2dec(n//10)));
num=int(input("Enter the octal number:"));
num1=oct2dec(num)
print("The decimal equivalent is:",num1);

Enter the octal number:16


The decimal equivalent is: 14

#decimal to octal:
def dec2oct(n):
if n<8:
return n;
else:
return((str(n%8))+str(dec2oct(n//8)));
num=int(input("Enter the decimal number"));
num1=int(dec2oct(num)[::-1]);
print("The decimal equivalent is:",num1);

Enter the decimal number14


The decimal equivalent is: 16

#hexadecimal to decimal:
def hex2dec(m):
n=m[::-1]
l=len(n)
k=0
sum1=0;
for i in range(l):
if ord(n[i])>=65 and ord(n[i])<=70:
sum1+=((ord(n[i])-65+10)*16**(k))
else:
sum1+=(int(n[i])*16**(k))
k+=1;
return sum1;
num=input("Enter hexadecimal number:")
num1=hex2dec(num);
print("Equivalent Decimal value is",num1)

Enter hexadecimal number:1A


Equivalent Decimal value is 26

#decimal to hexadecimal:
def dec2hex(n):
if n<16:
if n%16>9:
return (chr(55+n))
else:
return str(n)
else:
if n%16>9:
return (chr(55+(n%16))+dec2hex(n//16))
else:
return(str(n%16)+dec2hex(n//16))
num=int(input("Enter decimal number:"))
num1=dec2hex(num)[::-1];
print("The Hexadecimal equivalent is:",num1)

Enter decimal number:26


The Hexadecimal equivalent is: 1A

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 2/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab

Q5. Calculate area of circle, rectangle and triangle.

import math
class Shape:
def __init__(self):
self.area=0;
self.name="";

def showArea(self):
print("The area of",self.name,"is",self.area,"units")

class circle(Shape):
def __init__(self,radius):
self.area=0
self.name="circle"
self.radius=radius

def calcArea(self):
self.area=math.pi*self.radius*self.radius

class Rectangle(Shape):
def __init__(self,length,breadth):
self.area=0
self.name="Rectangle"
self.length=length
self.breadth=breadth

def calcArea(self):
self.area=self.length*self.breadth

class Triangle(Shape):
def __init__(self,base,height):
self.area=0
self.name="Triangle"
self.base=base
self.height=height

def calcArea(self):
self.area=self.base*self.height/2

c1=circle(5)
c1.calcArea()
c1.showArea()

r1=Rectangle(4,5)
r1.calcArea()
r1.showArea()

t1=Triangle(4,5)
t1.calcArea()
t1.showArea()

The area of circle is 78.53981633974483 units


The area of Rectangle is 20 units
The area of Triangle is 10.0 units

Q6. Program to calculate resistance, capacitance and inductance

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 3/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab
class ResistanceCalculator:
def __init__(self,voltage,current):
self.voltage=voltage
self.current=current

def calculate_resistance(self):
if self.current!=0:
return self.voltage/self.current
else:
return float('inf')

class InductanceCalculator(ResistanceCalculator):
def __init__(self,voltage,current):
super().__init__(voltage,current)

def calculate_inductance(self,frequency):
if self.current !=0 and frequency !=0:
return self.voltage/(2*3.14159*self.current*frequency)
else:
return float('inf')

class CapacitanceCalculator(ResistanceCalculator):
def __init__(self,voltage,current):
super().__init__(voltage,current)

def calculate_capacitance(self,frequency):
if self.current!=0 and frequency!=0:
return self.current/(2*3.141592*self.voltage*frequency)
else:
return float('inf')

#usage example
voltage_val=220
current_val=0.1
frequency_val=50

resistance_calculator=ResistanceCalculator(voltage_val,current_val)
resistance_result=resistance_calculator.calculate_resistance()
print(resistance_result)

inductance_calculator=InductanceCalculator(voltage_val,current_val)
inductance_result=inductance_calculator.calculate_inductance(frequency_val)
print(inductance_result)

capacitance_calculator=CapacitanceCalculator(voltage_val,current_val)
capacitance_result=capacitance_calculator.calculate_capacitance(frequency_val)
print(capacitance_result)

2200.0
7.002823411075283
1.4468634200286178e-06

Q6. Program to generate electric field lines due to point charge.

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 4/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab
import numpy as np
import matplotlib.pyplot as plt

k=8.99e-9
q=1e9
x=np.linspace(-10,10,400)
y=np.linspace(-10,10,400)
X,Y=np.meshgrid(x,y)

def electric_field(q,ro,x,y):
den=np.hypot(x-ro[0],y-ro[1])**3
Ex=k*q*(x-ro[0])/den
Ey=k*q*(y-ro[1])/den
return Ex,Ey

ro=np.array([0.0,0.0])
Ex,Ey=electric_field(q,ro,X,Y)

fig,ax=plt.subplots(figsize=(8,8))
color=np.log(np.hypot(Ex,Ey))

ax.streamplot(X,Y,Ex,Ey, color=color, linewidth=1 ,cmap='inferno', density=2)


ax.plot(ro[0],ro[1],'ro')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Electric field lines due to a point charger')
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
plt.show()

Q8. Program to display poles and zeros.

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 5/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

numerator=[5,2]
denominator=[3,2,5]
transfer_fucntion=signal.TransferFunction(numerator,denominator)
poles=transfer_fucntion.poles
zeros=transfer_fucntion.zeros

plt.figure(figsize=(8,6))
plt.scatter(np.real(poles),np.imag(poles),marker='x',color='red',label='poles')
plt.scatter(np.real(zeros),np.imag(zeros),marker='o',color='blue',label='zeros')
plt.axhline(0,color='black',linewidth=0.5)
plt.axvline(0,color='black',linewidth=0.5)
plt.ylabel('real')
plt.xlabel('imaginary')
plt.title('Pole-zero plot of transfer function')
plt.legend()
plt.grid()
plt.show()

Q9. Bode plot for given TF.

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

num=[1]
denum=[1,2,1]
system=signal.TransferFunction(num,denum)
omega=np.logspace(-2,2,1000)
_,mag,phase=signal.bode(system,omega)

plt.figure(figsize=(10,6))
plt.subplot(2,1,1)
plt.semilogx(omega,mag)
plt.xlabel('frequency rad/s')
plt.ylabel('magnitude(db)')
plt.title('Bode magnitude plot')

plt.figure(figsize=(10,6))
plt.subplot(2,1,2)
plt.semilogx(omega,phase)
plt.xlabel('frequency rad/s')
plt.ylabel('phase(degrees)')
plt.title('Bode phase plot')
plt.tight_layout()
plt.show()

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 6/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab

Q10. Program to display Nyquist plot.

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

num=[1]
denum=[1,2,1]
system=signal.TransferFunction(num,denum)
omega=np.logspace(-2,2,1000)
_,h=signal.freqresp(system,omega)

real_part=np.real(h)
image_part=np.imag(h)

plt.figure(figsize=(8,6))
plt.plot(real_part,image_part)
plt.plot(real_part,-image_part)

plt.xlabel('Real part')
plt.ylabel('Imaginary part')
plt.title('Nyquist plot')
plt.axis('equal')
plt.grid('true')
plt.show()

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 7/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab

Q11. Program to solve difference equation using Z transform.

import matplotlib.pyplot as plt


import numpy as np

def unilateral_ztransfrom_difference_equation(a,x):
n=len(x)
y=np.zeros(n)
y[0]=x[0]
for i in range (1,n):
y[i]=a*y[i-1]+x[i]
return y

a=0.5
n_samples=10
x=np.ones(n_samples)
y=unilateral_ztransfrom_difference_equation(a,x)
print("Output sequence(y)",y)
plt.stem(range(n_samples),x,basefmt='b-',linefmt='b-',markerfmt='bo',label="input x[n]")
plt.stem(range(n_samples),y,basefmt='r-',linefmt='r-',markerfmt='ro',label="output y[n]")
plt.xlabel('n')
plt.ylabel('Amplitude')
plt.title("Difference equation using Z transform")
plt.legend()
plt.show()

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 8/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab

Output sequence(y) [1. 1.5 1.75 1.875 1.9375 1.96875


1.984375 1.9921875 1.99609375 1.99804688]

add Code add Text


Q12. Program to solve 2nd order differential equation.

import sympy as sp
from scipy import signal
t,s=sp.symbols('t s')
coeff=[1,5,6]
in_cond=[0,2]
L_LHS=coeff[0]*s**2+coeff[1]*s+coeff[2]
L_RHS=in_cond[0]+in_cond[1]
tf=L_RHS/L_LHS
L_equation=sp.inverse_laplace_transform(tf,s,t)
print(L_equation)

2*exp(-2*t)*Heaviside(t) - 2*exp(-3*t)*Heaviside(t)

Q13. Generate a sin wave.

import math
import matplotlib.pyplot as plt
import numpy as np

def sine_wave_generator(freq,amplitude,duration,sampling_rate):
num_samples=duration*sampling_rate
print("Number od samples=",num_samples)
time_period=1.0/sampling_rate
print("Time period=",time_period)
time_value=np.arange(0,duration,time_period)
print("The time values are ",time_value)
sine_wave=amplitude*np.sin(2*np.pi*freq*time_value)
return time_value,sine_wave

#example usage
freq=0.5
amplitude=2
duration=20
sampling_rate=44100
time_value,sine_wave=sine_wave_generator(freq,amplitude,duration,sampling_rate)

plt.figure(figsize=(8,6))
plt.plot(time_value,sine_wave)
plt.xlabel('x')
plt.ylabel('y')
plt.title("Sine Wave")
plt.grid()
plt.show()

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 9/10
8/1/24, 8:23 PM Python Sem-4 codes.ipynb - Colab

Number od samples= 882000


Time period= 2.2675736961451248e-05
h ti l [0 00000000 00 2 2 3 0 0 3 39 0 99999320 0

https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 10/10

You might also like