Dsa Lab File - 240410 - 163630
Dsa Lab File - 240410 - 163630
UNIVERSITY
DEPARTMENT OF ELECTRICAL
ENGINEERING
DSALABPRACTICALFILE
CHINMAY BANSAL
23/EE/312
EE-5
EXPERIMENT-1
>>> z=82
>>> z
82
>>> x=38+53
>>> y=x+z
>>> z=z+1
>>> x,y,z
(91, 173, 83)
>>> w=a+b
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
w=a+b
NameError: name 'a' is not defined
>>> type(7),type(3.5)
(<class 'int'>, <class
'float'>)
>>> x,y,z
(91, 173, 83)
>>> x<100
True
>>> not(z>500)
True
>>> mylist=[1,3.5,True]
>>> mylist
[1, 3.5, True]
>>>
mylist[1] 3.5
>>> mylist[1]=92
>>> mylist[1]
92
>>> mylist
[1, 92, True]
>>> mylist[3]=False
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
mylist[3]=False
IndexError: list assignment index out of range
>>> len(mylist)
3
>>> mylist[-
1] True
>>> mylist[-
3] 1
>>> mylist[-4]
Traceback (most recent call last):
File "<pyshell#36>", line 1, in
<module> mylist[-4]
IndexError: list index out of range
>>> 7+2.5
9.5
>>> 7*3.0
21.0
>>> 7/3,7//3,7%3
(2.3333333333333335, 2, 1)
>>> 7.0//3.0
2.0
>>> 2**3
8
>>> log(7),sqrt(2)
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
log(7),sqrt(2)
NameError: name 'log' is not defined
>>> m=2**83
>>> n=3**158
>>> p=m*n
>>> m,n,p
(9671406556917033397649408,
2427494450315468069358961833665581682507450011656
972431201424883184770261689,
2347728574366072763775480191674683606646202458034
9400025504000696264843872721743215364497913635930
112)
>>> x=7
>>> y=False
>>> z=True
>>> x and y,x and
True (False, True)
>>> x=7
>>> y=5
>>> x and y, not(x and
y) (5, False)
>>>
False*x 0
>>> len(x)
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
len(x)
TypeError: object of type 'int' has no len()
EXPERIMENT-2
>>> x=5
>>> type(x)
<class 'int'>
>>> x=False
>>> type(x)
<class 'bool'>
>>> def
square(x):
y=x*x
return(y)
>>> square(7)
49
>>> a=square(7)+32+square(71)
>>> a
5122
>>> y
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
y
NameError: name 'y' is not defined
>>> y=377
>>> square(8)
64
>>> y
377
>>> def
squaremod(x):
y=x*x
print(y)
>>>
squaremod(7) 49
>>>
a=squaremod(7)+32+square(73) 49
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
a=squaremod(7)+32+square(73)
TypeError: unsupported operand type(s) for +: 'NoneType'
and 'int'
>>> def
squaremod2(x):
y=x*x
print(y)
return(y)
>>>
squaremod2(9) 81
81
>>> a=squaremod2(7)+32+squaremod2(73)
49
5329
>>> a
5410
>>> def
average(a,b): c
= (a+b)/2
return(c)
>>> average(3.7,8.55)
6.125
>>> average(1)
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
average(1)
TypeError: average() missing 1 required positional argument:
'b'
>>> def
average3(a,b,c):
return((a+b+c)/3)
>>> average3(7,9,11)
9.0
>>> 9==9.0
True
>>> 0.1+0.2-0.3==0
False
>>> 0.1+0.2-0.3
5.551115123125783e-17
>>> l1=[1,2,3,4]
>>> l2=[5,6,7,8]
>>> l1+l2,l1,l2
([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4], [5, 6, 7, 8])
>>> l3=l1+l2
>>> l3,l1,l2
([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4], [5, 6, 7, 8])
>>> l1+7
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
l1+7
TypeError: can only concatenate list (not "int") to list
>>> 7+l1
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
7+l1
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> l3.append(9)]
SyntaxError: unmatched ']'
>>> l3.append(9)
>>> l3
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(l3.append(10))
None
>>> l3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> l3=l3.append(11)
>>>
print(l3)
None
>>> l3=l1+l2
>>> l3=l3+[9]
>>> l3
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def
belongs(v,l):
for x in l:
if x == v:
return(True)
return(False)
>>> belongs(8,l3),belongs(12,l3),belongs(8.2,l3)
(True, False, False)
>>>def locatepos(v,l):
pos = 0
for x in l:
if x == v:
return(pos)
pos = pos+1
return(-1)
>>> locatepos(8,l3),
locatepos(12,l3) (7, -1)
EXPERIMENT-3
range(7)
range(0, 7)
>>> for i in range(7):
print(i)
0
1
2
3
4
5
6
>>> l=range(7)
>>> type(l)
<class 'range'>
>>> l[2]
2
>>> l=list(range(7))
>>> l
[0, 1, 2, 3, 4, 5, 6]
>>> l=list(6)
Traceback (most recent call last):
File "<pyshell#128>", line 1, in <module>
l=list(6)
TypeError: 'int' object is not iterable
>>> def locatepos2(v,l):
for pos in
range(len(l)): if
l[pos] == v:
return(pos)
return(-1)
>>> locatepos2(8,l3), locatepos2(12,l3)
(7, -1)
>>> list(range(3,13))
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> list(range(3,13,5))
[3, 8]
>>> list(range(3,13,3))
[3, 6, 9, 12]
>>> list(range(10,5,-1))
[10, 9, 8, 7, 6]
>>> len(l3)
10
>>> list(range(len(l3)-1,-1,-1))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> list(range(len(l3)-1,-1,-3))
[9, 6, 3, 0]
>>> list(range(1.3,2.7,1))
Traceback (most recent call last):
File "<pyshell#140>", line 1, in <module>
list(range(1.3,2.7,1))
TypeError: 'float' object cannot be interpreted as an integer
>>>def factors(n):
for i in
range(1,n+1): if
n%i == 0:
factorlist.append(i)
return(factorlist)
>>> factors(10)
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
factors(10)
File "<pyshell#143>", line 4, in
factors factorlist.append(i)
NameError: name 'factorlist' is not defined
>>> def
factors(n):
factorlist = []
for i in
range(1,n+1): if
n%i == 0:
factorlist.append(i)
return(factorlist)
>>> factors(10)
[1, 2, 5, 10]
>>> def
primesupto(m):
primelist = []
for i in range(1,m+1):
if isprime(i):
primelist.append(i)
return(primelist)
>>> primesupto(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> primesupto(10000)[-1]
9973
>>> def
firstmprimes(m):
count = 0
primelist = []
i=1
while(count < m):
if isprime(i):
primelist.append(i)
count = count + 1
i=i+1
return(primelist)
>>> firstprimes(20)
Traceback (most recent call last):
File "<pyshell#161>", line 1, in <module>
>>> firstmprimes(20)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71]
>>>l = [1,2,3,4,5,6,7,8]
len(l), sum(l), max(l), min(l)
>>>def
findcommon(l1,l2)
: commonlist = []
for x in l1:
for y in l2:
if x ==
y: commonlist.append(x)
return(commonlist)
>>>l1 = [1,2,3,4]
>>>l2 = [3,4,5,6]
>>>findcommon(l1,l2)
[3,4]
>>>l1 = [1,2,3,4]
>>>l2 = [3,4,5,3]
>>>findcommon(l1,l2)
[3,3,4]
>>>for i in range(1000):
for j in range(1000):
x=i+j
print("Done")
Done
>>>for i in range(10000):
for j in range(10000):
x=i+j
print("Done")
Done
EXPERIMENT-4
>>> def
findcommon(l1,l2):
commonlist = []
for x in l1:
for y in l2:
if x == y:
commonlist.append(x)
return(commonlist)
>>> l1=[1,2,3,4]
>>> l2=[3,4,5,6]
>>> findcommon(l1,l2)
[3,4]
>>> l1 = [1,2,3,4]
>>> l2 = [3,4,5,3]
>>> findcommon(l1,l2)
[3,4,3]
>>> l1 = [1,2,3,4,3]
>>> l2 = [3,4,5,3]
>>> findcommon(l1,l2)
[3,3,4,3]
>>>def duplicates(l):
for i in range(len(l)):
for j in
range(i+1,len(l)): if
l[i] == l[j]:
return(True)
return(False)
>>>
duplicates([1,2,3])
False
>>>
duplicates([1,2,1])
True
>>>def duplicatelist(l):
dlist = []
for i in range(len(l)):
for j in
range(i+1,len(l)): if
l[i] == l[j]:
def duplicatelist(l):
return(dlist)
>>>duplicatelist([1,2,1])
[1]
>>>duplicatelist([1,2,1,3,1])
[1,1,1]
>>>1 in [1,2,3,4]
True
>>def listcommon2(l1,l2):
for x in l1:
if x in l2:
return(True)
return(False)
>>> def sgn1(v):
if v > 0: # First check positive or not
return(1)
else:
if v < 0: # Then check zero or
negative return(-1)
else:
return(0)
>>> l = list(range(100))
>>> l[2:20]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l[20:20],l[23:22]
([], [])
>>> l[:20],l[84:]
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19], [84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 9
EXPERIMENT-5
>>>for k in marks:
print(k,marks[k])
Physics 75
Maths 88
>>> for k in
marks:
print(k)
Physics
Maths
>>> for k in
marks.values():
print(k)
75
88
>>> sorted([3,1,8,2,9])
[1, 2, 3, 8, 9]
>>> l = [3,1,8,2,9]
>>>
sorted(l) [1,
2, 3, 8, 9]
>>> l
[3, 1, 8, 2, 9]
>>> sorted(["A",2])
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
sorted(["A",2])
TypeError: '<' not supported between instances of 'int' and
'str'
>>> sorted(["B","A"])
['A', 'B']
>>> sorted(["1","2","3","10"])
['1', '10', '2', '3']
>>>totalruns = {}
>>> for p in runlist:
name = p[0]
runs = p[1]
if name in totalruns: totalruns[name]=totalruns[name]
+runs
else:
totalruns[name] = runs
>>> totalrunlist = {}
>>> for p in runlist:
name = p[0]
runs = p[1]
if name in totalrunlist:
totalrunlist[name]=totalrunlist[name]+[runs]
else:
totalrunlist[name] = [runs]
>>>x=input()
3443
>>>x,type(x)
(‘3443’,str)
>>>list(range(10)),range(10)
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], range(0, 10))
>>>int(x),x
(3443,’3443’)
>>>str(7888)
‘7888’
>>>int(“abcd”)
>>>int("abcd",16)
43981
>>>list(7)
>>>list((7,8))
[7,8]
>>>x=float(x)
x
343.0
>>>for k in marks.keys():
print(k, marks[k])
Physics 75
Maths 88
>>>for k in marks.keys():
print(k, marks[k], sep=":")
Physics:75
Maths:88
>>>for k in marks.keys():
print(k, marks[k], sep=":",end="")
print()
Physics:75
Maths:88
>>> count = 0
marksdict =
{} namelist =
[]
>>>(count,marksdict,namelist) = (0,{},[])
>>>(m,n)=swap(m,n)
>>>m,n
(10,5)
>>>m,n=5,10
>>>m,n=n,m
>>>m,n
(10,5)
>>> totalrunlist = {}
>>>for (name,runs) in runlist:
if name in
totalrunlist:
totalrunlist[name]=totalrunlist[name]+[runs
else:
totalrunlist[name]=[runs]
>>>totalrunlist
{'A': [10, 44], 'C': [20], 'B': [33, 77]}
>>>y=17
>>>x=y
>>>x=15
>>>y
17
>>>l1=[1,2,3]
>>>l1=l2
>>>l2[0]=4
>>>l1,l2
([4, 2, 3], [4, 2, 3])
>>>marks
{'Physics': 75, 'Maths': 88}
>>>newmarks = marks
>>>newmarks['Maths'] = 100
>>>marks, newmarks
({'Physics': 75, 'Maths': 100}, {'Physics': 75, 'Maths': 100})
>>> p1 = (5,2,3)
>>>p2 = p1
>>>p1, p2
((5, 2, 3), (5, 2, 3))
>>>p2[1] = 7
>>>p2=(7,9,4)
>>>p1,p2
((5, 2, 3), (7, 9, 4))
>>>l3 = l1[:]
>>>l1,l3
([4, 2, 3], [4, 2, 3])
>>>l3[0] = 17
>>>l1,l3
([4, 2, 3], [17, 2, 3])
>>> zeros = [0,0,0]
>>>zeromat = [zeros,zeros,zeros]
>>>zeros, zeromat
([0, 0, 0], [[0, 0, 0], [0, 0, 0], [0, 0, 0]])
>>>zeromat[1][1]=1
>>>zeros,zeromat
([0, 1, 0], [[0, 1, 0], [0, 1, 0], [0, 1, 0]])
>>>zeros = [0,0,0]
>>>zeromat2 = [zeros[:],zeros[:],zeros[:]]
>>>zeros, zeromat2
([0, 0, 0], [[0, 0, 0], [0, 0, 0], [0, 0, 0]])
>>>zeromat2[1][1] = 1
>>>zeros, zeromat2
([0, 0, 0], [[0, 0, 0], [0, 1, 0], [0, 0, 0]])
EXPERIMENT-6
>>>import time
>>>start=time.perf_counter()
l = []
for i in range(10000000):
l.append(i)
elapsed = time.perf_counter() - start
print(elapsed)
5.1879789797968676
>>> start =
time.perf_counter() l = []
for i in range(20000000):
l.append(i)
elapsed = time.perf_counter() -
start print(elapsed)
7.7535647355536674
>>>start =
time.perf_counter() l = []
for i in
range(100000):
l.insert(0,i)
elapsed = time.perf_counter() -
start print(elapsed)
7.6575684875478575
>>> start =
time.perf_counter() l = []
for i in
range(200000):
l.insert(0,i)
elapsed = time.perf_counter() - start
print(elapsed)
32.548568548757565
>>>start =
time.perf_counter() l = []
for i in range(300000):
l.insert(0,i)
elapsed=time.perf_counter() –
start print(elapsed)
5.6886685757744854
>>> start =
time.perf_counter() d = {}
for i in range(20000000,0,-
1): d[i] = i
elapsed = time.perf_counter() -
start print(elapsed)
7.54848548484839849
>>> def
createlist():
return({})
>>> def
listappend(l,x): if l
== {}:
l["value"] =
x l["next"] =
{} return
node = l
while node["next"] != {}:
node = node["next"]
node["next"]["value"] = x
node["next"]["next"] = {}
return
>>> def
listinsert(l,x): if l
== {}:
l["value"] =
x l["next"] =
{} return
newnode = {}
newnode["value"] = l["value"]
newnode["next"] = l["next"]
l["value"] = x
l["next"] = newnode
return
20.64044039999999
{'value': 0, 'next': {'value': 1, 'next': {'value': 2, 'next': {'value':
3, 'next': {'value': 4, 'next': {'value': 5, 'next': {'value': 6, 'next':
{'value': 7, 'next': {'value': 8, 'next': {'value': 9, 'next':
{}}}}}}}}}}}
>>> start =
time.perf_counter() l =
createlist()
for i in
range(1000000):
listinsert(l,i)
elapsed = time.perf_counter() -
start print(elapsed)
5.28938934848484848
>>>start =
time.perf_counter() l =
createlist()
for i in range(2000000):
listinsert(l,i)
elapsed = time.perf_counter() -
start print(elapsed)
8.4949438348448484
>>> start =
time.perf_counter() l =
createlist()
for i in range(10000):
listappend(l,i)
elapsed = time.perf_counter() - start
print(elapsed)
10.575747474747547
>>>start =
time.perf_counter() l =
createlist()
for i in range(5000):
listappend(l,i)
elapsed =
time.perf_counter()
print(elapsed)
5.3393939394959589
>>> evensqlist = []
>>> for i in range(20):
if i % 2 == 0:
evensqlist.append(i*i)
print(evensqlist)
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
>>> def even(x):
return(x%2 == 0)
>>> def odd(x):
return(not(even(x)))
>>> def
square(x):
return(x*x)
>>> N = 20
>>> l1 = list(range(N))
>>> l2 = list(filter(odd,l1))
>>> l3 = list(map(square,l1))
>>> l4 = list(map(square,filter(even,l1)))
>>> l1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l2
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> l3
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225,
256, 289, 324, 361]
>>> l4
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
>>> N=20
>>> triples=[]
>>> for x in range(1,N+1):
for y in
range(x,N+1):
for z in range(y,N+1):
if x*x + y*y == z*z:
triples.append((x,y,z))
>>> triples
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16,
20)]
>>> N=20
>>> [(x,y,z) for x in range(1,N+1) for y in range(x,N+1) for z in
range(y,N+1) if x*x + y*y ==z*z]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16,
20)]
EXPERIMENT-7
>>>a = np.array([1,2,3])
>>>a,
print(a) [1 2
3]
(array([1, 2, 3]), None)
>>>a=np.array((1,2,3))
>>>a
Array([1,2,3])
>>> b = np.array(range(10))
>>>b
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>c = np.array([1,"abc"])
>>>c
array(['1', 'abc'], dtype='<U21')
>>>c = np.array([(0,1,0),[2,3,2]])
>>>c
array([[0, 1, 0],
[2, 3, 2]])
>>>d = np.array([(0,1,0),range(3)])
>>>d
array([[0, 1, 0],
[0, 1, 2]])
>>>cproblem = np.array([(0,1),[2,3,2]])
/tmp/ipykernel_74734/1811570240.py:1:
VisibleDeprecationWarning: Creating an ndarray from ragged
nested sequences (which is
a list-or-tuple of lists-or-tuples-or ndarrays with different
lengths or shapes) is deprecated. If you meant to do this, you
must specify 'dtype=object' when creating the ndarray.
cproblem = np.array([(0,1),[2,3,2]])
>>> d = np.array([[(0,1,0),[2,3,2]],[[4,5,4],[6,7,6]]])
>>>d
array([[[0, 1, 0],
[2, 3, 2]],
[[4, 5, 4],
[6, 7, 6]]])
>>>a**3
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
>>>a+
array([ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>>3*a
array([ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27])
>>> 3+a
array([ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>>a-3, 3-a
(array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]),
array([ 3, 2, 1, 0, -1, -2, -3, -4, -5, -6]))
>>>a**3
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
>>>l = list(range(10))
>>>3+l
>>> b = np.fromfunction(f,(5,4),dtype=int)
>>>b
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
>>>print(b)
[[ 0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]]
>>> a = np.zeros((5,7))
>>>a
array([[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.]])
>>> a = np.zeros((5,7),dtype=int)
>>>a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>>a = np.random.random((5,7))
>>>a
array([[0.88213435, 0.16971307, 0.01241608, 0.76046308,
0.02927208,
0.22720506, 0.28021178],
[0.96245736, 0.89094659, 0.96283773, 0.76684503,
0.53365983,
0.51587229, 0.08982928],
[0.33130589, 0.52477119, 0.87205957, 0.33691265,
0.26971441,
0.85020038, 0.90909779],
[0.1431626 , 0.68307767, 0.48676025, 0.52794108,
0.68903994,
0.80502854, 0.01381994],
[0.73000794, 0.38163447, 0.55841497, 0.58133621,
0.73888899,
0.36052911, 0.66850846]])
>>>a = np.random.random((5,7))*10-5
>>>a
array([[ 4.96844914, -3.26404413, 3.56921996, -4.27737971,
-2.39299866,
-1.86906705, -0.34227678],
[ 0.01990647, 4.65734971, 3.60619785, -4.67756946, -
1.45417392,
-3.94531739, -1.80933633],
[ 0.74350601, -1.43335638, -1.89663478, 0.88976024, -
4.10888142,
4.01583694, 0.74279047],
[-0.79795651, 0.10458986, -2.65581491, 2.96077438, -
1.97117565,
-4.97546063, -1.34820046],
[ 1.51616659, -2.91947874, 4.1861112 , 2.91955603,
3.1778907 ,
0.96577325, -4.20250544]])
EXPERIMENT-8
>>>class Point:
def init (self,a,b):
self.x=a
self.y=b
def translate(self,deltax,deltay):
self.x+=deltax # Same as self.x = self.x deltax
# In general, if we have a = a op b for any arithmetic
operation op, can write a op= b
# For example: a += 5 is a = a + 5, a -= 10 is a = a - 10 etc
self.y+=deltay
def odistance(self):
import math
d = math.sqrt(self.x*self.x+self.y*self.y)
return(d)
>>>p=Point(3,4)
>>>q=Point(7,10)
>>>p.odistance(),q.odistance()
(5.0, 12.206555615733702)
>>>p.translate(3,4)
>>>p.odistance()
10.0
>>>print(p)
>>>print(p+q)
>>>p<q
>>> import math
class Point:
def init (self,a,b):
self.r = math.sqrt(a*a +
b*b) if a == 0:
if b >= 0:
self.theta =
math.pi/2 else:
self.theta =
3*math.pi/2 else:
self.theta = math.atan(b/a)
def translate(self,deltax,deltay):
x=self.r*math.cos(self.theta)
y=self.r*math.sin(self.theta)
x+=deltax
y+=deltay
self.r = math.sqrt(x*x +
y*y) if x == 0:
if y >= 0:
self.theta =
math.pi/2 else:
self.theta =
3*math.pi/2 else:
self.theta = math.atan(y/x)
def odistance(self):
return(self.r)
>>> p = Point(3,4)
>>>q = Point(7,10)
>>>p.odistance(), q.odistance()
(5.0, 12.206555615733702)
>>>p.translate(3,4)
>>>p.odistance()
10.0
>>> print(p)
>>>print(p+q)
>>> p = Point(3,4)
>>>q = Point(7,10)
>>>p.odistance(), q.odistance()
(5.0, 12.206555615733702)
>>>p.translate(3,4)
>>>p.odistance()
10.0
>>>
print(p)
(6,8)
>>>str(p)
‘(6,8)’
>>>print(p+q)
(13,18)
>>> print(p,q)
(6,8) (7,10)
>>>p<q
TypeError Traceback (most recent call
last) Cell In [21], line 1
----> 1 p < q
TypeError: '<' not supported between instances of 'Point' and
'Point'
>>>class Point:
def init (self,a,b):
self.x = a
self.y = b
def translate(self,deltax,deltay):
self.x += deltax
self.y += deltay
def odistance(self):
import math
d = math.sqrt(self.x*self.x+self.y*self.y)
return(d)
def str (self):
return('('+str(self.x)+','+str(self.y)+')')
def add (self,p):
return(Point(self.x+p.x,self.y+p.y))
def lt (self,p):
return(self.x<p.x and self.y<p.y)
>>> p = Point(3,4)
>>>q = Point(7,10)
>>>p < q, q < p
(True,False)
>>> Point.translate(p,9,10)
>>>print(p)
(12,14)
>>>l = [1,2,3]
>>>list.append(l,4)
>>>l
[1,2,3,4]
>>>p.x,
p.y (12,14)
>>>class Experiment3:
def init (self,a):
self.x = a
def str (this):
return(str(this.x))
>>>x = Experiment3(17)
>>>print(x)
17
EXPERIMENT-9
>>> class Node:
def init (self,v=None):
self.value=v
self.next=None
return
def isempty(self):
if self.value==None:
return(True)
else:
return(False)
def append(self,v):
if self.isempty():
self.value=v
elif self.next==None:
self.next=Node(v)
else:
self.next.append(v)
return
def appendi(self,v):
if self.isempty():
self.value=v
return
temp=self
while temp.next!=None:
temp=temp.next
temp.next=Node(v)
return
def insert(self,v):
if self.isempty():
self.value=v
return
newnode=Node(v)
(self.value,newnode.value)=(newnode.value,self.value)
(self.next,newnode.next)=(newnode, self.next)
return
def delete(self,v):
if
self.isempt
y(): return
if self.value == v:
self.value = None
if self.next != None:
self.value =
self.next.value self.next =
self.next.next
else: return
if self.next != None:
self.next.delete(v)
if self.next.value ==
None: self.next =
None
return
temp = self
selflist.append(temp.value)
>>> l=Node()
>>> l.append(5)
>>>
print(l) [5]
>>> l.append(7)
>>> print(L)
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
print(L)
NameError: name 'L' is not defined
>>>
print(l) [5,
7]
>>> l.append(9)
>>>
print(l) [5,
7, 9]
def isempty(self):
if self.value==None:
return(True)
else:
return(False)
def append(self,v):
if self.isempty():
self.value=v
elif self.next==None:
self.next=Node(v)
else:
self.next.append(v)
return
def appendi(self,v):
if
self.isempty():
self.value=v
return
temp=self
while temp.next!=None:
temp=temp.next
temp.next=Node(v)
return
def insert(self,v):
if self.isempty():
self.value=v
return
newnode=Node(v)
(self.value, newnode.value)=(newnode.value,
self.value)
(self.next, newnode.next)=(newnode, self.next)
return
def delete(self,v):
if
self.isempt
y(): return
if self.value==v:
self.value=None
if self.next!=None:
self.value=self.next.value
self.next=self.next.next
return
else:
if self.next!=None:
self.next.delete(v)
if self.next.value==None:
self.next=None
return
def _tolist(self):
if self.isempty():
return([])
elif self.next==None:
return([self.value])
else:
return([self.value]+self.next._tolist())
100000 0.18746390000001156
200000 0.5090372000000798
300000 0.7805974000000333
400000 1.1666528999999173
>>> for i in
range(1,5): l2 = []
start=time.perf_counter()
for j in range(i*50000):
l2.insert(0,j)
elapsed=time.perf_counter()-start
print(i*50000,elapsed)
50000 1.0172062000000324
100000 4.009719799999971
150000 9.315534400000047
200000 19.403902500000072
EXPERIMENT-10
>>> import time
>>> def naivesearch(v,l):
for x in l:
if v==x:
return(True)
return(False)
>>> l=list(range(0,51,2))
>>>l = list(range(0,200000,2))
starttime = time.perf_counter()
for i in range(3001,23000,2):
v = naivesearch(i,l)
elapsed = time.perf_counter() -
starttimeprint()
print("Naive search", elapsed)
starttime = time.perf_counter()
for i in range(3001,23000,2):
v = binarysearch(i,l)
elapsed = time.perf_counter() -
starttimeprint()
print("Binary search", elapsed)
>>>def SelectionSort(L):
n=len(L)
if n<1:
return(L)
for i in range(n):
# Assume L[:i] is sorted
mpos=i
# mpos is position of minimum in L
for j in range(i+1,n):
if L[j]<L[mpos]:
mpos=j
# L[mpos] is the smallest value in L[i:]
(L[i],L[mpos])=(L[mpos],L[i])
# Now L[:i+1] is sorted
return(L)
>>>import random
>>>random.seed(2023)
inputlists={}
inputlists["random"]=[random.randrange(100000)
for i in range(5000)]
inputlists["ascending"] = [i for i in
range(5000)]
inputlists["descending"] = [i for i in range
(4999,-1,-1)]
for k in inputlists.keys():
tmplist=inputlists[k][:]
starttime=time.perf_counter()
SelectionSort(tmplist)
elapsed=time.perf_counter()-starttime
print(k,elapsed)
random 0.6429454580065794
ascending 0.6363217170001008
descending 0.6335939559940016
>>>def InsertionSort(L):
n=len(L)
if n<1:
return(L)
for i in range(n):
# Assume L[:i] is sorted
# Move L[i] to correct position in L[:i]
j=i
while(j > 0 and L[j]<L[j-1]):
(L[j],L[j-1])=(L[j-1],L[j])
j=j-1
# Now L[:i+1] is sorted\
return(L)
>>>import random
>>>random.seed(2023)
>>>inputlists = {}
>>>inputlists["random"] =
[random.randrange(100000) for i in
Range(5000)]
>>>inputlists["ascending"] = [i for i in
range(5000)]
>>>inputlists["descending"] = [i for i in range
(4999,-1,-1)]
>>>for k in inputlists.keys():
tmplist = inputlists[k][:]
starttime = time.perf_counter()
InsertionSort(tmplist)
elapsed = time.perf_counter() – starttime
print(k,elapsed)
random 1.1455828940088395
ascending 0.00039821400423534214
descending 2.23140712500026
>>>def Insert(L,v):
n=len(L)
if n==0:
return([v])
if v>=L[-1]:
return(L+[v])
else:
return(Insert(L[:-1],v)+L[-1:])
>>>def ISort(L):
n=len(L)
if n<1:
return(L)
L=Insert(ISort(L[:-1]),L[-1])
return(L)
>>>import random
>>>random.seed(2023)
>>>inputlists={}
>>>inputlists["random"]=[random.randrange(1000
00) for i in range(2000)]
>>>inputlists["ascending"]=[i for i in range(2000)]
>>>inputlists["descending"]=[i for i in range (1999,-
1,-1)]
>>>for k in inputlists.keys():
tmplist=inputlists[k][:]
starttime=time.perf_counter()
ISort(tmplist)
elapsed=time.perf_counter() - starttime
print(k,elapsed)
>>>import random
>>>random.seed(2023)
>>>inputlists = {}
>>>inputlists["random"] =
[random.randrange(100000) for i in
range(2000)]
>>>inputlists["ascending"] = [i for i in
range(2000)]
>>>inputlists["descending"] = [i for i in range
(1999,-1,-1)]
>>>for k in inputlists.keys():
tmplist = inputlists[k][:]
starttime = time.perf_counter()
ISort(tmplist)
elapsed = time.perf_counter() - starttime
print(k,elapsed)
random 5.81613647499762
ascending 0.017258646999835037
descending 10.139818099996774
>>>def merge(A,B):
(m,n) = (len(A),len(B))
(C,i,j,k) = ([],0,0,0)
while k < m+n:
if i == m:
C.extend(B[j:])
k = k + (n-j)
elif j == n:
C.extend(A[i:])
k = k + (n-i)
elif A[i] < B[j]:
C.append(A[i])
(i,k) = (i+1,k+1)
else:
C.append(B[j])
(j,k) = (j+1,k+1)
return(C)
def mergesort(A):
n = len(A)
if n <= 1:
return(A)
L = mergesort(A[:n//2])
R = mergesort(A[n//2:])
B = merge(L,R)
return(B)
>>>def binarysearchiterative(v,L):
if len(L)==0:
return(True)
left=0
right=len(L)
while (right-left>0):
mid=(left+right)//2
if v==L[mid]:
return(True)
if v<L[mid]:
right=mid
else:
left=mid+1
return(False)
0 True
3 False
6 True
9 False
12 True
15 False
18 True
21 False
24 True
27 False
30 True
33 False
36 True
39 False
42 True
45 False
48 True
51 False
54 False
57 False
>>>l = list(range(0,200000,2))
>>>starttime = time.perf_counter()
>>>for i in range(3001,23000,2):
v = binarysearchiterative(i,l)
>>>elapsed = time.perf_counter() - starttime
>>>print()
>>>print("Binary search", elapsed)