!python -V
In [10]:
x=3
print (type(x))
print (x)
print (x+1)
print (x-1)
print (x*2)
print (x**2)
x+=1
print (x)
x*=2
print (x)
y=2.5
print (type(y))
print (y)
print (y,y+1,y*2,y**2)
In [15]:
t=True
f=False
print (type(t),type (f))
print (t and f)
print (t or f)
print (not t, not f)
print (t!=f)
In [37]:
s="hEllo"
print (s.capitalize())
print (s.upper())
print (s.lower())
print (s.rjust(9))
print (s.center(9))
print (s.replace('l','(cell)'))
print (s)
print (s.replace('2', '(isro)'))
print (' world'.strip())
In [43]:
xs=[3,1,2]
print (xs,xs[2])
print (xs[-1])
xs[2]='foo'
print (xs)
xs.append ('bar')
print (xs)
x=xs.pop()
print (x)
print (xs)
In [53]:
nums = list(range(5))
print (nums)
print (nums[2:4])
print (nums[2:])
print (nums[:2])
print (nums [:])
print (nums [:-1])
nums[2:4] = [7, 10]
print(nums)
In [58]:
animals=['cat','dog','monkey','rat']
for animal in animals:
print (animal)
In [59]:
for idx, animal in enumerate(animals):
print ('#%d: %s' %(idx+1,animal))
In [63]:
nums =[0,1,2,3,4]
squares =[]
for x in nums:
squares.append(x**2)
print (squares)
In [64]:
squares =[x ** 2 for x in nums]
print (squares)
In [67]:
even_squares =[x**2 for x in nums if x%2==0]
print (even_squares)
In [76]:
d={'cat':'pet','fun':'query'}
print (d['cat'])
print (d['fun'])
print ('cat' in d)
d['fish'] = 'wet'
print (d['fish'])
print(d.get('monkey', 'N/A'))
print(d.get('fish', 'N/A'))
del (d['fish'])
print(d.get('fish','N/A'))
In [77]:
d={'person':2, 'cat':4, 'spider':8}
for animal in d:
legs=d[animal]
print ("A %s has %d legs"%(animal, legs))
In [78]:
for animal, legs in d.items():
print("A %s has %d legs"%(animal, legs))
In [79]:
nums=[0,1,2,3,4]
even_number_to_square={x: x ** 2 for x in nums if x % 2 == 0}
print (even_number_to_square)
In [85]:
animals={'cat',"dog"}
print ('cat' in animals)
print ('rat' in animals)
print ('fish' in animals)
print ('dog' in animals)
animals.add ('fish')
print ('fish' in animals)
animals.add('cat')
print (len(animals))
animals.remove('cat')
print (len(animals))
In [89]:
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
In [92]:
from math import sqrt
num={ int(sqrt(x)) for x in range(30)}
print (num)
In [96]:
d={(x,x+1):x for x in range(20)}
t=(5,6)
print (type(t))
print (d[t])
print (d[(1,2)])
In [100]:
# function & class
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-2,-1,0,1,2,0]:
print (sign(x))
In [104]:
def hello (name, loud=True):
if loud:
print ('Hello, %s!' % name.upper())
else :
print ('Hello, %s!' %name)
hello ("Ranjan")
hello ('Sinha', loud=False)
In [114]:
#classes
class India(object):
#constructor
def __init__(self,name):#we have to put two _ here.
self.name=name
#instance method
def state(self, loud=True):
if loud:
print ('Hello, %s!' %self.name.upper())
else:
print ('Hello, %s!' %self.name)
In [116]:
g= India("Ranjan")
g.state ()
g.state (loud=False)
In [117]:
class Student (object):
# Constructor
def __init__(self, name):
self.name = name # Create an instance variable
#Instance Method
def rollcall(self, absent=False):
if absent:
print(self.name ,"absent")
else :
print (self.name,"present")
In [120]:
s1= Student("Ranjan")
s2= Student("Ruchi")
s3= Student("Ritu")
s1.rollcall()
s1.rollcall(absent=True)
s2.rollcall()
s2.rollcall(absent=True)
s3.rollcall()
s3.rollcall(absent=True)
In [125]:
class PraxisStudent (object):
# constructor
def __init__(self, name, roll):
self.name = name # Create an instance variable
self.rollno=roll
self.attendance=0
#Instance Method
def rollcall(self, absent=False):
if absent:
print (self.rollno, self.name, "absent", self.attendance, " classes attended")
else :
self.attendance=self.attendance+1
print (self.rollno, self.name, "present", self.attendance, " classes attended")
In [126]:
s2= PraxisStudent ("Ranjan",23)
s3= PraxisStudent ("Ruchi",24)
s4= PraxisStudent ("Ritu",25)
In [128]:
print (s2.name, s3.name, s4.name)
print (s2.rollno, s3.rollno, s4.rollno)
print (s2.attendance, s3.attendance, s4.attendance)
In [130]:
s2.rollcall()
s3.rollcall()
s4.rollcall()
s2.rollcall(absent=True)
s3.rollcall()
s4.rollcall(absent=True)
s2.rollcall(absent=True)
s3.rollcall(absent=True)
s4.rollcall()
In [132]:
print (s2.name,s3.name,s4.name)
print (s2.attendance,s3.attendance,s4.attendance)
In [133]:
s2.name= "Ranjan Sinha"
s3.name= "Ruchi srivastva"
In [137]:
print (s2.name,s3.name,s4.name)
In [138]:
del s2
In [146]:
# numpy
import numpy as np
a=np.array([1,2,3])
print (type(a))
print (a.shape)
print (a[0],a[1],a[2])
a[0]=5
print (a)
b=np.array([[1,2,3],[4,5,6]])
print (b.shape)
print (b[0,0],b[0,1],b[1,0])
In [155]:
import numpy as np
a=np.zeros((2,2))
print (a)
b=np.ones((1,2))
print(b)
c=np.full((2,2),9)
print (c)
d=np.eye(2)
print(d)
e=np.random.random((2,2))
print(e)
In [156]:
import numpy as np
a=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
b=a[:2, 1:3]
print (a[0,1])
b[0,0]=77
print (a[0,1])
In [157]:
import numpy as np
a=np.array ([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
row_r1= a[1, :]
row_r2= a[1:2,: ]
print (row_r1, row_r1.shape)
print (row_r2, row_r2.shape)
col_r1= a[:,1]
col_r2= a[:,1:2]
print (col_r1, col_r1.shape)
print (col_r2, col_r2.shape)
In [158]:
import numpy as np
a= np.array([[1,2],[3,4],[5,6]])
print(a[[0,1,2],[0,1,1]])
print (np.array([a[0,0],a[1,1],a[2,0]]))
print (a[[0,0],[1,1]])
print(np.array([a[0,1],a[0,1]]))
In [161]:
import numpy as np
a=np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
print (a)
b=np.array([0,2,0,1])
print (a[np.arange(4),b])
a[np.arange(4),b]+=10
print (a)
In [163]:
import numpy as np
a=np.array([[1,2],[3,4],[5,6]])
bool_idx= (a>2)
print (bool_idx)
print(a[bool_idx])
print(a[a>2])
In [164]:
import numpy as np
x=np.array([1,2])
print(x.dtype)
x=np.array([1.0,2.0])
print(x.dtype)
x=np.array([1,2],dtype=np.int64)
print(x.dtype)
In [166]:
import numpy as np
x=np.array([[1,2],[3,4]], dtype=np.float64)
y=np.array([[5,6],[7,8]], dtype=np.float64)
print(x+y)
print (np.add(x,y))
print(x-y)
print(np.subtract(x,y))
print(x*y)
print(np.multiply(x,y))
print (x/y)
print(np.divide(x,y))
print (np.sqrt(x))
In [168]:
import numpy as np
x= np.array([[1,2],[3,4]])
y=np.array([[5,6],[7,8]])
v=np.array([9,10])
w=np.array([11,12])
print (v.dot(w))
print(np.dot(v,w))
print (x.dot(v))
print(np.dot(x,v))
print(x.dot(y))
print (np.dot(x,y))
In [169]:
import numpy as np
x=np.array([[1,2],[3,4]])
print(np.sum(x))
print(np.sum(x,axis=0))
print(np.sum(x,axis=1))
In [170]:
import numpy as np
x=np.array ([[1,2],[3,4]])
print(x)
print(x.T)
v=np.array([1,2,3])
print(v)
print(v.T)
In [24]:
import numpy as np
a = np.arange(15).reshape(3, 5)
print (a)
print (a.shape)
print (a.ndim)
print (a.dtype.name)
print (a.itemsize)
print (a.size)
type(a)
b = np.array([6, 7, 8])
print (b)
print (type(b))
In [27]:
import numpy as np
a = np.array([2,3,4])
print (a)
print (a.dtype)
b = np.array([1.2, 3.5, 5.1])
print (b.dtype)
In [28]:
import numpy as np
a = np.array([1,2,3,4])
print (a)
print (a.dtype)
In [29]:
b = np.array([(1.5,2,3), (4,5,6)])
print (b)
print (b.dtype)
In [31]:
c = np.array( [ [1,2], [3,4] ], dtype=complex )
print (c)
print (c.dtype)
In [35]:
a=np.zeros( (3,4) )
print (a)
print (a.dtype)
b=np.ones( (2,3,4), dtype=np.int16 )
print (b)
print (b.dtype)
c=np.empty( (2,3) )
print (c)
print (c.dtype)
In [43]:
import numpy as np
a=np.arange( 10, 30, 5)
print (a)
print (a.dtype)
b=np.arange( 0, 2, 0.3)
print (b)
print (b.dtype)
In [44]:
from numpy import pi
a=np.linspace( 0, 2, 9 )
print (a)
x = np.linspace( 0, 2*pi, 100 )
print (x)
f = np.sin(x)
print (f)
In [46]:
import numpy as np
a = np.arange(6) # 1d array
print(a)
print (a.dtype)
b = np.arange(12).reshape(4,3) # 2d array
print(b)
print (b.dtype)
c = np.arange(24).reshape(2,3,4) # 3d array
print(c)
print (c.dtype)
In [49]:
print (np.arange (1000))
print (np.arange (10000).reshape (100,100))
In [50]:
print (np.set_printoptions(threshold=np.nan))
In [52]:
import numpy as np
a= np.array([20,30,40,50])
b=np.arange (4)
print (b)
c=a-b
print (c)
d=b**2
print (d)
print (10*np.sin(a))
print (a>35)
In [53]:
import numpy as np
A=np.array([[1,1],[0,1]])
B=np.array([[2,0],[3,4]])
print (A*B) # elementwise product
print (A@B) # matrix product
print (A.dot(B)) #another matrix product
In [63]:
a= np.ones ((2,3),dtype=int)
b= np.random.random((2,3))
a*=3
print (a)
print (a.dtype)
b +=a
print (b)
print (b.dtype)
In [64]:
a = np.ones(3, dtype=np.int32)
b = np.linspace(0,pi,3)
print (b.dtype.name)
c = a+b
print (c)
print (c.dtype.name)
d = np.exp(c*1j)
print (d)
print (d.dtype.name)
In [65]:
a=np.random.random ((2,3))
print(a)
b=a.sum()
print (b)
c=a.min()
print (c)
d=a.max()
print (d)
In [66]:
import numpy as np
b=np.arange (12).reshape(3,4)
print(b)
c=b.sum(axis=0)
print (c)
d=b.min (axis=1)
print (d)
e=b.cumsum (axis=1)
print (e)
In [67]:
B=np.arange(3)
print(B)
C=np.exp(B)
print(C)
D=np.sqrt(B)
print (D)
E=np.array([2.,-1.,4.])
print (np.add(B,E))
In [68]:
a = np.arange(10)**3
print (a)
print (a[2])
print (a[2:5])
a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
print (a)
print(a[ : :-1]) # reversed a
for i in a:
print(i**(1/3.))
In [70]:
def f(x,y):
return 10*x+y
b = np.fromfunction(f,(5,4),dtype=int)
print (b)
print (b[2,3])
print(b[0:5, 1]) # each row in the second column of b
print(b[ : ,1] ) # equivalent to the previous example
print (b[1:3, : ])
print (b[-1])
In [71]:
import numpy as np
c= np.array ([[[0,1,2],[10,12,13]],[[100,101,102],[110,112,113]]])
print (c.shape)
print (c[1,...])
print (c[...,2])
In [73]:
for row in b:
print (row)
for element in b.flat:
print(element)
In [86]:
import numpy as np
a=np.floor(10*np.random.random((3,4)))
print (a)
print (a.shape)
print (a.dtype)
print (a.ravel())
print(a.reshape(6,2))
print(a.T)
print(a.T.shape)
print (a)
print (a.resize((2,6)))
print (a)
print (a.reshape(3,-1))
In [88]:
import numpy as np
a=np.floor(10*np.random.random((2,2)))
print (a)
b=np.floor(10*np.random.random((2,2)))
print (b)
c=np.vstack((a,b))
print(c)
d=np.hstack((a,b))
print(d)
In [91]:
from numpy import newaxis
print (np.column_stack((a,b)))
a=np.array([4.,2.])
b=np.array([3.,8.])
print (np.column_stack((a,b)))
print(np.hstack((a,b)))
print (a[:,newaxis])
print (np.column_stack((a[:,newaxis],b[:,newaxis])))
print(np.hstack((a[:,newaxis],b[:,newaxis])))
print (np.r_[1:4,0,4])
In [93]:
a=np.floor(10*np.random.random((2,12)))
print(a)
print(np.hsplit(a,3))
print (np.hsplit(a,(3,4)))
In [94]:
a=np.arange (12)
b=a
print (b is a)
b.shape=3,4
print(a.shape)
In [95]:
def f(x):
print (id(x))
print (id (a))
print (f (a))
In [96]:
c=a.view()
print (c is a)
print (c.base is a)
print (c.flags.owndata)
c.shape =2,6
print (a.shape)
c[0,4]=1234
print (a)
In [97]:
s=a[ : , 1:3]
s[:]=10
print (a)
In [99]:
d=a.copy ()
print (d is a)
print (d.base is a)
d[0,0]=9999
print (a)
In [100]:
a=np.arange (12)**2
i=np.array([1,1,3,8,5])
print (a[i])
j=np.array ([[3,4],[9,7]])
print (a[j])
Friday, July 27, 2018
numpy codes_Session 6
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment