From e2281980a07df3bd5982d4f51c7f78b8ddda6f89 Mon Sep 17 00:00:00 2001 From: Bibek Jyoti Charah Date: Thu, 10 Oct 2024 12:33:46 +0530 Subject: [PATCH 1/4] Added matrix operations --- .../__pycache__/adjoint.cpython-312.pyc | Bin 0 -> 1590 bytes .../__pycache__/checker.cpython-312.pyc | Bin 0 -> 4441 bytes .../__pycache__/cofactor.cpython-312.pyc | Bin 0 -> 1477 bytes .../__pycache__/determinant.cpython-312.pyc | Bin 0 -> 2411 bytes .../__pycache__/minor.cpython-312.pyc | Bin 0 -> 1877 bytes .../__pycache__/transpose.cpython-312.pyc | Bin 0 -> 1681 bytes Matrix Operations/addition.py | 56 ++++++++ Matrix Operations/adjoint.py | 49 +++++++ Matrix Operations/checker.py | 131 ++++++++++++++++++ Matrix Operations/cofactor.py | 74 ++++++++++ Matrix Operations/determinant.py | 61 ++++++++ Matrix Operations/input.py | 59 ++++++++ Matrix Operations/inverse.py | 48 +++++++ Matrix Operations/matrix.py | 60 ++++++++ Matrix Operations/minor.py | 54 ++++++++ Matrix Operations/multiplication.py | 106 ++++++++++++++ Matrix Operations/readme.md | 107 ++++++++++++++ Matrix Operations/rotate.py | 59 ++++++++ Matrix Operations/subtraction.py | 57 ++++++++ Matrix Operations/sum.py | 105 ++++++++++++++ Matrix Operations/swap.py | 68 +++++++++ Matrix Operations/transpose.py | 62 +++++++++ 22 files changed, 1156 insertions(+) create mode 100644 Matrix Operations/__pycache__/adjoint.cpython-312.pyc create mode 100644 Matrix Operations/__pycache__/checker.cpython-312.pyc create mode 100644 Matrix Operations/__pycache__/cofactor.cpython-312.pyc create mode 100644 Matrix Operations/__pycache__/determinant.cpython-312.pyc create mode 100644 Matrix Operations/__pycache__/minor.cpython-312.pyc create mode 100644 Matrix Operations/__pycache__/transpose.cpython-312.pyc create mode 100644 Matrix Operations/addition.py create mode 100644 Matrix Operations/adjoint.py create mode 100644 Matrix Operations/checker.py create mode 100644 Matrix Operations/cofactor.py create mode 100644 Matrix Operations/determinant.py create mode 100644 Matrix Operations/input.py create mode 100644 Matrix Operations/inverse.py create mode 100644 Matrix Operations/matrix.py create mode 100644 Matrix Operations/minor.py create mode 100644 Matrix Operations/multiplication.py create mode 100644 Matrix Operations/readme.md create mode 100644 Matrix Operations/rotate.py create mode 100644 Matrix Operations/subtraction.py create mode 100644 Matrix Operations/sum.py create mode 100644 Matrix Operations/swap.py create mode 100644 Matrix Operations/transpose.py diff --git a/Matrix Operations/__pycache__/adjoint.cpython-312.pyc b/Matrix Operations/__pycache__/adjoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a3a9adae5ee24cf13e8ef7ef9dd1b82e2fc7a74 GIT binary patch literal 1590 zcmbVM&5ImG6tC*;o#~nEuEvPT20}^$aXakpxCuG97$Ha&JS4#=g0n20qPu3M-ToM> zs?DxuVGarbFChqf4Y`H<5%~kWh(XXMIeD7fn$=4{;(OISv$Gpd7SyX(uj>8YXVp(L zGfe{H@jtchw+qkrgDXvTD9kFT$`>9h$jW}Q5=h$E6LzZ?1wE#Pf{-Q?HgW>6u59w8ABz>R z!$!VbVry&53v3bQ`Sk_1c7B0fSYQ{C1<`x3TVFT#55;I?XV~>zLm(yM8Gw4F#7*hpI57cP?u#F+5kBmRf*^0NNMaaT$P6nA*!O6H=rDN z{YF{+ef6SoUJ6)yopmQankvS|4ShP_3)wyS&~PlH&_jt;+4C{#H@1 zc-a8;Ihg7MkOBGYB$++_qcK(F*$wuuUi0f{xk&z9Ql|*F1ZO;S68G7~;R@*>V;IXljVjgJ2pKiHGtv z6j&w%i8nl}ph;1aLglemc!e?P!csW+GUYK~&%soufec8|ICk%g2aTWIbA!uIXWqQ~ z$q((p>Qm?SyKnvKoRIh-7p@OaAxeG!n&%dE-w(6E_ltVa6Tya%#;B=BSsBcwF@kz2 zPlWG3BnHTM@xuL}{5L+7m~o6$T>!FcQ%e7|j#B6EvxL6=jGTH#PCu{B(l?&JW7E0a YY2r-Z`Q{gU?sv!ies$L-&PfCMFCx*aE&u=k literal 0 HcmV?d00001 diff --git a/Matrix Operations/__pycache__/checker.cpython-312.pyc b/Matrix Operations/__pycache__/checker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4ca6adf3bad39b9cd315ecab16969bb708b6331 GIT binary patch literal 4441 zcmdUyO>7fK6o6-T*Rj2Eew-g5fl3odMU32}`Qf)f6$+_ZsZ^ywEzro?csI!w?>d>a zAx2J>Ly-(lB~y?HY7Y_Wp(s7{*h3G!^-!s*lC%OVxAu}-8aQ$4n^~`S9UMqeFI{Qh z&d$7fJD&H=d(Xer)yW91o76x4a|oe7*^6@trN-kSXxv3Ax`XcAVpOI zDXBh?KD7p9jpkSVm%9+60Rd?>izOo%WdfN%B&Zw#v-0qSZjniv9H)vw;z={5=%z)+ z(q=rRC!v)}k}FC=SCy1T6k;eTs!vBrd_s#~Ci)mjT}|4Zam|wBib+O6O;t6OBq=e{ ziIhH>&^0wm6jOC)Ife*)+nP!%RO=@1q==HRlI1nXN_iD*5tCFmL8G*SZdpDvtr(LD z?U+p9GJ44ga_LfUl=MYO|45Wv8i#jJ`;OFSUxMv!!u`x#xxI_U3jO{aagfR0g~%rG9q|xEm}^@`OhERH9I-WEhu&7#U3_6EKgaHD|f*Lipq;8G;j}kt8gVUeztFn=fUJZTHY{L@0_0%`Ez;VvcJO zv51W#Hj7xdm`h-hPrG|2l7`k}DTa~hc`K=ER?mC>Cb^B0$WCIDlwj5rqtO%C1r~xzNRs)#a{lfGooT12yw%F5JF3TD+5m(5 znfe3>8{u8^!g65uQlS5vhVO-C(*J{R$$#QuL(6KQHg_uTpB;P{2+n<2Xv%+dGsL>< znhL%7j~&EA4F#dld&`%9_v?N0qYL4C+E)jbL!A|@(^~jg1?z0Fob@Zv_-|NOE8^$O z3yA0Obo^zQbTX9Y1hRhvrkOTIH3|V0%78@Lfcis$5(GjeM~@>^3VIVTK$BPhCjh&f zvK7UYxqJA5;Gzsz*FhhxXM%C;1Ztb$-4z5oAF%5J+63w>2wTTN0LFVz@VOZ0rf!_c z%bQVtSleKuSqiUU%aiOsftTuNz987*Y()^R1k(w*48UtYagSGKb2lP7#h|B(eA(p7 zjh2bsMwD_>uU$Vq->ozZdleBVOJTMvSz>cyQFDbSZF{r@6wbqK^??8nwxGby!ql?A zZT|d{e{U)L4CZSbpM@dFwB#?`tcRhheq#jjkn$rmyngefsd7T}B)K;r$zit;^J-@+ ziaXC7yLfYxCbBi{5>Cb635%t~j?vss3AyRj{f{ztqIy5)B3FeAUM#yM9??x6I8qul zbW=%?G5AA5HAPiM^@N_vymXz$zr#>r$>b>}5nL2CQ#}jEmHl9zg^E6|1zp_ZEdLbo zrel{w>yOaBbrA;s3eufJ`dWUyYo$^}&v&i7sTyo&E* zkOG$?NO7imFVlKfSE$-6ZpDtnfWwWqaC3>s0z1#uWL)#hEzPQ0boE4M+_{2bQe5$iNOOj zKjV~nJ|elH9?F(}xCb^BERq3#%;|nmPQz_|24WT!<>oIh+zgMmS%#SY19V^n_&2No`rWL7WRf6a5QVZv)7>EJE zx*3a|jRcDRSWHdEV=+62u~KT&@8s)eb4;j0W3dN_8{zrvY2dh#RMQFVB#pvEwz)ic z0n8ZxEi__jqce;fH@aFuyxt5V+5n=n7Kb+W$hdXA9Z8|wwI#9bkrcQ-v@Rm4om>A0 DyvH70 literal 0 HcmV?d00001 diff --git a/Matrix Operations/__pycache__/cofactor.cpython-312.pyc b/Matrix Operations/__pycache__/cofactor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72359c94408d2cb5d893b928ece7a1a762e57389 GIT binary patch literal 1477 zcmZ`(&2QsW5TEC-IIYv&E|8`T+dkM!EkQ#iw1*0iDj*Uo=psNYRG`R;UsG>mJAHP5 zRtd@hq)5x55{JUAa4PDR1OEdTN>y#K+7qX6iqbvx0`nX@U0^%1=gqvC`OVDx`Zbpu z1Eeo6wAzUV@TX8xk`m$kT@-e~2AkBuC98x8S*lB}v?|52T$f#WRVI)HTlorB6|^XmH01E3OrC=L^(T*YSLg!nn;s#!<7puu76> zF=X(U@jw3y*)D`5TMG^nxlL-&mO|kbQ;VdQH{jEI0BsrV$`$sP(XNK-C>C0BOFc-i z+L}#-zK!N>9Uv6d#MIK#9NQS%&a{;K+0=G9wlb*~fp2ar(2}0$r99^KvG95yOv#$Z z_QojE2kTBi*P326bbOD7)&>ixMTcuht$;dSqZv}mvngj`lY2N52DIw0S=G?ziQ~dp zjJ3>b!BQ*<B9&WSjd2C{fs2ieG^^2I zo^9%pHtZ)NUUV(3G&zkCaUx?h$NkSEaz8TS^O<@~jLe^jS_3>0AhHX(D3#WImz4s` zb+<~d`!)+o@5INP-fb{$iMPvnkTtsH2jiXPlYF6b z_cV87XYs*D1JKkLyX0hQx@(+H=65!~Eet@;zSLblEz-UG{^b7hQE{RB_Q~9Hdz<@< zKQzDhe=h#=$M~*Bl|jJ3lH_#Lw)wU*0KIVKZhCm z*TE?Mrp%mUEl?FKC9$C5Vw{(e?LrOTh#&Fl*;3497M nGq}}PW{5IaDv;vfc9u-{3!oU??ce3;KNS7za$g2zCWib6a!+MV literal 0 HcmV?d00001 diff --git a/Matrix Operations/__pycache__/determinant.cpython-312.pyc b/Matrix Operations/__pycache__/determinant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cb070cbb8f8a9bfd362234e8b132cba43810c5c GIT binary patch literal 2411 zcma)7U2GIp6ux(6_NPst zx0a*{8ry`#HAZRQc%-Q&JVN3Fk0!os*^=N|pM0@zNHxJesOR39*-nv2b4LSFjkXmfEkvSF^Od z)~~@_^aFpu%PX;a%HPKHpDrye&ak~(;Lsg}SVl(^uDaxzA( zg78H>aBY(-j1*jEh@A}Prnw0du#xWj-R~01v>7b(IJMo3!(kqfCCTXxmiy3rpsr($ z(JQ89dPNCTcZ;sa@?so#WTOS?%k3bhJ;u0aHkb$J>LAnxY;d$O$13ERJcMay^$bmW z4j0~pa$}5sOkNDGu+KP_<&1-$dZ@c~{SX;$2yeR|fy8h(kx2@ZLOgnniFo>YLS2AA zQt%{F&b$JLyqTV>lg4BP2@1ea%Z0>-=@za`y9R}f=gf4Dc+B;H054=UL;?OjnxOd+ zi*>_BBn0yT85lU+LAr)I$Us*Id4Fg~YBxBRoZm~%6+FP+O^)jNsvu|rS6@x%So&JZ zKVHg(EOFKg^AVt(!_zq6vG~N{RpDLR4YOZBiFh^bELsf4?lw=@$mgmSj_O|nhn5(5 zv2eb=-cbA^nni}X1Ju5}xUsD!ZTCKJ3xA4SDdi-Tc}*{8YI^Bk=qI5mzz$6zni-VA zP}*^?Ih@%DX?TtgQCRHZ%te%l(sv;sx=7ZE|5?()_7lo!UKG6`6d{LdkNgcd*bNon z%7!4mzNN6f1ndb+#&eGQe1m|d07VbwUh6Ohuu3eu;Ip`KLpe5WPkuw!4YUd?(cdlf zLrs@8;+CtS5hU4!S$B2XFX8|wz_J~W_`FNX6_Z;(mR(NtvAS+m@QaHcy(+|W#1x5p z8{V}Xh;Q&2gn^t>Xefcub!?z1JPFjDRSYa>F(su)d!4>@$_lF~ycke;F(9?D{ubZD z7~MRmp`!A=I*t?S>c8+vNWBTA+T0KyE{LB{t4i{%D!y8c`iFIeS3;)OyE=1Do^`r3 zpD%WvaG(=+21hy!{-aAw2IQyvW>{6@w zw=1yU=MaMDx|Qgi5yl{i`npB$X6q9L1fti<}G435vF0@3X+TaRf?TL@ihp* z@aI0X>CL&Z<>q}W@#Zh%v+?ql{mb$8m6$$rfzJXB9&+)GU0jZ%CD?TF(n< z0+&5XXuUiNKDg*@tAd%pjmQXxYVu>V4W?wkhzwX&6W0M3(K;$Ldq7O1$8DQSduB4F z(YZaPOu1#(^vM;i>E^*wrlRk9r0wRffmJo0g0^kisZ=6fjipkClTM|oG1<=reYiG;fEfOw)}jQ>!!V(qU32)F-&^k32T jr`isD6+i7(@S9I`q-~m+e5mgDS&M&u@`;MHozm-ni2Z~F literal 0 HcmV?d00001 diff --git a/Matrix Operations/__pycache__/minor.cpython-312.pyc b/Matrix Operations/__pycache__/minor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd13d9e70861221f46438b5abe6652824c1a07cd GIT binary patch literal 1877 zcma)7O>Epm6rQnXH`~n*O;Hgoe-j0v7&%!sEd>Ha3ZV@Gnj%0#N{AL?Pj;QG?J)M{ zPa7!*ka9p`D{ zpb^1#(}R?(=2!DZm-PX-D!yNHL+%Amqb|4|_>txMA-DKk!?z*Ep?d^=wJyq%os#9I0XxHf%JsKKVF59Ua;i)Rpmq;EY1Ko>+i^NQNb7M@mTRtE9_KU_8xYLH)VM2n3mp)#0o$Ou5h&TvPe+E{A_ zje8cQ>qnKux2>lYh*KB*&_4VS#1?5n5jW|1n43_{Yp~{kh4bs=3*FYL#MWj{6SA&1 zbwFx>)SFr-@`m>L83wp@{XLLWY0JdWt$7NCj;U0|o|Sf1*C)S1n(coSc1N)#sZ44Z zJ{P)v$C8#OA|XR%4rfD|sn;=Hcf$y~2ImBs@Dk7xkmjt5aMk5wuo@``M<}dMsC2P1 zqL%0X1(KF-ic+w5lde*FN=)hh&8DM&fbak8J)}9+hIEtfh{57~a_^YBF`bWfARjW= zL(~JaR0}*&3N6oDElmWD2us(JN9FpWkQP2ZVM);#SzL{CN|QZs`ce3WuYuSg2hWh< z3%5pZjeq;*?ML?L-oOv~9=rYcPv(_hx+ixgHYZwItABH{Wp58`kKY{Je!At}?Rjdy zd-4vOybqINbK|VRY;c#20%)o_VshWvBGCp4|KxLD}R3j%hd28 literal 0 HcmV?d00001 diff --git a/Matrix Operations/__pycache__/transpose.cpython-312.pyc b/Matrix Operations/__pycache__/transpose.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49e9c9e6c1d02e8895e1a9abad63d4416cdab0e4 GIT binary patch literal 1681 zcmZ`(-A~*`5a0E#jgN4AT-78rfviH3#*u(hRaA|ls?Z22QbQAxN)Zw|Ip+l&&OTWC zNLT@_PxnTTz9dhb-Sd4!Raf%t%+Abj z#yhj~b28bAU?ra$Gus5AzobxGTFe}c0`mwt$iZ3U;YsXilNy$?mL-$KA)ld1>QJCM zHynNLB0|E{5Z8BN0F0KjCCxI*Qns|H<5N59I(Ep@o*fGJe$+NETtAGZ@eGdrZ5R}M3KX~=iVAvx6ljxgQ-mod zeVTMlxKo`n<_cO-xvo%|@roYr&ls)ZS7ttw{SfKBK9Oz7r(7TR+>sGBf5V6H!(51H*dOzGdRKi9i%l$})>zd(~5n(UFc7*Rn_+EtF$bh0O!lfDDBx5u7@~y$yoW}

Bi7>uKRJkNzKs}u~@e{o=bDN58O(FHgR?$C~ka?oC@T8@C>y!PK zvj^s}O>@oM>$>pNd=rG?$hxsQqL`w+c6B`gLjT)84(;6eEjj!>{^tBP{`%sx_P)~1 z2MbTz`}UHAj)ak98kKftGkKZkh zm4?=?mFx!}{Y^l3NWlEiKy9hj>n|z^)N$^`ljLx45)$1#mKyCdc6$<|y=}V}bl`vL zl{5po`jWpT?=~J-Gcd5e#XvPh2~bjKnjnpN(U<}|@l1h{MJ;`KTvhY-EB!CH?KJiO zw8(j?8}b1c>Jg}6_MbN(D`(NNY=N>IPi0xqayt+>l~b-PCvmw=5?LdQisO=pM~=!V zN&10|TbhvGs*DyE(kGBPGa(Hl>e;R@dVxJJH9bI9QN={9C%)>~x8B<`FGB%o=a=1E zLk~~?N_&sM07YgRX0Pj~(^gB=l9}b1IWAO}R%6LbRX_zSt$ldO>GTgsoRKOS`K5Wq z%Q^Whe_xyfQKl4J0&++&#($!rKTvDM=)tMV2Uy2v4m%NTD=zPo?%%2T`Pd;r^bLje EFIZBBkpKVy literal 0 HcmV?d00001 diff --git a/Matrix Operations/addition.py b/Matrix Operations/addition.py new file mode 100644 index 00000000..fc8e5dfe --- /dev/null +++ b/Matrix Operations/addition.py @@ -0,0 +1,56 @@ +""" +This program implements matrix addition. + +It includes a function to check if the dimensions of two matrices match, +a function to add two matrices, and a main function to test the matrix +addition function. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + matrix_addition(m1, m2) + [[2, 4, 6], [8, 10, 12], [14, 16, 18]] +""" + +from checker import check_matrix_dimension, print_matrix +import sys + + +def matrix_addition(m1, m2): + """ + This function adds two matrices. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + list of lists: The sum of the two matrices. + + Raises: + sys.exit: If the dimensions of the two matrices do not match. + """ + if check_matrix_dimension(m1, m2) == False: + sys.exit("Matrix dimensions do not match") + + n = len(m1) + m = len(m1[0]) + answer = [[0 for i in range(m)] for j in range(n)] + for i in range(len(m1)): + for j in range(len(m1[i])): + answer[i][j] = m1[i][j] + m2[i][j] + return answer + + +def main(): + """ + This function tests the matrix addition function. + + """ + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(matrix_addition(m1, m2)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/adjoint.py b/Matrix Operations/adjoint.py new file mode 100644 index 00000000..23717199 --- /dev/null +++ b/Matrix Operations/adjoint.py @@ -0,0 +1,49 @@ +""" +This module contains a function to calculate the adjoint matrix of a given matrix. + +The adjoint matrix of a matrix is the transpose of its cofactor matrix. + +The module contains the following functions: + +- `adjoint(matrix)`: This function takes a matrix as input and returns its + adjoint matrix. + +The module also contains a main function which tests the adjoint function. + +Example: + matrix = [[1, -1, 2], [2, 3, 5], [1, 0, 3]] + adjoint(matrix) + # Output: + # [[9, 3, -11], [-1, 1, -1], [-3, -1, 5]] +""" + +from checker import print_matrix +from cofactor import cofactor +from transpose import transpose + + +def adjoint(matrix): + """ + This function takes a matrix as input and returns its adjoint matrix. + + Args: + matrix (list of lists): The input matrix. + + Returns: + list of lists: The adjoint matrix of the input matrix. + + Raises: + sys.exit: If the input matrix is not a square matrix. + """ + matrix = transpose(cofactor(matrix)) + return matrix + + +def main(): + m = [[1, -1, 2], [2, 3, 5], [1, 0, 3]] + result = adjoint(m) + print_matrix(result) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/checker.py b/Matrix Operations/checker.py new file mode 100644 index 00000000..3f453f7c --- /dev/null +++ b/Matrix Operations/checker.py @@ -0,0 +1,131 @@ +""" +This program contains functions to validate a matrix, check if two matrices +can be added or multiplied, and check if a matrix is square. It also contains +a function to print a matrix. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m4 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print(check_matrix_dimension(m1, m2)) + print(check_matrix_multiplication(m1, m2)) + print(check_matrix_square(m3)) + print(check_matrix_square(m4)) + print_matrix(m1) + print_matrix(m2) +""" + +def validate_matrix(m): + """ + This function validates a matrix. + + It checks if the 2d array is a valid matrix and if the matrix is a list of + lists. + + Args: + m (list of lists): The matrix to be validated. + + Returns: + bool: True if the matrix is valid, False otherwise. + """ + n = len(m[0]) + for i in range(len(m)): + if len(m[i]) != n: + return False + return True + + +def check_matrix_dimension(m1, m2): + """ + This function checks if two matrices can be added. + + It checks if the two matrices have the same dimensions. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + bool: True if the two matrices can be added, False otherwise. + """ + if (validate_matrix(m1) and validate_matrix(m2)) == False: + return False + n = len(m1) + if (n != len(m2)): + return False + for i in range(n): + if (len(m1[i]) != len(m2[i])): + return False + return True + + +def check_matrix_multiplication(m1, m2): + """ + This function checks if two matrices can be multiplied. + + It checks if the two matrices have the same number of columns as the first + matrix has rows. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + bool: True if the two matrices can be multiplied, False otherwise. + """ + if (validate_matrix(m1) and validate_matrix(m2)) == False: + return False + n = len(m1[0]) + if (n != len(m2)): + return False + return True + + +def check_matrix_square(m): + """ + This function checks if a matrix is square. + + Args: + m (list of lists): The matrix to be checked. + + Returns: + bool: True if the matrix is square, False otherwise. + """ + if validate_matrix(m) == False: + return False + n = len(m) + if (n != len(m[0])): + return False + return True + + +def print_matrix(m): + """ + This function prints a matrix in the terminal for readability. + + Args: + m (list of lists): The matrix to be printed. + """ + for i in range(len(m)): + for j in range(len(m[i])): + print(m[i][j], end=" ") + print() + print() + + +def main(): + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m4 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print(check_matrix_dimension(m1, m2)) + print(check_matrix_multiplication(m1, m2)) + print(check_matrix_square(m3)) + print(check_matrix_square(m4)) + print_matrix(m1) + print_matrix(m2) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/cofactor.py b/Matrix Operations/cofactor.py new file mode 100644 index 00000000..9355bebe --- /dev/null +++ b/Matrix Operations/cofactor.py @@ -0,0 +1,74 @@ +""" +This module contains functions to calculate the cofactor matrix of a given +matrix. + +A cofactor matrix is a matrix where each element is the cofactor of the +corresponding element in the original matrix. The cofactor of an element is +defined as the minor of the element multiplied by (-1) to the power of the sum +of the row and column indices. + +The module contains the following functions: + +- `cofactor(matrix)`: This function takes a matrix as input + and returns its cofactor matrix. + +The module also contains a main function which tests the +`calculate_cofactor_matrix` function. + +Example usage: + matrix = [ + [1, 2, 3], + [0, 4, 5], + [1, 0, 6] + ] + + result = calculate_cofactor_matrix(matrix) + print_matrix(result) +""" + +from checker import print_matrix +from minor import minor +from determinant import determinant + + +def cofactor(matrix): + """ + This function takes a matrix as input and returns its cofactor matrix. + + Args: + matrix (list of lists): The input matrix. + + Returns: + list of lists: The cofactor matrix of the input matrix. + + Raises: + sys.exit: If the input matrix is not a square matrix. + """ + + n = len(matrix) + cofactor_matrix = [] + for i in range(n): + cofactor_row = [] + for j in range(n): + minor_matrix = minor(matrix, i, j) + cofactor_value = ((-1) ** (i + j)) * determinant(minor_matrix) + cofactor_row.append(cofactor_value) + cofactor_matrix.append(cofactor_row) + + return cofactor_matrix + + +def main(): + # Example usage: + matrix = [ + [1, 2, 3], + [0, 4, 5], + [1, 0, 6] + ] + + result = cofactor(matrix) + print_matrix(result) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/determinant.py b/Matrix Operations/determinant.py new file mode 100644 index 00000000..70fe188a --- /dev/null +++ b/Matrix Operations/determinant.py @@ -0,0 +1,61 @@ +""" +This module contains functions to calculate the determinant of a matrix. + +The determinant of a matrix is a scalar value that can be used to describe the +matrix's linear transformation. It can be used to determine the solvability of a +system of linear equations, invertibility of a matrix, and the volume scaling +factor of the linear transformation. + +The module contains the following functions: + +- `determinant(matrix)`: This function takes a matrix as input and returns its + determinant. + +The module also contains a main function which tests the determinant function. + +Example: + matrix = [[1, 2], [2, 9]] + determinant(matrix) + # Output: 7 + +""" +from checker import check_matrix_square +import sys +from minor import minor + +def determinant(matrix): + """ + Calculate the determinant of a matrix. + + Parameters + ---------- + matrix : list of lists + The matrix whose determinant is to be calculated. + + Returns + ------- + int + The determinant of the matrix. + + Raises + ------ + sys.exit + If the matrix is not square. + """ + if not check_matrix_square(matrix): + sys.exit("Matrix is not square") + if len(matrix) == 1: + return matrix[0][0] + if len(matrix) == 2: + return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] + return sum(((-1) ** j) * matrix[0][j] * determinant(minor(matrix, 0, j)) for j in range(len(matrix))) + + + +def main(): + matrix = [[1, 2], [2, 9]] + print(determinant(matrix)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/input.py b/Matrix Operations/input.py new file mode 100644 index 00000000..808defca --- /dev/null +++ b/Matrix Operations/input.py @@ -0,0 +1,59 @@ +""" +This program asks the user to input a matrix and prints it back to the user. + +It asks the user how many rows they want in their matrix and then asks the user +to input the elements of the matrix one row at a time. If the user inputs a +matrix that is not valid, the program will raise a SystemExit exception with +the message "Matrix is not valid". + +The program will then print out the matrix that the user input with the message +"Here's your matrix: \n". + +Example: + $ python input.py + How many rows in your matrix? 3 + 1 2 3 + 4 5 6 + 7 8 9 + Here's your matrix: + [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + +""" + +from checker import print_matrix, validate_matrix +import sys + + +def input_matrix(): + """ + Ask the user to input a matrix. + + The function asks the user how many rows they want in their matrix and then + asks the user to input the elements of the matrix one row at a time. If the + user inputs a matrix that is not valid, the function will raise a SystemExit + exception with the message "Matrix is not valid". + + Returns: + list of lists: The matrix that the user input. + """ + m = [list(map(int, input().split())) for _ in range(int(input("How many rows in your matrix?")))] + if validate_matrix(m) == False: + sys.exit("Matrix is not valid") + return m + + +def main(): + """ + The main function of the program. + + The function asks the user to input a matrix and then prints out the matrix + that the user input with the message "Here's your matrix: \n". + """ + m = input_matrix() + print("Here's your matrix: \n") + print_matrix(m) + + +if __name__ == "__main__": + main() + diff --git a/Matrix Operations/inverse.py b/Matrix Operations/inverse.py new file mode 100644 index 00000000..4ebf2d34 --- /dev/null +++ b/Matrix Operations/inverse.py @@ -0,0 +1,48 @@ +""" +The inverse of a matrix is a matrix that when multiplied with the original +matrix gives the identity matrix. The inverse of a matrix is calculated using +the adjoint matrix and the determinant of the matrix. The adjoint matrix is the +transpose of the cofactor matrix and the determinant is the sum of the products +of the elements of the matrix and their corresponding cofactors. + +The function first calculates the determinant of the matrix. If the determinant +is zero, the function raises a ValueError because the inverse of a matrix with +zero determinant does not exist. The function then calculates the adjoint matrix +and divides each element of the adjoint matrix by the determinant to get the +inverse matrix. +""" +from checker import print_matrix +from adjoint import adjoint +from determinant import determinant +import sys + +def inverse(matrix): + """ + Calculate the inverse of a matrix. + + Args: + matrix (list of lists): The matrix whose inverse is to be calculated. + + Returns: + list of lists: The inverse of the input matrix. + + Raises: + sys.exit: If the matrix is not square or has zero determinant. + """ + det = determinant(matrix) + if det == 0: + sys.exit("Determinant of the matrix is zero and hence inverse matrix does not exist") + matrix = adjoint(matrix) + for i in range(len(matrix)): + for j in range(len(matrix[i])): + matrix[i][j] = matrix[i][j] / det + return matrix + + +def main(): + matrix = [[2, 7, 9], [3, 10, 2], [14, 6, 15]] + print_matrix(inverse(matrix)) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Matrix Operations/matrix.py b/Matrix Operations/matrix.py new file mode 100644 index 00000000..4e5d6733 --- /dev/null +++ b/Matrix Operations/matrix.py @@ -0,0 +1,60 @@ +# matrix.py +''' + The purpose of this program is to give easy access to all the functions of + the program in the parent directory. +''' + +from addition import matrix_addition +from subtraction import matrix_subtraction +from multiplication import matrix_multiplication +from transpose import transpose as transpose_matrix +from rotate import rotate as rotate_matrix +from cofactor import cofactor as calculate_cofactor +from determinant import determinant as calculate_determinant +from adjoint import adjoint as calculate_adjoint +from inverse import inverse as calculate_inverse +from swap import swap_row, swap_column +from sum import matrix_sum, trace, sum_secondary_diagonal + +def add_matrices(matrix1, matrix2): + return matrix_addition(matrix1, matrix2) + +def subtract_matrices(matrix1, matrix2): + + return matrix_subtraction(matrix1, matrix2) + +def multiply_matrices(matrix1, matrix2): + return matrix_multiplication(matrix1, matrix2) + +def transpose(matrix): + return transpose_matrix(matrix) + +def rotate(matrix, angle): + return rotate_matrix(matrix, angle) + +def cofactor(matrix): + return calculate_cofactor(matrix) + +def determinant(matrix): + return calculate_determinant(matrix) + +def adjoint(matrix): + return calculate_adjoint(matrix) + +def inverse(matrix): + return calculate_inverse(matrix) + +def swap_row(matrix, i, j): + return swap_row(matrix, i, j) + +def swap_column(matrix, i, j): + return swap_column(matrix, i, j) + +def sum_matrix(matrix): + return matrix_sum(matrix) + +def matrix_trace(matrix): + return trace(matrix) + +def secondary_diagonal_sum(matrix): + return sum_secondary_diagonal(matrix) \ No newline at end of file diff --git a/Matrix Operations/minor.py b/Matrix Operations/minor.py new file mode 100644 index 00000000..07e96207 --- /dev/null +++ b/Matrix Operations/minor.py @@ -0,0 +1,54 @@ +""" +This module contains a function to calculate the minor matrix of a given matrix. + +The function takes a matrix and two indices as arguments and returns the minor +matrix of the given matrix at the given indices. + +The minor matrix is a matrix that is formed by removing the row and column at the +given indices from the given matrix. + +The module also contains a main function which tests the minor function. + +Example: + matrix = [[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12], [13, 14, 15, 16]] + i = 1 + j = 1 + minor(matrix, i-1, j-1) + # Output: + # [[1, 3, 10], [7, 9, 12], [13, 15, 16]] +""" + +from checker import print_matrix + + +def minor(matrix, i, j): + """ + This function calculates the minor matrix of a given matrix at the given + indices. + + Parameters + ---------- + matrix : list of lists + The input matrix. + i : int + The row index. + j : int + The column index. + + Returns + ------- + list of lists + The minor matrix of the given matrix at the given indices. + """ + return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])] + + +def main(): + matrix = [[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12], [13, 14, 15, 16]] + i = 1 + j = 1 + print_matrix(minor(matrix, i-1, j-1)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/multiplication.py b/Matrix Operations/multiplication.py new file mode 100644 index 00000000..f7d5a85a --- /dev/null +++ b/Matrix Operations/multiplication.py @@ -0,0 +1,106 @@ +""" +This module contains two functions to multiply matrices. + +The first function, `matrix_multiplication`, multiplies two matrices. The +function takes two matrices as arguments and returns the product of the two +matrices. The function first checks if the dimensions of the two matrices match. +If the dimensions do not match, the function raises a SystemExit exception. + +The function then creates a new matrix filled with zeros and calculates the +product of the two matrices by iterating over the elements of the matrices and +multiplying the corresponding elements together. The function then returns the +product of the two matrices. + +The second function, `scalar_matrix_multiplication`, multiplies a matrix by a +scalar. The function takes a scalar and a matrix as arguments and returns the +product of the scalar and the matrix. The function first checks if the matrix is +valid. If the matrix is not valid, the function raises a SystemExit exception. + +The function then multiplies each element of the matrix by the scalar and +returns the product of the scalar and the matrix. + +The module also contains a main function which tests the matrix multiplication +functions. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + matrix_multiplication(m1, m2) + [[30, 36, 42], [66, 81, 96], [102, 126, 150]] + + scalar_matrix_multiplication(5, m1) + [[5, 10, 15], [20, 25, 30], [35, 40, 45]] + +""" + +from checker import check_matrix_multiplication, validate_matrix, print_matrix +import sys + + +def matrix_multiplication(m1, m2): + """ + This function multiplies two matrices. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + list of lists: The product of the two matrices. + + Raises: + sys.exit: If the dimensions of the two matrices do not match. + """ + if check_matrix_multiplication(m1, m2) == False: + sys.exit("Matrix dimensions do not match") + + n = len(m1) + m = len(m1[0]) + l = len(m2[0]) + answer = [[0 for i in range(l)] for j in range(n)] + for i in range(n): + for j in range(m): + for k in range(l): + answer[i][j] += m1[i][k] * m2[k][j] + + return answer + + + +def scalar_matrix_multiplication(s, m): + """ + This function multiplies a matrix by a scalar. + + Args: + s (int): The scalar. + m (list of lists): The matrix. + + Returns: + list of lists: The product of the scalar and the matrix. + + Raises: + sys.exit: If the matrix is not valid. + """ + if validate_matrix(m) == False: + sys.exit("The 2D array is not a valid matrix") + for i in range(len(m)): + for j in range(len(m[0])): + m[i][j] = s * m[i][j] + return m + + + +def main(): + """ + This function tests the matrix multiplication functions. + + """ + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(matrix_multiplication(m1, m2)) + print_matrix(scalar_matrix_multiplication(5, m1)) + + +if __name__ == "__main__": + main() + diff --git a/Matrix Operations/readme.md b/Matrix Operations/readme.md new file mode 100644 index 00000000..cf93338f --- /dev/null +++ b/Matrix Operations/readme.md @@ -0,0 +1,107 @@ +# Matrix Operations Library +===================================== + +A collection of Python functions for performing various matrix operations. + +## Functions +------------- + +### 1. Checker +--------------- + +* **File:** `checker.py` +* **Description:** This program contains functions to validate a matrix, check if two matrices can be added or multiplied, and check if a matrix is square. It also contains a function to print a matrix. + +### 2. Input +------------- + +* **File:** `input.py` +* **Description:** This program asks the user to input a matrix and prints it back to the user. + +### 3. Matrix +------------- + +* **File:** `matrix.py` +* **Description:** This module contains functions to perform various matrix operations, including addition, subtraction, multiplication, transpose, rotate, cofactor, determinant, adjoint, inverse, swap, and sum. + +### 4. Addition +-------------- + +* **File:** `addition.py` +* **Description:** This program implements matrix addition. + +### 5. Subtraction +---------------- + +* **File:** `subtraction.py` +* **Description:** This program implements matrix subtraction. + +### 6. Multiplication +------------------ + +* **File:** `multiplication.py` +* **Description:** This module contains two functions to multiply matrices. + +### 7. Transpose +-------------- + +* **File:** `transpose.py` +* **Description:** This module contains functions to transpose a matrix. + +### 8. Rotate +------------ + +* **File:** `rotate.py` +* **Description:** This program rotates a matrix by 90, 180 or 270 degrees. + +### 9. Cofactor +------------- + +* **File:** `cofactor.py` +* **Description:** This module contains functions to calculate the cofactor matrix of a given matrix. + +### 10. Determinant +---------------- + +* **File:** `determinant.py` +* **Description:** This module contains a function to calculate the determinant of a matrix. + +### 11. Adjoint +------------- + +* **File:** `adjoint.py` +* **Description:** This module contains a function to calculate the adjoint matrix of a given matrix. + +### 12. Inverse +------------- + +* **File:** `inverse.py` +* **Description:** The inverse of a matrix is a matrix that when multiplied with the original matrix gives the identity matrix. + +### 13. Swap +------------ + +* **File:** `swap.py` +* **Description:** This module contains functions to swap rows and columns of a matrix. + +### 14. Sum +------------ + +* **File:** `sum.py` +* **Description:** This module contains functions to calculate the sum of all elements in a matrix, the trace of a matrix and the sum of the elements in the secondary diagonal of a matrix. + + + +## Usage +----- + +To use the functions in this library, simply import the corresponding module and call the desired function. For example, to add two matrices, you would import the `matrix` module and call the `add_matrices` function. + +```python +import matrix + +matrix1 = [[1, 2], [3, 4]] +matrix2 = [[5, 6], [7, 8]] + +result = matrix.add_matrices(matrix1, matrix2) +print(result) \ No newline at end of file diff --git a/Matrix Operations/rotate.py b/Matrix Operations/rotate.py new file mode 100644 index 00000000..1844df55 --- /dev/null +++ b/Matrix Operations/rotate.py @@ -0,0 +1,59 @@ +""" +This program rotates a matrix by 90, 180 or 270 degrees. + +It includes a function to rotate a matrix, and a main function to test the +rotation function. + +Example: + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + rotate(m, 90) + # Output: + # [[14, 17, 45, 18], [12, 10, 8, 6], [6, 4, 2, 14]] + +""" +from transpose import transpose +from checker import print_matrix +import sys + + +def rotate(m, deg = 90): + """ + Rotate a matrix. + + This function takes a matrix and a rotation degree (90, 180 or 270) as input and returns its rotated version. + + Parameters + ---------- + m : list of lists + The matrix to be rotated. + + Returns + ------- + list of lists + The rotated matrix. + + Raises + ------ + sys.exit + If the matrix is not square. + """ + + if (deg!= 90 and deg!= 180 and deg!= 270): + sys.exit("Rotation degree must be 90, 180 or 270") + n = deg//90 + k = len(m) + for _ in range(n): + m = transpose(m) + for i in range(len(m)): + for j in range(len(m[i])//2): + m[i][j], m[i][k-j-1] = m[i][k-j-1], m[i][j] + return m + + +def main(): + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + print_matrix(rotate(m, 90)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/subtraction.py b/Matrix Operations/subtraction.py new file mode 100644 index 00000000..d841b7e2 --- /dev/null +++ b/Matrix Operations/subtraction.py @@ -0,0 +1,57 @@ +""" +This program implements matrix subtraction. + +It includes a function to check if the dimensions of two matrices match, +a function to subtract the second matrix from the first, and a main function +to test the matrix subtraction function. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + matrix_subtraction(m1, m2) + [[0, 0, 0], [0, 0, 0], [0, 0, 0]] +""" + +from checker import check_matrix_dimension, print_matrix +import sys + + +def matrix_subtraction(m1, m2): + """ + This function subtracts the second matrix from the first. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + list of lists: The difference of the two matrices. + + Raises: + sys.exit: If the dimensions of the two matrices do not match. + """ + if check_matrix_dimension(m1, m2) == False: + sys.exit("Matrix dimensions do not match") + + n = len(m1) + m = len(m1[0]) + answer = [[0 for i in range(m)] for j in range(n)] + for i in range(len(m1)): + for j in range(len(m1[i])): + answer[i][j] = m1[i][j] - m2[i][j] + return answer + + +def main(): + """ + This function tests the matrix subtraction function. + + """ + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(matrix_subtraction(m1, m2)) + + +if __name__ == "__main__": + main() + diff --git a/Matrix Operations/sum.py b/Matrix Operations/sum.py new file mode 100644 index 00000000..effb7c26 --- /dev/null +++ b/Matrix Operations/sum.py @@ -0,0 +1,105 @@ +""" +This module contains functions to calculate the sum of all elements in a matrix, +the trace of a matrix and the sum of the elements in the secondary diagonal of a +matrix. + +The module contains the following functions: + +- `matrix_sum(m)`: This function takes a matrix as input and returns the sum of + all its elements. +- `trace(m)`: This function takes a matrix as input and returns the sum of the + elements in its main diagonal. +- `sum_secondary_diagonal(m)`: This function takes a matrix as input and + returns the sum of the elements in its secondary diagonal. + +The module also contains a main function which tests the above functions. + +Example: + m1 = [[1, 2, 10], [4, 5, 11], [7, 8, 12]] + matrix_sum(m1) + # Output: 45 + trace(m1) + # Output: 36 + sum_secondary_diagonal(m1) + # Output: 39 + +""" +from checker import validate_matrix, check_matrix_square +import sys + + +def matrix_sum(m): + """ + This function calculates the sum of all elements in a matrix. + + Args: + m (list of lists): The matrix whose sum is to be calculated. + + Returns: + int: The sum of all elements in the matrix. + + Raises: + sys.exit: If the 2D array is not a valid matrix. + """ + if not validate_matrix(m): + sys.exit("The 2D array is not a valid matrix") + sum = 0 + for i in range(len(m)): + for j in range(len(m[i])): + sum += m[i][j] + return sum + + +def trace(m): + """ + This function calculates the trace of a matrix. + + Args: + m (list of lists): The matrix whose trace is to be calculated. + + Returns: + int: The trace of the matrix. + + Raises: + sys.exit: If the matrix is not square. + """ + if not check_matrix_square(m): + sys.exit("The matrix is not square") + sum = 0 + for i in range(len(m)): + sum += m[i][i] + return sum + + +def sum_secondary_diagonal(m): + """ + This function calculates the sum of the elements in the secondary diagonal of + a matrix. + + Args: + m (list of lists): The matrix whose secondary diagonal sum is to be + calculated. + + Returns: + int: The sum of the elements in the secondary diagonal of the matrix. + + Raises: + sys.exit: If the matrix is not square. + """ + if not check_matrix_square(m): + sys.exit("The matrix is not square") + sum = 0 + for i in range(len(m)): + sum += m[i][len(m)-i-1] + return sum + + +def main(): + m1 = [[1, 2, 10], [4, 5, 11], [7, 8, 12]] + print(matrix_sum(m1)) + print(trace(m1)) + print(sum_secondary_diagonal(m1)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/swap.py b/Matrix Operations/swap.py new file mode 100644 index 00000000..f1539b71 --- /dev/null +++ b/Matrix Operations/swap.py @@ -0,0 +1,68 @@ +""" +This module contains functions to swap rows and columns of a matrix. + +The module contains the following functions: + +- `swap_row(matrix, i, j)`: This function swaps the i-th and j-th rows of the + given matrix. +- `swap_column(matrix, i, j)`: This function swaps the i-th and j-th columns of + the given matrix. +- `main()`: This function is the main function of the program. It swaps rows and + columns of a matrix and prints the result. + +Example: + $ python swap.py + [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[4, 5, 6], [1, 2, 3], [7, 8, 9]] + [[3, 2, 1], [6, 5, 4], [9, 8, 7]] +""" + +from checker import validate_matrix, print_matrix +import sys + + +def swap_row(m, i, j): + """ + This function swaps the i-th and j-th rows of the given matrix. + + Args: + m (list of lists): The matrix to be modified. + i (int): The index of the first row to be swapped. + j (int): The index of the second row to be swapped. + """ + temp = m[i] + m[i] = m[j] + m[j] = temp + return + + +def swap_column(m, i, j): + """ + This function swaps the i-th and j-th columns of the given matrix. + + Args: + m (list of lists): The matrix to be modified. + i (int): The index of the first column to be swapped. + j (int): The index of the second column to be swapped. + """ + for lis in m: + lis[i], lis[j] = lis[j], lis[i] + return + + +def main(): + """ + This function is the main function of the program. It swaps rows and columns + of a matrix and prints the result. + """ + m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(m) + swap_row(m, 0, 1) + print_matrix(m) + m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + swap_column(m, 0, 2) + print_matrix(m) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/transpose.py b/Matrix Operations/transpose.py new file mode 100644 index 00000000..bd4fb74b --- /dev/null +++ b/Matrix Operations/transpose.py @@ -0,0 +1,62 @@ +""" +This module contains functions to transpose a matrix. + +The module contains the following functions: + +- `transpose(matrix)`: This function takes a matrix as input and returns its + transpose. + +The module also contains a main function which tests the transpose function. + +Example: + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + transpose(m) + # Output: + # [[2, 8, 14], [4, 10, 16], [6, 12, 18], [14, 17, 45]] +""" + +from checker import validate_matrix, print_matrix +import sys + + +def transpose(m): + """ + Transpose a matrix. + + Parameters + ---------- + m : list of lists + The matrix to be transposed. + + Returns + ------- + list of lists + The transposed matrix. + + Raises + ------ + sys.exit + If the matrix is not square. + """ + if validate_matrix(m) == False: + sys.exit("Matrix is not valid") + a = len(m) + b = len(m[0]) + answer = [[0 for i in range(a)] for j in range(b)] + for i in range(b): + for j in range(a): + answer[i][j] = m[j][i] + return answer + + +def main(): + """ + This function reads a matrix from the user and prints its transpose. + """ + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + print_matrix(transpose(m)) + + +if __name__ == "__main__": + main() + From cea3c9047b9bbcc98c19e2e9daf8387a539237b3 Mon Sep 17 00:00:00 2001 From: Bibek Jyoti Charah Date: Thu, 10 Oct 2024 12:54:11 +0530 Subject: [PATCH 2/4] added explanation for array sorting --- Sorting/bubblesort-explanation.py | 38 +++++++++++++++++++++ Sorting/insertionsort-explanation.py | 51 ++++++++++++++++++++++++++++ Sorting/readme.md | 34 +++++++++++++++++++ Sorting/selectionsort-explanation.py | 43 +++++++++++++++++++++++ 4 files changed, 166 insertions(+) create mode 100644 Sorting/bubblesort-explanation.py create mode 100644 Sorting/insertionsort-explanation.py create mode 100644 Sorting/readme.md create mode 100644 Sorting/selectionsort-explanation.py diff --git a/Sorting/bubblesort-explanation.py b/Sorting/bubblesort-explanation.py new file mode 100644 index 00000000..d44286c6 --- /dev/null +++ b/Sorting/bubblesort-explanation.py @@ -0,0 +1,38 @@ +def bubble_sort_with_explanation(arr): + n = len(arr) + + print(f"Initial array: {arr}") + print("\nStarting Bubble Sort...") + + for i in range(n): + print(f"\nPass {i + 1}:") + + # Flag to check if any swap happened in this pass + swapped = False + + for j in range(0, n - i - 1): + print(f" Comparing {arr[j]} and {arr[j + 1]}") + + if arr[j] > arr[j + 1]: + print(f" Swapping {arr[j]} and {arr[j + 1]} since {arr[j]} > {arr[j + 1]}") + arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped = True + else: + print(" No swap needed") + + print(f" Array after comparison: {arr}") + + print(f"Array after pass {i + 1}: {arr}") + + # If no swapping occurred, array is already sorted + if not swapped: + print(f"\nArray is already sorted after pass {i + 1}. Stopping early.") + break + + print("\nSorting completed!") + print(f"Final sorted array: {arr}") + +# Test the function +if __name__ == "__main__": + test_array = [64, 34, 25, 12, 22, 11, 90] + bubble_sort_explained(test_array) \ No newline at end of file diff --git a/Sorting/insertionsort-explanation.py b/Sorting/insertionsort-explanation.py new file mode 100644 index 00000000..39330100 --- /dev/null +++ b/Sorting/insertionsort-explanation.py @@ -0,0 +1,51 @@ +""" +This program implements the insertion sort algorithm and prints out each step of the process. + +The function insertion_sort_with_explanation takes in an array and sorts it using the insertion sort algorithm. It prints out the state of the array at each step of the process, explaining what's happening. +""" + +def insertion_sort_with_explanation(arr): + """ + Sorts the given array using insertion sort and prints out each step of the process. + + :param arr: The array to be sorted + :type arr: list + :return: The sorted array + :rtype: list + """ + print("Initial array:", arr) + print("\nBeginning Insertion Sort:\n") + + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + print(f"Step {i}:") + print(f" Current element to insert: {key}") + print(f" Current array state: {arr}") + + if arr[j] <= key: + print(f" {key} is already in the correct position.") + else: + print(f" Finding the correct position for {key}:") + + while j >= 0 and arr[j] > key: + print(f" Comparing {key} with {arr[j]}") + print(f" {arr[j]} > {key}, so moving {arr[j]} to the right") + arr[j + 1] = arr[j] + j -= 1 + print(f" Current array state: {arr}") + + if j + 1 != i: + arr[j + 1] = key + print(f" Inserted {key} at index {j + 1}") + print(f" Array after insertion: {arr}") + + print() # Empty line for readability + + print("Sorting complete. Final array:", arr) + + +# Test the function +if __name__ == "__main__": + test_array = [64, 34, 25, 12, 22, 11, 90] + insertion_sort_with_explanation(test_array) diff --git a/Sorting/readme.md b/Sorting/readme.md new file mode 100644 index 00000000..e3e56683 --- /dev/null +++ b/Sorting/readme.md @@ -0,0 +1,34 @@ +# Sorting Algorithms +====================== + +This folder contains implementations of three common sorting algorithms in Python: Insertion Sort, Bubble Sort, and Selection Sort. Additionally, there are explanation scripts that print out the steps involved in each sorting process. + +## Algorithms +------------ + +### Insertion Sort + +* Implementation: `insertionsort.py` +* Explanation: `insertionsort-explanation.py` + +### Bubble Sort + +* Implementation: `bubblesort.py` +* Explanation: `bubblesort-explanation.py` + +### Selection Sort + +* Implementation: `selectionsort.py` +* Explanation: `selectionsort-explanation.py` + +## Usage +----- + +To run the implementations, simply execute the corresponding Python script. For example, to run the Insertion Sort implementation, run `python insertionsort.py`. + +To see the step-by-step explanation of each sorting process, run the corresponding explanation script. For example, to see the explanation of Insertion Sort, run `python insertionsort-explanation.py`. + +## Contributing +------------ + +Feel free to contribute to this repository by adding more sorting algorithms or improving the existing implementations. \ No newline at end of file diff --git a/Sorting/selectionsort-explanation.py b/Sorting/selectionsort-explanation.py new file mode 100644 index 00000000..974d7b63 --- /dev/null +++ b/Sorting/selectionsort-explanation.py @@ -0,0 +1,43 @@ +def selection_sort_with_explaination(arr): + """ + Sorts the given array using selection sort and prints out each step of the process. + + :param arr: The array to be sorted + :type arr: list + :return: The sorted array + :rtype: list + """ + n = len(arr) + + print(f"Initial array: {arr}") + print("\nStarting Selection Sort...") + + for i in range(n): + print(f"\nIteration {i + 1}:") + print(f"Current array: {arr}") + + # Find the minimum element in the unsorted part of the array + min_idx = i + print(f"Looking for the minimum element starting from index {i}") + + for j in range(i + 1, n): + if arr[j] < arr[min_idx]: + min_idx = j + print(f" New minimum found: {arr[min_idx]} at index {min_idx}") + + # Swap the found minimum element with the first element of the unsorted part + if min_idx != i: + print(f"Swapping {arr[i]} at index {i} with {arr[min_idx]} at index {min_idx}") + arr[i], arr[min_idx] = arr[min_idx], arr[i] + else: + print(f"No swap needed. {arr[i]} at index {i} is already in the correct position.") + + print(f"Array after iteration {i + 1}: {arr}") + + print("\nSorting completed!") + print(f"Final sorted array: {arr}") + +# Test the function +if __name__ == "__main__": + test_array = [64, 34, 25, 12, 22, 11, 90] + selection_sort_with_explaination(test_array) From 819f8dfcf48f98972f5b9c5a5f89f030f76a5668 Mon Sep 17 00:00:00 2001 From: SammyUrfen Date: Thu, 10 Oct 2024 14:20:12 +0530 Subject: [PATCH 3/4] Added scripts to Sorting and Star Pattern --- Matrix Operations/readme.md | 8 ++++- Sorting/bubblesort-explanation.py | 2 +- Star Pattern/README.md | 50 +++++++++++++++++++++++--- Star Pattern/Star.py | 48 +++++++++++++++++++++++++ Star Pattern/diamond.py | 18 ++++++++++ Star Pattern/inversePyramid.py | 12 +++++++ Star Pattern/inversestarPattern.py | 10 ++++++ Star Pattern/pyramid.py | 12 +++++++ Star Pattern/reverseDiamond.py | 22 ++++++++++++ Star Pattern/rightiversestarPattern.py | 12 +++++++ Star Pattern/rightstarPattern.py | 12 +++++++ Star Pattern/starPattern.py | 5 +-- 12 files changed, 203 insertions(+), 8 deletions(-) create mode 100644 Star Pattern/Star.py create mode 100644 Star Pattern/diamond.py create mode 100644 Star Pattern/inversePyramid.py create mode 100644 Star Pattern/inversestarPattern.py create mode 100644 Star Pattern/pyramid.py create mode 100644 Star Pattern/reverseDiamond.py create mode 100644 Star Pattern/rightiversestarPattern.py create mode 100644 Star Pattern/rightstarPattern.py diff --git a/Matrix Operations/readme.md b/Matrix Operations/readme.md index cf93338f..c7e5fea5 100644 --- a/Matrix Operations/readme.md +++ b/Matrix Operations/readme.md @@ -104,4 +104,10 @@ matrix1 = [[1, 2], [3, 4]] matrix2 = [[5, 6], [7, 8]] result = matrix.add_matrices(matrix1, matrix2) -print(result) \ No newline at end of file +print(result) +``` + +## Contributed By +-------------- + +SammyUrfen diff --git a/Sorting/bubblesort-explanation.py b/Sorting/bubblesort-explanation.py index d44286c6..0be6cac0 100644 --- a/Sorting/bubblesort-explanation.py +++ b/Sorting/bubblesort-explanation.py @@ -35,4 +35,4 @@ def bubble_sort_with_explanation(arr): # Test the function if __name__ == "__main__": test_array = [64, 34, 25, 12, 22, 11, 90] - bubble_sort_explained(test_array) \ No newline at end of file + bubble_sort_with_explanation(test_array) \ No newline at end of file diff --git a/Star Pattern/README.md b/Star Pattern/README.md index 97a603d1..b2050698 100644 --- a/Star Pattern/README.md +++ b/Star Pattern/README.md @@ -4,13 +4,55 @@ You can contribute by adding more python scripts which can be used to automate t Incase you have anything to be followed while executing the python script mention it as well -# Python Script +# Star Pattern +================ -## Script - Star Pattern +This folder contains Python scripts to create various patterns with '*' (stars). -Code to create star pattern -starPattern.py +## Scripts +-------- +### 1. starPattern.py +Creates a star pattern pyramid. + +### 2. inversestarPattern.py + +Creates an inverse star pattern pyramid. + +### 3. rightstarPattern.py + +Creates a right-aligned star pattern pyramid. + +### 4. rightinversestarPattern.py + +Creates a right-aligned inverse star pattern pyramid. + +### 5. pyramid.py + +Creates a pyramid pattern. + +### 6. inversePyramid.py + +Creates an inverse pyramid pattern. + +### 7. diamond.py + +Creates a diamond pattern. + +### 8. reverseDiamond.py + +Creates a reverse diamond pattern. + +### 9. Star.py + +Creates a star pattern. + +## Contributed By +-------------- + +Daksh Jain, +marialee222, +SammyUrfen \ No newline at end of file diff --git a/Star Pattern/Star.py b/Star Pattern/Star.py new file mode 100644 index 00000000..5a2bc549 --- /dev/null +++ b/Star Pattern/Star.py @@ -0,0 +1,48 @@ +def Star(n): + # Upper part of the star + for i in range(1, n + 1): + for j in range(n): + print(" ", end="") + for j in range(1, n - i + 1): + print(" ", end="") + for j in range(1, 2 * i): + print("* ", end="") + print() + + # Upper middle part of the star + for i in range(1, n + 1): + for j in range(n - 1, n - i, -1): + print(" ", end="") + for j in range(1, n - i + 2): + print("* ", end="") + for j in range(1, 2 * n): + print("* ", end="") + for j in range(1, n - i + 2): + print("* ", end="") + print() + + # Lower middle part of the star + for i in range(1, n + 1): + for j in range(1, n - i + 1): + print(" ", end="") + for j in range(1, i + 1): + print("* ", end="") + for j in range(1, 2 * n): + print("* ", end="") + for j in range(1, i + 1): + print("* ", end="") + print() + + # Lower part of the star + for i in range(n, 0, -1): + for j in range(n): + print(" ", end="") + for j in range(1, n - i + 1): + print(" ", end="") + for j in range(1, 2 * i): + print("* ", end="") + print() + +if __name__ == "__main__": + n = int(input("Enter the size of the star: ")) + Star(n) \ No newline at end of file diff --git a/Star Pattern/diamond.py b/Star Pattern/diamond.py new file mode 100644 index 00000000..8b7a90f7 --- /dev/null +++ b/Star Pattern/diamond.py @@ -0,0 +1,18 @@ +def diamond(n): + for i in range(n): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + for i in range(n-2, -1, -1): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height of half the diamond : ")) + diamond(n) \ No newline at end of file diff --git a/Star Pattern/inversePyramid.py b/Star Pattern/inversePyramid.py new file mode 100644 index 00000000..aab8169d --- /dev/null +++ b/Star Pattern/inversePyramid.py @@ -0,0 +1,12 @@ +def inversePyramid(n): + for i in range(n, -1, -1): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + inversePyramid(n) \ No newline at end of file diff --git a/Star Pattern/inversestarPattern.py b/Star Pattern/inversestarPattern.py new file mode 100644 index 00000000..8e8654dc --- /dev/null +++ b/Star Pattern/inversestarPattern.py @@ -0,0 +1,10 @@ +def inversestarPattern(n): + for i in range(n+1, 0, -1): + for j in range(1, i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + inversestarPattern(n) \ No newline at end of file diff --git a/Star Pattern/pyramid.py b/Star Pattern/pyramid.py new file mode 100644 index 00000000..240c03a7 --- /dev/null +++ b/Star Pattern/pyramid.py @@ -0,0 +1,12 @@ +def pyramid(n): + for i in range(n): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + pyramid(n) \ No newline at end of file diff --git a/Star Pattern/reverseDiamond.py b/Star Pattern/reverseDiamond.py new file mode 100644 index 00000000..6b29663f --- /dev/null +++ b/Star Pattern/reverseDiamond.py @@ -0,0 +1,22 @@ +def reverseDiamond(n): + for i in range(1, n + 1): + for j in range(1, 2 * n): + if n - i + 1 < j < n + i - 1: + print(" ", end="") + else: + print("*", end="") + print() + + for i in range(n-1, 0, -1): + for j in range(1, 2 * n): + if n - i + 1 < j < n + i - 1: + print(" ", end="") + else: + print("*", end="") + print() + + + +if __name__ == "__main__": + n = int(input("Enter the height of half the diamond : ")) + reverseDiamond(n) \ No newline at end of file diff --git a/Star Pattern/rightiversestarPattern.py b/Star Pattern/rightiversestarPattern.py new file mode 100644 index 00000000..3cf1cf29 --- /dev/null +++ b/Star Pattern/rightiversestarPattern.py @@ -0,0 +1,12 @@ +def rightinversestarPattern(n): + for i in range(n+1, 0, -1): + for j in range(n-i+1, 0, -1): + print(" ", end="") + for j in range(1, i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + rightinversestarPattern(n) \ No newline at end of file diff --git a/Star Pattern/rightstarPattern.py b/Star Pattern/rightstarPattern.py new file mode 100644 index 00000000..d1a20a99 --- /dev/null +++ b/Star Pattern/rightstarPattern.py @@ -0,0 +1,12 @@ +def rightstarPattern(n): + for i in range(1, n+1): + for j in range(1, n-i+1): + print(" ", end="") + for j in range(1, i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + rightstarPattern(n) \ No newline at end of file diff --git a/Star Pattern/starPattern.py b/Star Pattern/starPattern.py index 9b9dc3c5..886bc8e3 100644 --- a/Star Pattern/starPattern.py +++ b/Star Pattern/starPattern.py @@ -5,6 +5,7 @@ def starPattern(n): print() -n = int(input("Enter the number of rows: ")) -starPattern(n) +if __name__ == "__main__": + n = int(input("Enter the height : ")) + starPattern(n) From d8ff51f21fd862fa6bd26b78d085b06e362ed380 Mon Sep 17 00:00:00 2001 From: SammyUrfen Date: Thu, 10 Oct 2024 15:04:38 +0530 Subject: [PATCH 4/4] Updated README file --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 97710f02..3fa0ffee 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,9 @@ More information on contributing and the general code of conduct for discussion | JSON to YAML converter | [JSON to YAML converter](https://github.com/DhanushNehru/Python-Scripts/tree/master/JSON%20to%20YAML) | Converts JSON file to YAML files. A sample JSON is included for testing. | | Keylogger | [Keylogger](https://github.com/DhanushNehru/Python-Scripts/tree/master/Keylogger) | Keylogger that can track your keystrokes, clipboard text, take screenshots at regular intervals, and records audio. | | Keyword - Retweeting | [Keyword - Retweeting](https://github.com/DhanushNehru/Python-Scripts/tree/master/Keyword%20Retweet%20Twitter%20Bot) | Find the latest tweets containing given keywords and then retweet them. | -| LinkedIn Bot | [LinkedIn Bot](https://github.com/DhanushNehru/Python-Scripts/tree/master/LinkedIn%20Bot) | Automates the process of searching for public profiles on LinkedIn and exporting the data to an Excel sheet. | -| Mail Sender | [Mail Sender](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mail%20Sender) | Sends an email. | +| LinkedIn Bot | [LinkedIn Bot](https://github.com/DhanushNehru/Python-Scripts/tree/master/LinkedIn%20Bot) | Automates the process of searching for public profiles on LinkedIn and exporting the data to an Excel sheet. \ +| Mail Sender | [Mail Sender](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mail%20Sender) | Sends an email. | +| Matrix Operations | [Matrix Operations](https://github.com/SammyUrfen/Python-Scripts/tree/master/Matrix%20Operations) | Scripts for doing different operations and transformations to a Matrix. | Merge Two Images | [Merge Two Images](https://github.com/DhanushNehru/Python-Scripts/tree/master/Merge%20Two%20Images) | Merges two images horizontally or vertically. | | Mouse mover | [Mouse mover](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mouse%20Mover) | Moves your mouse every 15 seconds. | | No Screensaver | [No Screensaver](https://github.com/DhanushNehru/Python-Scripts/tree/master/No%20Screensaver) | Prevents screensaver from turning on. |