Python Sem-4 Codes - Ipynb - Colab
Python Sem-4 Codes - Ipynb - Colab
ipynb - Colab
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));
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
#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
#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)
#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);
#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);
#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)
#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)
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
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()
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
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))
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()
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
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
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
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)
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
https://colab.research.google.com/drive/1274a18hvQ-_Cd_4NpxBEFuYAuaLeKmmu#scrollTo=XnpdxZmfKjLk&printMode=true 10/10