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

Python Cheat Sheet

This document contains code snippets and documentation for several Python functions: 1) Functions for calculating the cube root of a number, rolling a coin, calculating Fibonacci numbers recursively and iteratively, and the exponential integral using numerical integration. 2) Code showing plotting of various functions like sine with different powers of x, and exponential decay. 3) Documentation and code for exhaustive search, bisection search, and other numerical methods to find roots of functions within a range. 4) Miscellaneous code defining functions, importing modules, calculating factorials recursively and iteratively, and computing the power set of a set.

Uploaded by

BeenishMuazzam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Python Cheat Sheet

This document contains code snippets and documentation for several Python functions: 1) Functions for calculating the cube root of a number, rolling a coin, calculating Fibonacci numbers recursively and iteratively, and the exponential integral using numerical integration. 2) Code showing plotting of various functions like sine with different powers of x, and exponential decay. 3) Documentation and code for exhaustive search, bisection search, and other numerical methods to find roots of functions within a range. 4) Miscellaneous code defining functions, importing modules, calculating factorials recursively and iteratively, and computing the power set of a set.

Uploaded by

BeenishMuazzam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

x=float(input('Enter a number = ')) x=float(input('Enter a number = ')) import random def fact_smp(n):#simple

eps=0.01; """cube root of positive number greater than 1""" def roll_coin(): fact=1
step=0.001; eps=0.1 """A function to toss a coin""" for i in range(1,n+1):
i=0; low=1 return int(random.uniform(0.5,1.5)) fact*=i
while abs(x)-i**3>eps: high=x heads, tails, up=0, 0, 0 return fact
i+=step; guess=(low+high)/2 for i in range(10000): def Fib_smp(n):
while abs(x-guess**3)>eps: res=int(roll_coin()) Fib1=0
print('guess = ',guess, 'low = ',low,'high =',high) if res==0: Fib2=1
if abs(x)-i**3<=eps:
if guess**3>=abs(x): heads+=1 for i in range(3,n+1):
if x>0:
high=guess elif res==1: Fib=Fib1+Fib2
print('Approx Cube root is = ',i)
else: tails+=1 Fib1, Fib2=Fib2, Fib
else:
low=guess else: return Fib
print('approx cube root is = ', -i)
guess=(low+high)/2 up+=1 for i in range(3,10):
else:
if abs(x-guess**3)<=eps: print('number of heads = ', heads) print(Fib_smp(i))
print('No solution!')
print('Approx Cube root is = ',guess) print('number of tails = ', tails)
import random import math
def findx(a,b): """overflow and underflow""" def fact_rec(n):#recursion ee=math.e
x=random.uniform(a,b) ov=1; if n>0: def Inf(n):
return x und=1; return n*fact_rec(n-1) if n==0:
def f(x): for i in range(1100): if n==0: return ee-1
return x**2-5*x+6 ov*=2.0; return 1 if n>0:
a, b=0, 4 # Solution will be searched in [a,b] und/=2; def Fib_rec(n): return ee-n*Inf(n-1)
eps=0.001 print('i = ',i) if n>2: import pylab
max_guess=10000 print('ov = ',ov) return Fib_rec(n-1)+Fib_rec(n-2) nn=[]
for i in range(max_guess+1): print('und = ',und) if n==1: inti=[]
x=findx(a,b) """Checking machine precision""" return 0 for i in range(20):
if abs(f(x))<eps: eps=10**(-1) if n==2: nn.append(i)
print('Number of steps = ',i) for m in range(30): return 1 inti.append(Inf(i))
print('solution = ',x) eps*=10**(-1) for i in range(1,10): pylab.plot(nn,inti)
break if 1+eps==1: print(Fib_rec(i)) pylab.show()
if i==max_guess: print('machine precision = ',eps) def sinr(x,n):
print('No real solutions from ',a,' to ',b) break if n==0: import numpy as np
return x import pylab as pl
"""Exhaustive Search for finding roots in [a,b]""" Int;float;bool,str;bytes if n>0: N=30
def f(x): #This defines a function return sinr(x,n-1)\ I=[0]*(N+1)
return x**3-5*x**2-100 +(-1)**n*x**(2*n+1)/fact_rec(2*n+1) for n in range(N,0,-1):
a, b=-10, 100 # Solution will be searched in [a,b] import pylab as pl I[n-1]=(np.e-I[n])/(n)
eps, step=0.01, 0.0001 x=pl.linspace(-10,10,1001) n = range(N+1)
N=int((b-a)/step) # Number of Steps in [a,b] import time pl.plot(n,I)
y1=x**1*pl.sin(x)
flag=0 t0=time.clock() pl.xlabel('n')
y1/=max(y1)
for i in range(0,N+1): for i in range(10000000): pl.ylabel('$I(n)$')
y2=x**2*pl.sin(x)
x=step*i x=2 pl.title('Back Integration')
y2/=max(y2)
if abs(f(x))<eps: t1=time.clock()
y3=x**3*pl.sin(x)
print('One solution is = ',x) print('time t =',t1-t0)
y3=y3/max(y3)
flag=1 def powerset(input):
pl.plot(x,y1,label='$x^{1}\sin x$',linestyle='-') import math
if flag==0: A=[[]]
pl.plot(x,y2,label='$x^{2}\sin x$',linestyle='--') try:
print('No real solutions from ',a,' to ',b) B=[]
pl.plot(x,y3,label='$x^{3}\sin x$',linestyle='-.') i=1 for m in input:
pl.legend(loc='lower center') k=1.0 for n in A:
"""Bisection Search for finding roots in [a,b]""" pl.xlabel('x') while i!=0: B=[n+[m]]
def f(x): #This defines a function pl.ylabel('$x^n\sin x$') k=math.exp(i) A=A+B
return x**2-5*x+6 pl.title('several plots') i=i+0.1 return A
a, b=2.1, 3.1 # Solution will be searched in [a,b] pl.show() except Exception as e:
eps=0.001 import pylab as pl print("Error1: ",str(e)) Module:math;cmath;random
precision=0.00001 x=pl.linspace(-10,10,1001) print("k=",k) Package:pylab;numpy;scipy
c=(b+a)/2 # First middle value of x st=['-','--','-.','-',':'] print("i=",i) Library:sympy;matplotlib
while abs(f(c))>eps: for n in range(1,5):
if (f(a)>0 and f(c)>0) or (f(a)<0 and f(c)<0): y=x**n*pl.sin(x) import numpy as np
a=c y/=max(y) import matplotlib.pyplot as plt
elif (f(b)>0 and f(c)>0) or (f(b)<0 and f(c)<0): pl.plot(x,y,label='$x^{}\sin x$'.format(n),\ from mpl_toolkits.mplot3d import Axes3D
b=c linewidth=n/2,linestyle=st[n]) ax = plt.subplot(111, projection='3d')
c=(b+a)/2 # New middle value of x pl.legend(loc='lower center') L, n = 2, 400
if abs(b-a)<precision: pl.xlabel('x') x = np.linspace(-L, L, n)
break pl.ylabel('$x^n\sin x$') y = x.copy()
if abs(f(c))<=eps: pl.title('several plots') X, Y= np.meshgrid(x, y)
print('solution found is = ',c) pl.show() A = np.double(0.1)
else: Z = np.exp(-(X**2+Y**2))
print('No real solutions from ',a,' to ',b) ax.plot_wireframe(X, Y, Z)
import numpy as np #ax.plot_surface(X, Y, Z)
"""Secant method for finding roots in [a,b]""" import matplotlib.pyplot as plt plt.show()
def f(x): #This defines a function from mpl_toolkits.mplot3d import Axes3D
return x**2-5*x+6 fig = plt.figure() x=0 s=str(input('Enter a phrase: '))
xn2, xn1=4, 5.1 # Solution will be searched in [a,b] ax = fig.add_subplot(111, projection='3d') y=1 abbrev= s[0].upper()
eps=0.01 # Plot a helix along the x-axis count=0 for i in range(1, len(s)):
precision=0.00001 n = 1000 print('100 Fib no are' ) if (s[i] == ' ' or s[i] =='-'):
xn=xn1-f(xn1)*(xn1-xn2)/(f(xn1)-f(xn2)) theta_max = 8 * np.pi for count in range(0,100): characters = s[i + 1].upper()
while abs(f(xn))>eps: theta = np.linspace(0, theta_max, n) print(x) abbrev = abbrev + characters
xn=xn1-f(xn1)*(xn1-xn2)/(f(xn1)-f(xn2)) x = theta F=x+y print(abbrev)
xn2,xn1=xn1,xn z = np.sin(theta) x=y
if abs(xn1-xn2)<precision: y = np.cos(theta) y=F
break ax.plot(x, y, z, 'b')
if abs(f(xn))<=eps: ax.plot(x, y, 0, color='r')
print('solution found is = ',xn) ax.plot(x, [0]*n, z, color='m')
plt.show()
import pylab as pl orbitals=["1s","2s","2p","3s","3p","4s",\ from numpy import sin
def factorial(n): "3d","4p","5s","4d","5p",\ from numpy import exp
if n <= 0: "6s","4f","5d"] import pylab as pl
return 1 electrons=[2,2,6,2,6,2,10,6,2,10,6,2,14,10] def f(x):
else: atomic_number=int(input('Enter atomic number: ')) return sin(x)
return n*factorial(n-1) while atomic_number<1: #Test 1 and test 2
def expf(x,N): print('Enter a positive number.') def integral(a,b,delta_x):
term=0 atomic_number=int(input('Enter atomic number: ')) N=int((b-a)/delta_x)
ans=1 while atomic_number>80: Sum=f(a)
for i in range(1,N ): print('Enter atomic number between 1 and 80') for i in range(1,N):
term= (-x)**(i)/factorial(i) atomic_number=int(input('Enter atomic number: ')) Sum += 2*f(a+i*delta_x)
ans=ans+term sum=0 Sum += f(b)
return ans i=0 Integral_1=(delta_x*Sum)/2
def integral(xc,N): ec=[] return Integral_1
a=0 for o in orbitals: Integ1=[]
b=xc if sum<=atomic_number-1: Integ2=[]
delta_x=(b-a)/N sum=electrons[i]+sum dx=pl.linspace(0.0001,0.1)
Sum=expf(a,N) e=orbitals[i-1],electrons[i-1] for i in dx:
for i in range(1,N): ec.append(e) I1=integral(0,10*22/7,i)
Sum += 2*expf(a+i*delta_x,N) i=i+1 Integ1.append(I1)
Sum += expf(b,N) d=sum-atomic_number I2 =integral(0,9*22/7,i)
Integral_1=(delta_x*Sum)/2 if d>=0: Integ2.append(I2)
return Integral_1 electrons[i-1]=electrons[i-1]-d Integ1/=max(Integ1)
xc=[2,18,15,20,50] e1=(orbitals[i-1],electrons[i-1]) Integ2/=max(Integ2)
for item in xc: ec.append(e1) pl.plot(dx,Integ1,label='Integral ',linestyle='--')
E=[] print('The electronic configuration is:') pl.plot(dx,Integ2,label='Integral ',linestyle='-')
for m in range(1,50+1): print(ec[1:]) pl.legend(loc='best')
I=integral(item,m) pl.xlabel('$\Delta x$')
error=I-1 def f(x,y): pl.ylabel('Integral')
E.append(error) return x**2-x-y-6 pl.title('Variation of integral ')
m = pl.linspace(1,51) def g(x,y): pl.show()
pl.plot(m,E,label='$xc={}$'.format(item)) return y+2*x-6
pl.legend(loc='best') a,b=-100,100 hbar=1.054*10**-34
pl.xlabel('No of terms in taylor expansion') eps, step=0.0001,0.1 pi=22/7
pl.ylabel('$Error$') N=int((b-a)/step) L=1*10**-9
pl.title('Limit of integration=xc') for i in range(-N,N): print('The length is', L/(1*10**-9),'nm.')
pl.show() for j in range(-N,N): U=4*1.6*10**-19
x=step*i print('The potential energy is',U/(1.6*10**-19),'eV.')
a=float(input('Enter the value of a: ')) y=step*j n=3
b=float(input('Enter the value of b: ')) if abs(f(x,y))<eps and abs(g(x,y))<eps: print('n =',n)
c=float(input('Enter the value of c: ')) print('The roots are', x,y) m=9.11*10**-31
d=b*b-4*a*c d0=0
eps=0.02 """sin function""" E0=n**2*pi**2*hbar**2/(2*m*L**2)
step=0.001 def factorial(n): print('Ground state energy',E0/(1.6*10**-19),'eV.')
ans=0.0 if n <= 0: d1=hbar/((2*m*(U-E0))**0.5)
while abs(ans**2-d) >= eps and ans<=d: return 1 E1=n**2*pi**2*hbar**2/(2*m*(L+2*d1)**2)
ans=ans+step else: d2=hbar/((2*m*(U-E1))**0.5)
if abs(ans**2-d)>=eps: return n*factorial(n-1) E2=n**2*pi**2*hbar**2/(2*m*(L+2*d2)**2)
print('Sorry failed to find roots') x=float(input('Enter the angle: ')) while abs(E2-E1)>0.0001*E1:
else: N=int(input('Enter the number of terms: ')) d2=hbar/((2*m*(U-E1))**0.5)
x1=(-b-ans)/(2*a) pi=22/7 E2=n**2*pi**2*hbar**2/(2*m*(L+2*d2)**2)
x2=(-b+ans)/(2*a) rad=x*pi/180 d1=hbar/((2*m*(U-E2))**0.5)
print('The first root is: ', x1) ans=rad E1=n**2*pi**2*hbar**2/(2*m*(L+2*d1)**2)
print('The second root is: ', x2) term=0 print('Penetration length:',d1/(1*10**-9),'nm. The energy is'\
for i in range(1,N ): ,E1/(1.6*10**-19), 'eV.')
x = int(input('Enter : ')) term= (-1)**i * rad**(2*i+1)/factorial(2*i+1)
while x < 0: ans=ans+term
print('Sorry ! ' ) print(ans)
x = int(input('Enter : '))
if x == 0 or x == 1:
print('The facorial of', x, 'is', 1)
else:
factorial = 1
num = x
while num > 1:
factorial = factorial * num
num = num -1
print('facorial of', x, 'is', factorial)

List:lst.append(val); lst.extend(seq);
lst.inert(idx,val);lst.remove(val);
lst.pop([idx]), lst.sort(), lst.reverse() String:s.startswith(prefix[,start[,end]]);s.strip([chars]);
Set:s.update(s2);s.copy();s.add(key), s.endswith(suffix[,start[,end]]);s.patition(sep);
s.remove(key),s.discard(key);s.clear(); s.count(sub[,start[,end]]); s.find(sub[,start[,end]]);
s.pop();|(union);&(intersection). s.index(sub[,start[,end]]),s.is …();s.lower();s.title();
s.swapcase();s.casefold();s.capitalize();s.split([sep]);
Dict:d[key]=value;d.update(d2);d.k s.center([width,fill});s.join(seq);s.encode(encoding);
ey(); d.values();d.items(); s.ljust([width,fill}); s.rjust([width,fill});s.zfill([width])
d.pop(key);d.popitem(key,value);
d.get(key);d.setdefault(key) len(c);min(c);max(c);sum(c);sorted(c);val in c;
list[];tuple(); enumerate(c);zip(c1,c2);all(c),any(c);
dict{1:”one”,2:”two”}; range([start,]end[,step])

You might also like