├── CustomList_DynamicArray.py ├── HandlingGeoSpatialDataWithGeoPandas.ipynb ├── NumpyTutorial.ipynb ├── README.md ├── Testing_using_pytest ├── __init__.py ├── calculator.py ├── string_operators.py ├── test_calculator.py └── test_string_ops.py ├── aws_boto3_work_file.py ├── backtracking_problems.py ├── circuit_diagram.py ├── dataclasses_in_python.py ├── dsa_binary_search_tree.py ├── dsa_linked_list.py ├── dsa_stack.py ├── hangman-game ├── __pycache__ │ └── list_of_words.cpython-312.pyc ├── hangman_game.py └── list_of_words.py ├── interview_programs.py ├── linked_list_dsa.py ├── number-guessing-game └── number_gusessing_game.py ├── panda_xlsx.ipynb ├── profiling_in_python.py ├── program_utils.py ├── python_mongob_cheatcode.py ├── python_mysql_cheatcodes.py ├── python_oops_concept.py ├── python_postgresql_cheatcodes.py ├── python_speech_recognition_text_to_speech.py ├── python_sqlite_cheatcodes.py ├── rb_workoutfile_or_utils.py ├── recurssion_workoutfile.py ├── sending_mails.py ├── sortedPython.py ├── stack_dsa_tutorial.py ├── subprocess_in_python.py ├── ternary_operations.py ├── timeComplexityProgramms.py └── unittest_folder └── project ├── __pycache__ ├── test_str.cpython-311.pyc └── tests.cpython-311.pyc ├── code ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-310.pyc │ ├── __init__.cpython-311.pyc │ ├── calculations.cpython-310.pyc │ ├── calculations.cpython-311.pyc │ ├── string_operations.cpython-310.pyc │ └── string_operations.cpython-311.pyc ├── calculations.py └── string_operations.py ├── test_str.py └── tests.py /CustomList_DynamicArray.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | #creating own list 4 | class MyList: 5 | def __init__(self): 6 | self.size = 1 7 | self.n = 0 8 | self.A = self.__make_array(self.size) 9 | 10 | def __make_array(self, capacity): 11 | return (capacity*ctypes.py_object)() 12 | 13 | #print 14 | def __str__(self): 15 | result = '' 16 | for i in range(self.n): 17 | result = result+str(self.A[i])+", " 18 | return "["+result[:-2]+"]" 19 | 20 | #len 21 | def __len__(self): 22 | return self.n 23 | 24 | #representing 25 | def __repr__(self): 26 | return self.__str__() 27 | 28 | #adding element 29 | def append(self, val): 30 | if self.n == self.size: 31 | self.__resize(self.size*2) 32 | self.A[self.n] = val 33 | self.n+=1 34 | 35 | def __resize(self, new_size): 36 | B = self.__make_array(new_size) 37 | self.size = new_size 38 | for i in range(self.n): 39 | B[i] = self.A[i] 40 | self.A = B 41 | 42 | #getting elements using index 43 | """def __getitem__(self, index): 44 | if index >= self.n: 45 | return "IndexError - Index Out Of Range" 46 | if index < 0: 47 | try: 48 | return self.A[self.n+index] 49 | except: 50 | return [] 51 | return self.A[index]""" 52 | 53 | #adding slicing to the get_item 54 | def __getitem__(self, index): 55 | if isinstance(index, int): 56 | if index < 0: 57 | try: 58 | return self.A[self.n+index] 59 | except: 60 | return MyList() 61 | if index >= self.n: 62 | return "Index out of range" 63 | return self.A[index] 64 | if isinstance(index, slice): 65 | start, stop, step = index.start, index.stop, index.step 66 | #checking that is it's none and assign a value 67 | #for start check if it's none. if it's none assigning 0 68 | start = start if start is not None else 0 69 | #and also for stop, if it's none assigning self.n 70 | stop = stop if stop is not None else self.n 71 | #and for step assigning 1 as default 72 | step = step if step is not None else 1 73 | 74 | #creating a new array 75 | new_li = MyList() 76 | #checking that start and step is > self.n 77 | if start >= self.n: 78 | return new_li 79 | if stop > self.n: 80 | stop = self.n 81 | #running an loop and adding element to new_li 82 | for i in range(start, stop, step): 83 | new_li.append(self.A[i]) 84 | return new_li 85 | else: 86 | return "Invalid Option" 87 | 88 | #finding element index 89 | def find(self, item): 90 | for i in range(self.n): 91 | if self.A[i] == item: 92 | return i 93 | else: 94 | return "Not in the List" 95 | 96 | #inserting element using index 97 | def insert(self, pos, item): 98 | if self.n == self.size: 99 | self.__resize(self.size*2) 100 | for i in range(self.n, pos, -1): 101 | self.A[i] = self.A[i-1] 102 | self.A[pos] = item 103 | self.n+=1 104 | 105 | #delete an item 106 | def __delitem__(self, pos): 107 | if pos < 0: 108 | try: 109 | pos = self.n+pos 110 | except: 111 | return "Index out of range" 112 | for i in range(pos, self.n-1): 113 | self.A[i] = self.A[i+1] 114 | self.n-=1 115 | 116 | #remove an item by using value 117 | def remove(self, value): 118 | pos = self.find(value) 119 | if type(pos) == int: 120 | self.__delitem__(pos) 121 | else: 122 | return pos 123 | 124 | #pop element 125 | def pop(self): 126 | if self.n == 0: 127 | return "Empty List" 128 | index = self.n-1 129 | self.n-=1 130 | return self.A[index] 131 | 132 | #clear 133 | def clear(self): 134 | self.n = 0 135 | self.size = 1 136 | 137 | #adding sort - insertion sort algorithm going to use 138 | def sort(self): 139 | for i in range(1, self.n): 140 | key = self.A[i] 141 | j = i-1 142 | while j>=0 and self.A[j] > key: 143 | self.A[j+1] = self.A[j] 144 | j-=1 145 | self.A[j+1] = key 146 | 147 | #concatenate array using + operator 148 | def __add__(self, other_li): 149 | new_li = MyList() 150 | #first appending the self.A element 151 | for i in range(self.n): 152 | new_li.append(self.A[i]) 153 | #then appending the other_list element 154 | for i in range(len(other_li)): 155 | new_li.append(other_li[i]) 156 | #then returning new_li 157 | return new_li 158 | 159 | 160 | -------------------------------------------------------------------------------- /NumpyTutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "authorship_tag": "ABX9TyOlDy8MtVrVXiYQEFf85U2+" 8 | }, 9 | "kernelspec": { 10 | "name": "python3", 11 | "display_name": "Python 3" 12 | }, 13 | "language_info": { 14 | "name": "python" 15 | } 16 | }, 17 | "cells": [ 18 | { 19 | "cell_type": "markdown", 20 | "source": [ 21 | "\n", 22 | "

Numpy Beginner's Guide

\n", 23 | "

Arun Arunisto

" 24 | ], 25 | "metadata": { 26 | "id": "MjAy04Q-S_4t" 27 | } 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": [ 32 | "

" 37 | ], 38 | "metadata": { 39 | "id": "E-vYAq-jTTtF" 40 | } 41 | }, 42 | { 43 | "cell_type": "code", 44 | "source": [ 45 | "!pip install numpy \n", 46 | "#not need ! to install numpy on windows, \n", 47 | "#or other platforms you can execute simply \"pip install numpy\"" 48 | ], 49 | "metadata": { 50 | "colab": { 51 | "base_uri": "https://localhost:8080/" 52 | }, 53 | "id": "aYPRapAiU7_2", 54 | "outputId": "f9b9544b-c8eb-4de8-fd92-83a3843d6379" 55 | }, 56 | "execution_count": 2, 57 | "outputs": [ 58 | { 59 | "output_type": "stream", 60 | "name": "stdout", 61 | "text": [ 62 | "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n", 63 | "Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (1.22.4)\n" 64 | ] 65 | } 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "source": [ 71 | "import numpy as np\n", 72 | "#accessing numpy in Python" 73 | ], 74 | "metadata": { 75 | "id": "PDQ8KPLPVOeu" 76 | }, 77 | "execution_count": 5, 78 | "outputs": [] 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "source": [ 83 | "" 87 | ], 88 | "metadata": { 89 | "id": "5mtTWYhJXOCt" 90 | } 91 | }, 92 | { 93 | "cell_type": "code", 94 | "source": [ 95 | "#creating an basic array\n", 96 | "basic_array = np.array([1, 2, 3])\n", 97 | "basic_array" 98 | ], 99 | "metadata": { 100 | "colab": { 101 | "base_uri": "https://localhost:8080/" 102 | }, 103 | "id": "EI1_znT8W3kP", 104 | "outputId": "4bf9c001-f14d-408b-eb4a-1a4ec89d1dae" 105 | }, 106 | "execution_count": 6, 107 | "outputs": [ 108 | { 109 | "output_type": "execute_result", 110 | "data": { 111 | "text/plain": [ 112 | "array([1, 2, 3])" 113 | ] 114 | }, 115 | "metadata": {}, 116 | "execution_count": 6 117 | } 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "source": [ 123 | "#creating an 2D array\n", 124 | "two_d = np.array([[1, 2, 3], [4, 5, 6]])\n", 125 | "two_d" 126 | ], 127 | "metadata": { 128 | "colab": { 129 | "base_uri": "https://localhost:8080/" 130 | }, 131 | "id": "wFvwIVwhYn2H", 132 | "outputId": "9c1f4aa6-5c34-4cfd-994a-7d5b9e82dd9a" 133 | }, 134 | "execution_count": 7, 135 | "outputs": [ 136 | { 137 | "output_type": "execute_result", 138 | "data": { 139 | "text/plain": [ 140 | "array([[1, 2, 3],\n", 141 | " [4, 5, 6]])" 142 | ] 143 | }, 144 | "metadata": {}, 145 | "execution_count": 7 146 | } 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "source": [ 152 | "#creating an array filled with 0's\n", 153 | "zeros = np.zeros(4)\n", 154 | "zeros" 155 | ], 156 | "metadata": { 157 | "colab": { 158 | "base_uri": "https://localhost:8080/" 159 | }, 160 | "id": "_qhavQSPZCw2", 161 | "outputId": "edfdcb00-2d4c-4ea2-d938-0d0babf5f565" 162 | }, 163 | "execution_count": 8, 164 | "outputs": [ 165 | { 166 | "output_type": "execute_result", 167 | "data": { 168 | "text/plain": [ 169 | "array([0., 0., 0., 0.])" 170 | ] 171 | }, 172 | "metadata": {}, 173 | "execution_count": 8 174 | } 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "source": [ 180 | "#creating an array filled with 1's\n", 181 | "ones = np.ones(4)\n", 182 | "ones" 183 | ], 184 | "metadata": { 185 | "colab": { 186 | "base_uri": "https://localhost:8080/" 187 | }, 188 | "id": "4LPSbe3pZmlG", 189 | "outputId": "8ab3a8ab-0ad0-4438-c256-c773a8941ffc" 190 | }, 191 | "execution_count": 10, 192 | "outputs": [ 193 | { 194 | "output_type": "execute_result", 195 | "data": { 196 | "text/plain": [ 197 | "array([1., 1., 1., 1.])" 198 | ] 199 | }, 200 | "metadata": {}, 201 | "execution_count": 10 202 | } 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "source": [ 208 | "#create an empty array with 4 elements\n", 209 | "#the result will be vary\n", 210 | "empty = np.empty(4)\n", 211 | "empty" 212 | ], 213 | "metadata": { 214 | "colab": { 215 | "base_uri": "https://localhost:8080/" 216 | }, 217 | "id": "w1lqUo2RaOuR", 218 | "outputId": "ff452bf3-39f7-4a5d-8a53-8f04c36abbab" 219 | }, 220 | "execution_count": 12, 221 | "outputs": [ 222 | { 223 | "output_type": "execute_result", 224 | "data": { 225 | "text/plain": [ 226 | "array([1., 1., 1., 1.])" 227 | ] 228 | }, 229 | "metadata": {}, 230 | "execution_count": 12 231 | } 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "source": [ 237 | "#creating an array using range\n", 238 | "range_ = np.array(range(1, 5))\n", 239 | "range_" 240 | ], 241 | "metadata": { 242 | "colab": { 243 | "base_uri": "https://localhost:8080/" 244 | }, 245 | "id": "9AHyRxtgaoPW", 246 | "outputId": "02ba6747-b7a7-4c5e-a743-8eea8d4d2987" 247 | }, 248 | "execution_count": 13, 249 | "outputs": [ 250 | { 251 | "output_type": "execute_result", 252 | "data": { 253 | "text/plain": [ 254 | "array([1, 2, 3, 4])" 255 | ] 256 | }, 257 | "metadata": {}, 258 | "execution_count": 13 259 | } 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "source": [ 265 | "#concatenating two arrays\n", 266 | "a1 = np.array([1, 2, 3])\n", 267 | "a2 = np.array([4, 5, 6])\n", 268 | "concate = np.concatenate((a1, a2))\n", 269 | "concate" 270 | ], 271 | "metadata": { 272 | "colab": { 273 | "base_uri": "https://localhost:8080/" 274 | }, 275 | "id": "8N3mE67_bBIm", 276 | "outputId": "3f578ce4-1eb3-46a9-a315-0f96c8f0fd20" 277 | }, 278 | "execution_count": 17, 279 | "outputs": [ 280 | { 281 | "output_type": "execute_result", 282 | "data": { 283 | "text/plain": [ 284 | "array([1, 2, 3, 4, 5, 6])" 285 | ] 286 | }, 287 | "metadata": {}, 288 | "execution_count": 17 289 | } 290 | ] 291 | }, 292 | { 293 | "cell_type": "markdown", 294 | "source": [ 295 | "

* To find dimension, shape, size of an array

" 296 | ], 297 | "metadata": { 298 | "id": "Fq62mR7-eUae" 299 | } 300 | }, 301 | { 302 | "cell_type": "code", 303 | "source": [ 304 | "#sample array\n", 305 | "sam = np.array([[[24, 45, 66, 78]], \n", 306 | " [[77, 86, 94, 36]],\n", 307 | " [[28, 53, 71, 90]]])\n", 308 | "sam" 309 | ], 310 | "metadata": { 311 | "colab": { 312 | "base_uri": "https://localhost:8080/" 313 | }, 314 | "id": "MH-3W1EFeDX4", 315 | "outputId": "54ad64b3-4fb8-43a0-8b5f-e20c3a5a569d" 316 | }, 317 | "execution_count": 18, 318 | "outputs": [ 319 | { 320 | "output_type": "execute_result", 321 | "data": { 322 | "text/plain": [ 323 | "array([[[24, 45, 66, 78]],\n", 324 | "\n", 325 | " [[77, 86, 94, 36]],\n", 326 | "\n", 327 | " [[28, 53, 71, 90]]])" 328 | ] 329 | }, 330 | "metadata": {}, 331 | "execution_count": 18 332 | } 333 | ] 334 | }, 335 | { 336 | "cell_type": "code", 337 | "source": [ 338 | "#to find the number of dimensions\n", 339 | "sam.ndim" 340 | ], 341 | "metadata": { 342 | "colab": { 343 | "base_uri": "https://localhost:8080/" 344 | }, 345 | "id": "FZkTKmgjfCMQ", 346 | "outputId": "c3994eae-574e-4b0b-8dad-31a984ea4323" 347 | }, 348 | "execution_count": 19, 349 | "outputs": [ 350 | { 351 | "output_type": "execute_result", 352 | "data": { 353 | "text/plain": [ 354 | "3" 355 | ] 356 | }, 357 | "metadata": {}, 358 | "execution_count": 19 359 | } 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "source": [ 365 | "#to find the shape\n", 366 | "sam.shape" 367 | ], 368 | "metadata": { 369 | "colab": { 370 | "base_uri": "https://localhost:8080/" 371 | }, 372 | "id": "4qI9b_XEfMM4", 373 | "outputId": "8eca288f-d52c-49c8-8ad3-8a926dc45713" 374 | }, 375 | "execution_count": 20, 376 | "outputs": [ 377 | { 378 | "output_type": "execute_result", 379 | "data": { 380 | "text/plain": [ 381 | "(3, 1, 4)" 382 | ] 383 | }, 384 | "metadata": {}, 385 | "execution_count": 20 386 | } 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "source": [ 392 | "#to find the size\n", 393 | "sam.size" 394 | ], 395 | "metadata": { 396 | "colab": { 397 | "base_uri": "https://localhost:8080/" 398 | }, 399 | "id": "NlDOC3lDfVPH", 400 | "outputId": "adbbe0b6-bb03-41d5-a111-aa9e9a022476" 401 | }, 402 | "execution_count": 21, 403 | "outputs": [ 404 | { 405 | "output_type": "execute_result", 406 | "data": { 407 | "text/plain": [ 408 | "12" 409 | ] 410 | }, 411 | "metadata": {}, 412 | "execution_count": 21 413 | } 414 | ] 415 | }, 416 | { 417 | "cell_type": "markdown", 418 | "source": [ 419 | "

* Most useful array operations

" 420 | ], 421 | "metadata": { 422 | "id": "LYuZyO7FgDFf" 423 | } 424 | }, 425 | { 426 | "cell_type": "code", 427 | "source": [ 428 | "#to find maximum\n", 429 | "sam.max()" 430 | ], 431 | "metadata": { 432 | "colab": { 433 | "base_uri": "https://localhost:8080/" 434 | }, 435 | "id": "0Xs0G2FtgJIn", 436 | "outputId": "6abebc45-8e1b-4e9f-913d-ab8b0498a1a7" 437 | }, 438 | "execution_count": 23, 439 | "outputs": [ 440 | { 441 | "output_type": "execute_result", 442 | "data": { 443 | "text/plain": [ 444 | "94" 445 | ] 446 | }, 447 | "metadata": {}, 448 | "execution_count": 23 449 | } 450 | ] 451 | }, 452 | { 453 | "cell_type": "code", 454 | "source": [ 455 | "#to find minimum\n", 456 | "sam.min()" 457 | ], 458 | "metadata": { 459 | "colab": { 460 | "base_uri": "https://localhost:8080/" 461 | }, 462 | "id": "MqXGAs0kgWnP", 463 | "outputId": "4ea2c8b8-62aa-4259-ebef-049908ded724" 464 | }, 465 | "execution_count": 24, 466 | "outputs": [ 467 | { 468 | "output_type": "execute_result", 469 | "data": { 470 | "text/plain": [ 471 | "24" 472 | ] 473 | }, 474 | "metadata": {}, 475 | "execution_count": 24 476 | } 477 | ] 478 | }, 479 | { 480 | "cell_type": "code", 481 | "source": [ 482 | "#to find sum\n", 483 | "sam.sum()" 484 | ], 485 | "metadata": { 486 | "colab": { 487 | "base_uri": "https://localhost:8080/" 488 | }, 489 | "id": "2oIoeyLOgb0H", 490 | "outputId": "198fceb0-bf50-4563-82cd-eb5caf7202f2" 491 | }, 492 | "execution_count": 25, 493 | "outputs": [ 494 | { 495 | "output_type": "execute_result", 496 | "data": { 497 | "text/plain": [ 498 | "748" 499 | ] 500 | }, 501 | "metadata": {}, 502 | "execution_count": 25 503 | } 504 | ] 505 | }, 506 | { 507 | "cell_type": "markdown", 508 | "source": [ 509 | "

* generating array with random numbers

" 510 | ], 511 | "metadata": { 512 | "id": "Z3b796elhtnx" 513 | } 514 | }, 515 | { 516 | "cell_type": "code", 517 | "source": [ 518 | "#generating array with random numbers\n", 519 | "#from 1, 10 in the shape of 2x4\n", 520 | "rng = np.random.default_rng() #to generate random numbers\n", 521 | "ran = rng.integers(10, size=(2, 4))\n", 522 | "ran" 523 | ], 524 | "metadata": { 525 | "colab": { 526 | "base_uri": "https://localhost:8080/" 527 | }, 528 | "id": "sWOsVYmyh1FI", 529 | "outputId": "f81514d0-6f4f-4e4b-dc44-c21af30ba7b6" 530 | }, 531 | "execution_count": 29, 532 | "outputs": [ 533 | { 534 | "output_type": "execute_result", 535 | "data": { 536 | "text/plain": [ 537 | "array([[0, 6, 3, 5],\n", 538 | " [1, 0, 2, 1]])" 539 | ] 540 | }, 541 | "metadata": {}, 542 | "execution_count": 29 543 | } 544 | ] 545 | }, 546 | { 547 | "cell_type": "markdown", 548 | "source": [ 549 | "

* getting unique items

" 550 | ], 551 | "metadata": { 552 | "id": "u6B-pvDAiwkp" 553 | } 554 | }, 555 | { 556 | "cell_type": "code", 557 | "source": [ 558 | "arr = np.array([11, 11, 12, 13, 14, 15, 16, 17, 12, 13, 11, 14, 18, 19, 20])\n", 559 | "uni = np.unique(arr)\n", 560 | "uni" 561 | ], 562 | "metadata": { 563 | "colab": { 564 | "base_uri": "https://localhost:8080/" 565 | }, 566 | "id": "nfOJ7mcwjESY", 567 | "outputId": "6fa3aa07-4ec8-4586-fe8e-c47ed1ef3c94" 568 | }, 569 | "execution_count": 30, 570 | "outputs": [ 571 | { 572 | "output_type": "execute_result", 573 | "data": { 574 | "text/plain": [ 575 | "array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20])" 576 | ] 577 | }, 578 | "metadata": {}, 579 | "execution_count": 30 580 | } 581 | ] 582 | }, 583 | { 584 | "cell_type": "markdown", 585 | "source": [ 586 | "

* Reversing an array

" 587 | ], 588 | "metadata": { 589 | "id": "l8o1FJvRj0yw" 590 | } 591 | }, 592 | { 593 | "cell_type": "code", 594 | "source": [ 595 | "#reverse an array\n", 596 | "rev = np.flip(uni)\n", 597 | "rev" 598 | ], 599 | "metadata": { 600 | "colab": { 601 | "base_uri": "https://localhost:8080/" 602 | }, 603 | "id": "LpdW_T9aj5xQ", 604 | "outputId": "35a5683b-3837-4f20-8ea0-62fa977febe1" 605 | }, 606 | "execution_count": 31, 607 | "outputs": [ 608 | { 609 | "output_type": "execute_result", 610 | "data": { 611 | "text/plain": [ 612 | "array([20, 19, 18, 17, 16, 15, 14, 13, 12, 11])" 613 | ] 614 | }, 615 | "metadata": {}, 616 | "execution_count": 31 617 | } 618 | ] 619 | }, 620 | { 621 | "cell_type": "markdown", 622 | "source": [ 623 | "

* Saving and load numpy objects

" 624 | ], 625 | "metadata": { 626 | "id": "a1aIuudxkjYg" 627 | } 628 | }, 629 | { 630 | "cell_type": "code", 631 | "source": [ 632 | "#saving a numpy object\n", 633 | "np.save(\"reverse\", rev) \n", 634 | "#it will save as reverse.npy " 635 | ], 636 | "metadata": { 637 | "id": "6ENnmxxJknvq" 638 | }, 639 | "execution_count": 33, 640 | "outputs": [] 641 | }, 642 | { 643 | "cell_type": "code", 644 | "source": [ 645 | "#loading an numpy file\n", 646 | "file_ = np.load(\"reverse.npy\")\n", 647 | "file_" 648 | ], 649 | "metadata": { 650 | "colab": { 651 | "base_uri": "https://localhost:8080/" 652 | }, 653 | "id": "6JW3ovC3lDGn", 654 | "outputId": "4e80a284-b628-48af-fed0-5a7c1524fbee" 655 | }, 656 | "execution_count": 34, 657 | "outputs": [ 658 | { 659 | "output_type": "execute_result", 660 | "data": { 661 | "text/plain": [ 662 | "array([20, 19, 18, 17, 16, 15, 14, 13, 12, 11])" 663 | ] 664 | }, 665 | "metadata": {}, 666 | "execution_count": 34 667 | } 668 | ] 669 | } 670 | ] 671 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Education 2 | 3 | ## sortedPython - sample code and examples of python sorted() function 4 | 5 | ## python_mysql_cheatcodes - a small guide of python and mysql database 6 | 7 | ## python_speech_recognition_text_to_speech - a small guide of using this dependencies for a voice assistant 8 | 9 | ## python_sqlite_cheatcodes - a small guide of python and sqlite database 10 | 11 | ## python_postgresql_cheatcodes - a small guide of python and postgresql database 12 | 13 | ## python_mongodb_cheatcodes - a small guide of python and mongodb database 14 | 15 | ## interview_programs - sample programs different and simple approach 16 | 17 | ## dsa_linked_list - sample linked list [Data structures & Alogorithms] 18 | 19 | ## dsa_stack - sample stack class created using collections deque 20 | 21 | ## dsa_binary_search_tree - sample BST 22 | 23 | ## unittest_folder - Test case used for unittest tutorial guide posted on linkedin 24 | 25 | ## pytest_folder - Test case for pytest tutorial guide posted on linkedin 26 | 27 | ## sending_mails - sending mails using python 28 | 29 | ## timeComplexityProgramms - Sample Programms and their time complexity 30 | 31 | ## CustomList_DynamicArray - Creating our own custom list (Dynamic Array) using ctypes module 32 | 33 | ## linked_list_dsa - Trying to create own singly linkedlist by using DS logic 34 | 35 | ## recurssion_workoutfile - Learning Recurssion! So, yes this is my workout file 36 | 37 | ## stack_dsa_tutorial - Stack datastructure 38 | 39 | ## aws_boto3_work_file - AWS boto3 tutorial file 40 | 41 | ## handlingGeoSpatialDatausingGeoPandas - Geo Pandas tutorial file 42 | 43 | ## profiling_in_python - profiling tools with sample code 44 | 45 | ## dataclasses_in_python - sample codes for @dataclass implementation 46 | 47 | ## subprocess in python - sample codes of subprocess module 48 | 49 | ## backtracking_problems - Backtracking using python 50 | 51 | ## ternary_operations - ternary operations using datastructures 52 | 53 | ## circuit_diagram - circuit diagram using python 54 | 55 | ## hangman-game - hangman game using python 56 | 57 | ![Screenshot from 2025-05-27 13-19-20](https://github.com/user-attachments/assets/fd9276dc-f6ed-49be-8066-d795b226e0e8) 58 | 59 | ## number-guessing-game - number guessing game using python 60 | 61 | ![Screenshot from 2025-05-27 13-20-15](https://github.com/user-attachments/assets/bc0f17c5-bf7e-468c-9b9b-e2363bfb6f44) 62 | -------------------------------------------------------------------------------- /Testing_using_pytest/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/Testing_using_pytest/__init__.py -------------------------------------------------------------------------------- /Testing_using_pytest/calculator.py: -------------------------------------------------------------------------------- 1 | class Calc: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | def add(self): 7 | return self.a+self.b 8 | def sub(self): 9 | return self.a-self.b 10 | def mul(self): 11 | return self.a*self.b 12 | def div(self): 13 | return self.a/self.b 14 | 15 | -------------------------------------------------------------------------------- /Testing_using_pytest/string_operators.py: -------------------------------------------------------------------------------- 1 | class str_operations: 2 | def __init__(self, str): 3 | self.str = str 4 | 5 | #for reversing a string 6 | def reverse_str(self): 7 | return self.str[::-1] 8 | #upper case 9 | def upper_str(self): 10 | return self.str.upper() 11 | #lower case 12 | def lower_str(self): 13 | return self.str.lower() 14 | -------------------------------------------------------------------------------- /Testing_using_pytest/test_calculator.py: -------------------------------------------------------------------------------- 1 | from .calculator import Calc 2 | 3 | 4 | class TestCalc: 5 | calc = Calc(12, 10) 6 | def test_add(self): 7 | assert self.calc.add() == 22, "Add test Failed" 8 | 9 | def test_sub(self): 10 | assert self.calc.sub() == 2, "Sub test failed" 11 | 12 | def test_mul(self): 13 | assert self.calc.mul() == 120, "Mul test failed" 14 | 15 | def test_div(self): 16 | assert self.calc.div() == 1.2, "Div test failed" 17 | 18 | -------------------------------------------------------------------------------- /Testing_using_pytest/test_string_ops.py: -------------------------------------------------------------------------------- 1 | from .string_operators import str_operations 2 | 3 | class TestStringOperations: 4 | str_op = str_operations("Arunisto") 5 | msg = "Test Failed" 6 | reverse_str = str_op.reverse_str() 7 | upper_str = str_op.upper_str() 8 | lower_str = str_op.lower_str() 9 | 10 | def test_reverse_str(self): 11 | assert self.reverse_str == "otsinurA", self.msg 12 | 13 | def test_upper_str(self): 14 | assert self.upper_str == "ARUNISTO", self.msg 15 | 16 | def test_lower_str(self): 17 | assert self.lower_str == "arunisto", self.msg 18 | 19 | -------------------------------------------------------------------------------- /aws_boto3_work_file.py: -------------------------------------------------------------------------------- 1 | import os 2 | import boto3 3 | from dotenv import load_dotenv 4 | import re 5 | from botocore.exceptions import ClientError 6 | import requests 7 | 8 | 9 | load_dotenv() 10 | 11 | s3_client = boto3.client('s3', 12 | aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"), 13 | aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"), 14 | region_name=os.environ.get("AWS_REGION"), 15 | config=boto3.session.Config(signature_version='s3v4')) 16 | s3_bucket_name = os.environ.get("AWS_BUCKET_NAME") 17 | print("Completed") 18 | 19 | #generating presigned URL 20 | def create_presigned_url(bucket_name, object_name): 21 | try: 22 | response = s3_client.generate_presigned_url( 23 | 'get_object', 24 | Params={ 25 | "Bucket":bucket_name, 26 | "Key":object_name, 27 | } 28 | ) 29 | return response 30 | except ClientError as e: 31 | return e 32 | """ 33 | url_link = create_presigned_url(s3_bucket_name, bike_image_key) 34 | #print(url_link) 35 | response = requests.get(url_link) 36 | print(response) 37 | """ 38 | #generating a presigned url to upload a file 39 | def create_presigned_post(bucket_name, object_name): 40 | try: 41 | response = s3_client.generate_presigned_post(bucket_name, 42 | object_name) 43 | except ClientError as e: 44 | print("Hello") 45 | return e 46 | return response 47 | 48 | object_name = "rb_logo.svg" 49 | """ 50 | url_link = create_presigned_url(s3_bucket_name, object_name) 51 | print(url_link) 52 | response = requests.get(url_link) 53 | print(response) 54 | """ 55 | """ 56 | response = create_presigned_post(s3_bucket_name, object_name) 57 | print(response) 58 | """ 59 | #access control list 60 | """ 61 | result = s3_client.get_bucket_acl(Bucket=s3_bucket_name) 62 | print(result) 63 | """ 64 | 65 | #retrieving the list of buckets 66 | """ 67 | response = s3_client.list_buckets() 68 | for bucket in response['Buckets']: 69 | print(bucket["Name"]) 70 | """ 71 | 72 | #uploading file 73 | def upload_file(filename, bucket, object_name=None): 74 | if object_name is None: 75 | object_name = os.path.basename(filename) 76 | 77 | try: 78 | response = s3_client.upload_file(filename, bucket, object_name) 79 | except ClientError as e: 80 | print(e) 81 | return False 82 | return True 83 | """ 84 | response = upload_file("rb_logo.svg", s3_bucket_name) 85 | print(response) 86 | """ 87 | """ 88 | print(os.path.basename(object_name)) 89 | """ 90 | 91 | #downloading a file 92 | def download_file(bucket_name, object_name, file_name): 93 | try: 94 | response = s3_client.download_file(bucket_name, object_name, file_name) 95 | except ClientError as e: 96 | print(e) 97 | return False 98 | return True 99 | 100 | response = download_file(s3_bucket_name, "rb_logo.svg", "rb_logo.svg") 101 | print(response) 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /backtracking_problems.py: -------------------------------------------------------------------------------- 1 | #subset or powerset 2 | def backtrack_subsets(nums): 3 | result = [] 4 | 5 | def backtrack(start, path): 6 | #adding the current subset to the result 7 | result.append(path[:]) 8 | #exploring further elements 9 | for i in range(start, len(nums)): 10 | #choosing the current number 11 | path.append(nums[i]) 12 | #backtracking exploring from next index 13 | backtrack(i+1, path) 14 | #undo the choice 15 | path.pop() 16 | backtrack(0, []) 17 | return result 18 | """ 19 | nums = [1, 2, 3, 4] 20 | print("All subsets", backtrack_subsets(nums)) 21 | """ 22 | def getting_all_substrings(a:str): 23 | result = [] 24 | #converting the strings to list 25 | list_str = list(a) 26 | def substrings(start, path): 27 | #adding current subset to the result 28 | result.append(path[:]) 29 | for i in range(start, len(list_str)): 30 | path.append(list_str[i]) 31 | substrings(i+1, path) 32 | path.pop() 33 | substrings(0, []) 34 | return result 35 | """ 36 | s = "ADOBECODEBANC" 37 | print(getting_all_substrings(s)) 38 | """ 39 | # trying to get the subsets without the empty array 40 | def subset_without_empty_array(arr:list): 41 | result = [] 42 | def backtrack_logic(start, path): 43 | if path: 44 | result.append(path[:]) 45 | for i in range(start, len(arr)): 46 | path.append(arr[i]) 47 | backtrack_logic(i+1, path) 48 | path.pop() 49 | backtrack_logic(0, []) 50 | return result 51 | """ 52 | nums = [1, 2, 2] 53 | print(subset_without_empty_array(nums)) 54 | """ 55 | # removing duplicates subsets 56 | def subset_without_duplicates(arr:list): 57 | result = [] 58 | def backtrack_logic(start, path): 59 | if path: 60 | result.append(path[:]) 61 | for i in range(start, len(arr)): 62 | if i > start and arr[i] == arr[i-1]: 63 | continue 64 | path.append(arr[i]) 65 | backtrack_logic(i+1, path) 66 | path.pop() 67 | backtrack_logic(0, []) 68 | return result 69 | """ 70 | nums = [1, 2, 3] 71 | print(subset_without_duplicates(nums)) 72 | """ 73 | # generating all binary strings using length N 74 | def generate_binary_str(n): 75 | result = [] 76 | def backtrack_logic(current_string): 77 | if len(current_string) == n: 78 | result.append(current_string) 79 | return 80 | backtrack_logic(current_string+"0") 81 | backtrack_logic(current_string+"1") 82 | backtrack_logic('') 83 | return result 84 | 85 | """ 86 | print(generate_binary_str(2)) 87 | """ 88 | 89 | 90 | -------------------------------------------------------------------------------- /circuit_diagram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Circuit Diagrams using Python 3 | ----------------------------- 4 | Schemdraw is a python package for producing high-quality electrical circuit 5 | schematic diagrams. Included are symbols for basic electrical components 6 | (resistors, capacitors, diodes, transistors, etc.), opamps and 7 | signal processing elements. 8 | Additionally, Schemdraw can produce digital timing diagrams, state machine diagrams, 9 | and flowcharts. 10 | """ 11 | import schemdraw 12 | import schemdraw.elements as elm 13 | 14 | with schemdraw.Drawing(color="red") as d: 15 | elm.Resistor().label('100KΩ') 16 | elm.Capacitor().down().label('0.1μF', loc='bottom') 17 | elm.Line().left() 18 | elm.Ground() 19 | elm.SourceV().up().label('10V') 20 | -------------------------------------------------------------------------------- /dataclasses_in_python.py: -------------------------------------------------------------------------------- 1 | # class without dataclass 2 | """ 3 | class Person: 4 | def __init__(self, name, age): 5 | self.name = name 6 | self.age = age 7 | 8 | def __repr__(self): 9 | return f"Name:{self.name}, Age:{self.age}" 10 | 11 | per1 = Person("Arun", 28) 12 | print(per1) #Name:Arun, Age:28 13 | """ 14 | #class with dataclass 15 | """ 16 | from dataclasses import dataclass 17 | 18 | @dataclass 19 | class Person: 20 | name: str 21 | age: int 22 | 23 | per1 = Person("Arun", 28) 24 | print(per1) #Person(name='Arun', age=28) 25 | """ 26 | # default values and immutability 27 | """ 28 | from dataclasses import dataclass 29 | 30 | @dataclass(frozen=True) #makes immutable 31 | class Product: 32 | name: str 33 | price: float = 0.0 #default value 34 | in_stock: bool = True #default 35 | 36 | item = Product("Phone", 999) 37 | print(item) #Product(name='Phone', price=999, in_stock=True) 38 | # This will raise an error because frozen=True makes it immutable 39 | item.price = 1000 #FrozenInstanceError 40 | """ 41 | # class with custom methods 42 | """ 43 | from dataclasses import dataclass 44 | 45 | @dataclass 46 | class Employee: 47 | name: str 48 | emp_id: int 49 | salary: float 50 | 51 | def give_raise(self, percentage): 52 | self.salary+=self.salary*(percentage/100) 53 | 54 | emp = Employee("Arun", 101, 50000) 55 | print(emp) #Employee(name='Arun', emp_id=101, salary=50000) 56 | emp.give_raise(10) 57 | print(emp) #Employee(name='Arun', emp_id=101, salary=55000.0) 58 | """ 59 | # nested dataclasses 60 | """ 61 | from dataclasses import dataclass 62 | 63 | @dataclass 64 | class Company: 65 | reg_name: str 66 | city: str 67 | 68 | @dataclass 69 | class Employee: 70 | name: str 71 | role: str 72 | company: Company 73 | 74 | com = Company("RB", "BNG") 75 | emp = Employee("Arun", "dev", com) 76 | print(emp) 77 | #Employee(name='Arun', role='dev', company=Company(reg_name='RB', city='BNG')) 78 | """ 79 | # ordering and comparison 80 | """ 81 | from dataclasses import dataclass 82 | 83 | @dataclass(order=True) 84 | class Employee: 85 | name: str 86 | salary: int 87 | 88 | emp1 = Employee("Arunisto", 5000) 89 | emp2 = Employee("Arun", 1000) 90 | 91 | print(emp2 > emp1) 92 | #False (Compares attributes in order: name, salary) 93 | print(sorted([emp1, emp2])) 94 | """ 95 | """ 96 | result: 97 | [Employee(name='Arun', salary=1000), Employee(name='Arunisto', salary=5000)] 98 | """ 99 | # post-initialization with __post_init__ 100 | """ 101 | from dataclasses import dataclass 102 | 103 | @dataclass 104 | class Rectangle: 105 | width: int 106 | height: int 107 | area: int = 0 # will be compute 108 | 109 | def __post_init__(self): 110 | self.area = self.width*self.height 111 | 112 | rect = Rectangle(40, 50) 113 | print(rect) #Rectangle(width=40, height=50, area=2000) 114 | """ 115 | # inheritance with dataclass 116 | from dataclasses import dataclass 117 | 118 | @dataclass 119 | class Vehicle: 120 | make: str 121 | year: int 122 | 123 | @dataclass 124 | class Car(Vehicle): 125 | model: str 126 | doors: int = 4 127 | 128 | car = Car(make="Toyota", year=2020, model="Camry") 129 | print(car) 130 | #Car(make='Toyota', year=2020, model='Camry', doors=4) 131 | -------------------------------------------------------------------------------- /dsa_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | sample 3 | left right 4 | 15 5 | / \ 6 | 12 23 7 | / \ / \ 8 | 7 14 20 27 9 | \ 10 | 88 11 | """ 12 | 13 | #binary_search_tree 14 | class bstNode: 15 | def __init__(self, data): 16 | self.data = data 17 | self.left = None 18 | self.right = None 19 | 20 | #adding child 21 | def add_child(self, data): 22 | #checking if the data already there 23 | #because BST never allows duplicates 24 | if data == self.data: 25 | return 26 | 27 | #adding data by checking greater than or lesser 28 | #lesser it will move to the left 29 | #otherwise right 30 | if data < self.data: 31 | #checking if left have data 32 | if self.left: 33 | #recurssion method 34 | self.left.add_child(data) 35 | else: 36 | self.left = bstNode(data) 37 | else: 38 | if self.right: 39 | self.right.add_child(data) 40 | else: 41 | self.right = bstNode(data) 42 | 43 | 44 | #displaying elements in the order of traversal 45 | def in_order_traversal(self): 46 | elements = [] 47 | 48 | #first visiting left tree 49 | if self.left: 50 | elements+=self.left.in_order_traversal() 51 | 52 | #visiting the base node 53 | elements.append(self.data) 54 | 55 | #visiting the right tree 56 | if self.right: 57 | elements+=self.right.in_order_traversal() 58 | 59 | return elements 60 | 61 | #displaying elements in the pre-order traversal 62 | def pre_order_traversal(self): 63 | elements = [self.data] 64 | if self.left: 65 | elements+=self.left.pre_order_traversal() 66 | if self.right: 67 | elements+=self.right.pre_order_traversal() 68 | return elements 69 | 70 | #displaying elements in the post-order traversal 71 | def post_order_traversal(self): 72 | elements = [] 73 | if self.left: 74 | elements += self.left.post_order_traversal() 75 | if self.right: 76 | elements += self.right.post_order_traversal() 77 | 78 | elements.append(self.data) 79 | return elements 80 | 81 | #displaying elements in the level-order traversal 82 | def level_order_traversal(self): 83 | elements = [] 84 | queue = [] 85 | queue.append(self) #appending entire node 86 | while len(queue) != 0: 87 | current_node = queue.pop(0) 88 | elements.append(current_node.data) 89 | if current_node.left: 90 | queue.append(current_node.left) 91 | if current_node.right: 92 | queue.append(current_node.right) 93 | 94 | return elements 95 | 96 | 97 | 98 | #searching inside the tree 99 | def search(self, value): 100 | #checking the self.data is the value 101 | if self.data == value: 102 | return True 103 | 104 | #or checking in the left tree 105 | if value < self.data: 106 | if self.left: 107 | #recursion 108 | return self.left.search(value) 109 | else: 110 | return False 111 | 112 | #checking on the right tree 113 | if value > self.data: 114 | if self.right: 115 | #recursion 116 | return self.right.search(value) 117 | else: 118 | return False 119 | 120 | #finding minimum from BST 121 | def find_min(self): 122 | if self.left is None: 123 | return self.data 124 | return self.left.find_min() 125 | 126 | #finding maximum from BST 127 | def find_max(self): 128 | if self.right is None: 129 | return self.data 130 | return self.right.find_max() 131 | 132 | #calculate sum 133 | def calculate_sum(self): 134 | left_sum = self.left.calculate_sum() if self.left else 0 135 | right_sum = self.right.calculate_sum() if self.right else 0 136 | return self.data+left_sum+right_sum 137 | 138 | #delete function first apporach 139 | def delete_data(self, data): 140 | #checking value lesser than 141 | if data < self.data: 142 | if self.left: 143 | self.left = self.left.delete_data(data) 144 | #checking value greater than 145 | elif data > self.data: 146 | if self.right: 147 | self.right = self.right.delete_data(data) 148 | else: 149 | if self.left is None and self.right is None: 150 | return None 151 | if self.left is None: 152 | return self.right 153 | if self.right is None: 154 | return self.right 155 | 156 | min_val = self.right.find_min() 157 | self.data = min_val 158 | self.right = self.right.delete_data(min_val) 159 | 160 | return self 161 | 162 | #delete using 2nd apporach 163 | def delete_data_2(self, data): 164 | #checking value lesser than 165 | if data < self.data: 166 | if self.left: 167 | self.left = self.left.delete_data(data) 168 | #checking value greater than 169 | elif data > self.data: 170 | if self.right: 171 | self.right = self.right.delete_data(data) 172 | else: 173 | if self.left is None and self.right is None: 174 | return None 175 | if self.left is None: 176 | return self.right 177 | if self.right is None: 178 | return self.right 179 | 180 | min_val = self.left.find_max() 181 | self.data = min_val 182 | self.left = self.left.delete_data(min_val) 183 | 184 | return self 185 | 186 | #getting height of the leaves left 187 | def get_height_left(self): 188 | if self.left is None: 189 | return 0 190 | hl = self.left.get_height_left() 191 | return hl+1 192 | 193 | #getting height of the leaves right 194 | def get_height_right(self): 195 | if self.right is None: 196 | return 0 197 | hr = self.right.get_height_right() 198 | return hr+1 199 | 200 | 201 | #function for building tree 202 | def build_tree(elements): 203 | #adding the first element as base node 204 | root = bstNode(elements[0]) 205 | 206 | 207 | for i in range(1, len(elements)): 208 | root.add_child(elements[i]) 209 | 210 | return root 211 | 212 | if __name__ == "__main__": 213 | numbers = [3, 5, 4, 7, 2, 1] 214 | numbers_tree = build_tree(numbers) 215 | print(numbers_tree.in_order_traversal()) 216 | print(numbers_tree.pre_order_traversal()) 217 | print(numbers_tree.level_order_traversal()) 218 | #numbers = [15,12,7,14,27,20,23,88] 219 | #numbers_tree = build_tree(numbers) 220 | 221 | #numbers_hr = [3, 5, 2, 1, 4, 6, 7] 222 | #numbers_hr_tree = build_tree(numbers_hr) 223 | """print(numbers_hr_tree.in_order_traversal()) 224 | print(numbers_hr_tree.get_height_right()) 225 | print(numbers_hr_tree.get_height_left()) 226 | print(numbers_tree.in_order_traversal()) 227 | print(numbers_tree.search(88)) 228 | print(numbers_tree.search(15)) 229 | print(numbers_tree.search(2)) 230 | print(numbers_tree.search(155)) 231 | print(numbers_tree.find_min()) 232 | print(numbers_tree.find_max()) 233 | print(numbers_tree.pre_order_traversal()) 234 | print(numbers_tree.post_order_traversal()) 235 | print(numbers_tree.calculate_sum()) 236 | numbers_tree.delete_data(20) 237 | print(numbers_tree.in_order_traversal()) 238 | numbers_tree.delete_data(14) 239 | print(numbers_tree.in_order_traversal()) 240 | numbers_tree.delete_data_2(27) 241 | print(numbers_tree.in_order_traversal()) 242 | print(numbers_tree.get_height_left())""" 243 | -------------------------------------------------------------------------------- /dsa_linked_list.py: -------------------------------------------------------------------------------- 1 | class Node: #creating a class node 2 | def __init__(self, data, next=None): 3 | self.data = data 4 | self.next = next 5 | 6 | class LinkedList: #LinkedList class 7 | def __init__(self): 8 | self.head = None 9 | 10 | #functions like adding element deleting element 11 | def insert_at_end(self, data): 12 | # adding node[contains data] to head if head is None 13 | if self.head is None: 14 | new_node = Node(data) 15 | self.head = new_node 16 | return 17 | 18 | #adding data back2back 19 | current_data = self.head 20 | while current_data.next: 21 | current_data = current_data.next 22 | current_data.next = Node(data) 23 | 24 | #adding multiple data into linkedlist 25 | def insert_many_at_once(self, data, empty=False): 26 | #if empty change into True it will remove all existing elements 27 | if empty: 28 | self.head = None 29 | for d in data: 30 | self.insert_at_end(d) 31 | 32 | #inserting elements at beginning of the nodes 33 | def insert_at_start(self, data): 34 | new_node = Node(data, self.head) 35 | self.head = new_node 36 | 37 | #getting length of the list 38 | def get_length(self): 39 | #if data none it will return 0 40 | if self.head is None: 41 | print(0) 42 | return 43 | 44 | #total data 45 | total = 0 46 | data_iter = self.head 47 | while data_iter: 48 | total+=1 49 | data_iter = data_iter.next 50 | return total #it will print the total data 51 | 52 | #removing the last element from the list 53 | def remove_at_end(self): 54 | if self.head is None: 55 | print("List is empty") 56 | return 57 | #removing last element 58 | count = 0 59 | data_iter = self.head 60 | while data_iter: 61 | count+=1 62 | if count == self.get_length()-1: 63 | data_iter.next = data_iter.next.next 64 | break 65 | data_iter = data_iter.next 66 | 67 | #removing the first element from the list 68 | def remove_at_start(self): 69 | if self.head is None: 70 | print("List is empty") 71 | return 72 | self.head = self.head.next 73 | 74 | #inserting using index 75 | def insert_index(self, index, data): 76 | if index < 0 or index > self.get_length(): 77 | raise IndexError("Index not in range") 78 | #if index is 0 79 | if index == 0: 80 | new_node = Node(data, self.head) 81 | self.head = new_node 82 | 83 | count = 0 84 | data_iter = self.head 85 | while data_iter: 86 | count+=1 87 | if count == index: 88 | new_node = Node(data, data_iter.next) 89 | data_iter.next = new_node 90 | break 91 | data_iter = data_iter.next 92 | 93 | #removing data using index 94 | def remove_index(self, index): 95 | if index < 0 or index >= self.get_length(): 96 | raise IndexError("Index not in range") 97 | #removing if position is 0 98 | if index == 0: 99 | self.head = self.head.next 100 | return 101 | 102 | count = 0 103 | data_iter = self.head 104 | while data_iter: 105 | if count == index-1: 106 | data_iter.next = data_iter.next.next 107 | break 108 | count+=1 109 | data_iter = data_iter.next 110 | 111 | #removing data using data 112 | def remove_data(self, data): 113 | data_iter = self.head 114 | previous = None 115 | while data_iter: 116 | if data_iter.data == data: 117 | if previous: 118 | previous.next = data_iter.next 119 | else: 120 | self.head = data_iter.next 121 | return 122 | previous = data_iter 123 | data_iter = data_iter.next 124 | 125 | #removing duplicates 126 | def remove_duplicates(self): 127 | current = self.head 128 | duplicates = {} 129 | while current: 130 | if current.data not in duplicates: 131 | duplicates[current.data] = 1 132 | current = current.next 133 | else: 134 | next_data = current.next 135 | self.remove_data(current.data) 136 | current = next_data 137 | 138 | #displaying the data 139 | def display_data(self): 140 | if self.head is None: 141 | print("List is Empty") 142 | return 143 | 144 | #if self.head containing data 145 | data_iter = self.head 146 | while data_iter: 147 | print(data_iter.data, end=" ") 148 | data_iter = data_iter.next 149 | 150 | if __name__ == "__main__": 151 | li = LinkedList() 152 | li.insert_at_end(25) 153 | li.insert_at_end(45) 154 | li.insert_at_end(75) 155 | li.insert_many_at_once([12, 34, 56, 78]) 156 | li.insert_at_start("Arunisto") 157 | print("Length:",li.get_length()) 158 | li.remove_at_end() 159 | li.remove_at_end() 160 | li.remove_at_start() 161 | li.insert_index(2, 80) 162 | li.insert_index(0, "arun") 163 | li.insert_index(7, "Hello") 164 | li.remove_index(0) 165 | li.remove_index(2) 166 | li.remove_index(5) 167 | li.remove_data(25) 168 | li.remove_data(75) 169 | li.display_data() 170 | 171 | 172 | -------------------------------------------------------------------------------- /dsa_stack.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Stack: 4 | def __init__(self): 5 | self.stack = deque() 6 | 7 | #push 8 | def push(self, value): 9 | self.stack.append(value) 10 | 11 | #pop 12 | def pop(self): 13 | if len(self.stack) == 0: 14 | print("Stack is empty") 15 | return 16 | self.stack.pop() 17 | 18 | #length 19 | def length(self): 20 | return len(self.stack) 21 | 22 | #peek 23 | def peek(self): 24 | return self.stack[-1] 25 | 26 | #print 27 | def display(self): 28 | print(self.stack) 29 | 30 | 31 | if __name__ == "__main__": 32 | s = Stack() 33 | s.push("https://google.com/") 34 | s.push("https://drive.google.com/") 35 | s.push("https://mail.google.com/") 36 | s.display() 37 | s.pop() 38 | s.display() 39 | print(s.length()) 40 | print(s.peek()) 41 | s.pop() 42 | s.pop() 43 | s.pop() 44 | -------------------------------------------------------------------------------- /hangman-game/__pycache__/list_of_words.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/hangman-game/__pycache__/list_of_words.cpython-312.pyc -------------------------------------------------------------------------------- /hangman-game/hangman_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | from list_of_words import words_list 3 | 4 | stage = { 5 | 0:r""" 6 | +---+ 7 | | | 8 | | 9 | | 10 | | 11 | | 12 | ========= 13 | """, 14 | 1:r""" 15 | +---+ 16 | | | 17 | O | 18 | | 19 | | 20 | | 21 | ========= 22 | """, 23 | 2:r""" 24 | +---+ 25 | | | 26 | O | 27 | | | 28 | | 29 | | 30 | ========= 31 | """, 32 | 3:r""" 33 | +---+ 34 | | | 35 | O | 36 | /| | 37 | | 38 | | 39 | ========= 40 | """, 41 | 4:r""" 42 | +---+ 43 | | | 44 | O | 45 | /|\ | 46 | | 47 | | 48 | ========= 49 | """, 50 | 5:r""" 51 | +---+ 52 | | | 53 | O | 54 | /|\ | 55 | / | 56 | | 57 | ========= 58 | """, 59 | 6:r""" 60 | +---+ 61 | | | 62 | O | 63 | /|\ | "Sorry!! He's dead better luck next time" 64 | / \ | 65 | | 66 | ========= 67 | """ 68 | } 69 | 70 | sucess = r""" 71 | +---+ 72 | | 73 | | 74 | \O/ | "You save the day!!" 75 | | | 76 | / \ | 77 | ========= 78 | """ 79 | 80 | welcome_message = r""" 81 | _____________ 82 | | | 83 | | 0 84 | | /|\ 85 | | / \ 86 | | 87 | | 88 | ___ ___ Created by: Arun Arunisto 89 | / | \_____ ____ ____ _____ _____ ____ 90 | / ~ \__ \ / \ / ___\ / \\__ \ / \ 91 | \ Y // __ \| | \/ /_/ > Y Y \/ __ \| | \ 92 | \___|_ /(____ /___| /\___ /|__|_| (____ /___| / 93 | \/ \/ \//_____/ \/ \/ \/ 94 | 95 | """ 96 | def hangman_stages(step: int): 97 | return stage.get(step) 98 | 99 | def get_random_word(li: list): 100 | return random.choice(li) 101 | 102 | def generate_empty_list(word: str): 103 | return ["_" for i in word] 104 | 105 | def index_of_guessed_alphabet(word: str, alphabet: str, guessed_list: list): 106 | index_li = [i for i, letter in enumerate(word) if letter==alphabet] 107 | for i in index_li: 108 | if guessed_list[i] == "_": 109 | guessed_list[i] = alphabet 110 | break 111 | return guessed_list 112 | 113 | 114 | 115 | def game(word: str, empty_li: list): 116 | step = 0 117 | while step < 7: 118 | print(empty_li) 119 | print(f"Remaning rounds: {7-step}") 120 | guess = input("Guess the alphabets to fill in the blanks and save the man: ") 121 | if guess in word: 122 | index_of_guessed_alphabet(word, guess, empty_li) 123 | if "_" not in empty_li: 124 | print(sucess) 125 | break 126 | else: 127 | print(hangman_stages(step)) 128 | step += 1 129 | print("The answer is:",word) 130 | 131 | def main(): 132 | while True: 133 | options = input("[1] Start the game [2] Quit the game\nEnter the option: ") 134 | if options == "1": 135 | word = get_random_word(words_list) 136 | empty_li = generate_empty_list(word) 137 | game(word, empty_li) 138 | elif options == "2": 139 | break 140 | else: 141 | print("Invalid option!!") 142 | if __name__ == "__main__": 143 | print(welcome_message) 144 | main() 145 | 146 | -------------------------------------------------------------------------------- /hangman-game/list_of_words.py: -------------------------------------------------------------------------------- 1 | from english_words import get_english_words_set 2 | 3 | # Retrieve the set of English words 4 | english_words = get_english_words_set(['web2'], lower=True) 5 | 6 | # Define a list of common computer-related keywords 7 | computer_keywords = ['computer', 'network', 'data', 'software', 'hardware', 'program', 'code', 'algorithm', 'database', 'internet'] 8 | 9 | # Filter words that contain any of the computer-related keywords 10 | computer_terms = [word for word in english_words if any(keyword in word for keyword in computer_keywords)] 11 | 12 | # Display the first 100 computer-related terms 13 | words_list = computer_terms[:100] 14 | # print(words_list) 15 | -------------------------------------------------------------------------------- /interview_programs.py: -------------------------------------------------------------------------------- 1 | """ 2 | * 3 | * * 4 | * * * 5 | * * * * 6 | * * * * * 7 | Q1: Pattern program 8 | """ 9 | #solution 1 10 | def pyramidPattern(n): 11 | for i in range(n): #<- rows 12 | #loop for the space 13 | for j in range(1, n-i): #<- columns 14 | print(" ", end="") 15 | #loop for the star with a space 16 | for s in range(i+1): #<- columns 17 | print("*", end=" ") 18 | #for splitting columns 19 | print() 20 | 21 | pyramidPattern(5) 22 | """ 23 | * * * * * 24 | * * * * 25 | * * * 26 | * * 27 | * 28 | Q2: Reverse pattern 29 | """ 30 | #solution2 31 | def reversePyramid(n): 32 | for i in range(n): #<- rows 33 | for j in range(i): #<- space columns 34 | print(" ", end="") 35 | for s in range(n-i): #<- star columns with one space 36 | print("*", end=" ") 37 | print() #<- splitting columns 38 | 39 | reversePyramid(5) 40 | 41 | """ 42 | ********** 43 | **** **** 44 | *** *** 45 | ** ** 46 | * * 47 | * * 48 | ** ** 49 | *** *** 50 | **** **** 51 | ********** 52 | Q3: Card pattern 53 | """ 54 | #solution3 55 | def cardPattern(n): 56 | """ 57 | code for the first half pattern 58 | ********** 59 | **** **** 60 | *** *** 61 | ** ** 62 | * * 63 | """ 64 | for i in range(n): 65 | for j in range(n-i): 66 | print("*", end="") 67 | for s in range(i): 68 | print(" ", end=" ") 69 | for p in range(n-i): 70 | print("*", end="") 71 | print() 72 | """ 73 | Again code for another half 74 | * * 75 | ** ** 76 | *** *** 77 | **** **** 78 | ********** 79 | """ 80 | for i in range(n): 81 | for j in range(i+1): 82 | print("*", end="") 83 | for s in range(1, n-i): 84 | print(" ",end=" ") 85 | for p in range(i+1): 86 | print("*", end="") 87 | print() 88 | cardPattern(5) 89 | """ 90 | 0 91 | 1 2 92 | 3 4 5 93 | 6 7 8 9 94 | Q4: numeric pattern 95 | """ 96 | #solution4 97 | def numericPattern(n): 98 | no = 0 99 | for i in range(n): 100 | for j in range(1, n-i): 101 | print(" ", end="") 102 | for s in range(i+1): 103 | print(no, end=" ") 104 | no+=1 105 | print() 106 | numericPattern(4) 107 | """ 108 | str = "arunisto" 109 | rev = "otsinura" 110 | Q5: Reverse a string using for loop 111 | """ 112 | #solution5 113 | def reverse(str): 114 | s = "".join( 115 | list( 116 | str[i] for i in range(len(str)-1, -1, -1) 117 | ) 118 | ) 119 | return s 120 | print(reverse("arunisto")) 121 | """ 122 | li = ["arun", "arunisto", "python"] 123 | reverse = ["python", "arunisto", "arunisto"] 124 | Q6: Reversing a list using for loop 125 | """ 126 | #solution6 127 | def reverseList(list): 128 | new_li = [list[i] for i in range(len(list)-1, -1, -1)] 129 | return new_li 130 | print(reverseList(["arun", "arunisto", "python"])) 131 | """ 132 | Function for converting integer to binary 133 | """ 134 | def binaryNumber(num): 135 | bin_li = [] 136 | half = num 137 | while half > 0: 138 | temp = half 139 | half//=2 140 | bin_li.insert(0, str(temp%2)) 141 | return "".join(bin_li) 142 | """ 143 | Fibonacci number function 144 | """ 145 | def fibonacciNum(num): 146 | fib_li = [] 147 | num1 = 0 148 | num2 = 1 149 | for i in range(num): 150 | fib_li.append(num1) 151 | temp = num1 152 | num1 = num2 153 | num2+=temp 154 | print(*fib_li) 155 | """ 156 | Primenumber or not 157 | """ 158 | def isPrime(num): 159 | if num < 2: 160 | return False 161 | if num > 2: 162 | for i in range(2, (num//2)+1): 163 | if num%i == 0: 164 | return False 165 | return True 166 | """ 167 | Function for converting binary to integer 168 | """ 169 | def binary2Integer(binary): 170 | bin_li = [] 171 | for i in range(len(str(binary))-1, -1, -1): 172 | bin_li.append(str(binary)[i]) 173 | result = 0 174 | for i in range(len(bin_li)): 175 | result+=(int(bin_li[i])*(2**i)) 176 | return result 177 | """ 178 | HackerRank Day 11: 2D arrays 179 | """ 180 | li = [[1, 1, 1, 0, 0, 0], 181 | [0, 1, 0, 0, 0, 0], 182 | [1, 1, 1, 0, 0, 0], 183 | [0, 0, 2, 4, 4, 0], 184 | [0, 0, 0, 2, 0, 0], 185 | [0, 0, 1, 2, 4, 0]] 186 | #print(li) 187 | sum = 0 188 | tarr = [] 189 | for l in range(0, 4): 190 | for k in range(0, 4): 191 | for i in range(l,l+3): 192 | #print(f"i:{i}", end="") 193 | for j in range(k,k+3): 194 | if i == l+1 and (j == k or j == k+2): 195 | #print("i",i,"j",j,"l",l,"k",k) 196 | continue 197 | else: 198 | sum+=li[i][j] 199 | tarr.append(sum) 200 | sum = 0 201 | print(max(tarr)) 202 | """ 203 | Bubble sort 204 | """ 205 | def bubbleSort(arr): 206 | for i in range(len(arr)): 207 | for j in range(len(arr)-1): 208 | if arr[j] > arr[j+1]: 209 | arr[j], arr[j+1] = arr[j+1], arr[j] 210 | return arr 211 | """ 212 | prime number with less time complexity 213 | """ 214 | def prime_number(number): 215 | if number <= 1: 216 | return False 217 | if number == 2: 218 | return True 219 | if number%2 == 0: 220 | return False 221 | for i in range(3, int(number**0.5)+1, 2): 222 | if number %i == 0: 223 | return False 224 | return True 225 | """ 226 | Text Wrap 227 | """ 228 | import textwrap 229 | 230 | string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 231 | width = 4 232 | 233 | print(textwrap.wrap(string, width)) 234 | #output: 235 | """ 236 | ['ABCD', 'EFGH', 'IJKL', 'MNOP', 'QRST', 'UVWX', 'YZ'] 237 | """ 238 | 239 | print(textwrap.fill(string, width)) 240 | #output: 241 | """ 242 | ABCD 243 | EFGH 244 | IJKL 245 | MNOP 246 | QRST 247 | UVWX 248 | YZ 249 | """ 250 | """ 251 | Method overloading using multipledispatch module 252 | """ 253 | from multipledispatch import dispatch 254 | 255 | class sampleClass: 256 | @dispatch(int, int) 257 | def add(self, a, b): 258 | return a+b 259 | 260 | @dispatch(int, int, int) 261 | def add(self, a, b, c): 262 | return a+b+c 263 | 264 | obj = sampleClass() 265 | print(obj.add(23, 45)) #68 266 | print(obj.add(23, 45, 66)) #134 267 | """ 268 | ---------.|.--------- 269 | ------.|..|..|.------ 270 | ---.|..|..|..|..|.--- 271 | -------WELCOME------- 272 | ---.|..|..|..|..|.--- 273 | ------.|..|..|.------ 274 | ---------.|.--------- 275 | """ 276 | n = 7 277 | m = 21 278 | for i in range(n//2): 279 | j = int((2*i)+1) 280 | print(('.|.'*j).center(m, '-')) 281 | print('WELCOME'.center(m, '-')) 282 | for i in reversed(range(n//2)): 283 | j = int((2*i)+1) 284 | print(('.|.'*j).center(m, '-')) 285 | """ 286 | 1 1 1 1 287 | 2 2 2 10 288 | 3 3 3 11 289 | 4 4 4 100 290 | 5 5 5 101 291 | 6 6 6 110 292 | 7 7 7 111 293 | 8 10 8 1000 294 | 9 11 9 1001 295 | 10 12 A 1010 296 | 11 13 B 1011 297 | 12 14 C 1100 298 | 13 15 D 1101 299 | 14 16 E 1110 300 | 15 17 F 1111 301 | 16 20 10 10000 302 | 17 21 11 10001 303 | """ 304 | width = len(bin(17)[2:]) 305 | for i in range(1, 17+1): 306 | dec_i = str(i) 307 | oct_i = oct(i)[2:] 308 | hex_i = hex(i)[2:].upper() 309 | bin_i = bin(i)[2:] 310 | print(dec_i.rjust(width), oct_i.rjust(width), hex_i.rjust(width), bin_i.rjust(width)) 311 | """ 312 | --------e-------- 313 | ------e-d-e------ 314 | ----e-d-c-d-e---- 315 | --e-d-c-b-c-d-e-- 316 | e-d-c-b-a-b-c-d-e 317 | --e-d-c-b-c-d-e-- 318 | ----e-d-c-d-e---- 319 | ------e-d-e------ 320 | --------e-------- 321 | """ 322 | letters = "abcdefghijklmnopqrstuvwxyz" 323 | def print_rangoli(size): 324 | lines = [] 325 | for row in range(size): 326 | print_ = "-".join(letters[row:size]) 327 | lines.append(print_[::-1]+print_[1:]) 328 | #print(lines) 329 | width = len(lines[0]) 330 | for row in range(size-1, 0, -1): 331 | print(lines[row].center(width, "-")) 332 | for row in range(size): 333 | print(lines[row].center(width, "-")) 334 | """ 335 | hackerrank minion solution 336 | """ 337 | def minion_game(string): 338 | n = len(string) 339 | comb = ((n)*(n+1))/2 340 | #print(comb) 341 | count_k = sum([len(string[i:]) for i in range(len(string)) if string[i] in "aeiou"]) 342 | count_s = comb - count_k 343 | if count_s == count_k: 344 | print("Draw") 345 | elif count_s > count_k: 346 | print("Stuart",int(count_s)) 347 | else: 348 | print("Kevin", int(count_k)) 349 | 350 | minion_game("banana") 351 | """ 352 | 1 353 | 121 354 | 12321 355 | 1234321 356 | 123454321 357 | """ 358 | n = int(input()) 359 | for i in range(1, n+1): 360 | print(((10**i-1)//9)**2) 361 | """ 362 | PixDynamics @decorator function 363 | """ 364 | def odd_dec(func): 365 | def wrapper(a, b): 366 | if (a%2!=0 and b%2!=0): 367 | return a+b 368 | else: 369 | return func(a, b) 370 | return wrapper 371 | 372 | @odd_dec 373 | def sum(a, b): 374 | return a+b 375 | 376 | print(sum(3, 5)) 377 | """ 378 | li = [1, 2, 3, 4, 5] 379 | result = [3, 2, 1] 380 | """ 381 | li = [1, 2, 3, 4, 5] 382 | print(li[2::-1]) 383 | """ 384 | Leet code : 383. Ransom Note 385 | """ 386 | class Solution: 387 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 388 | for i in range(len(ransomNote)): 389 | pos = ransomNote[i] 390 | matchIndex = magazine.find(pos) 391 | if matchIndex == -1: 392 | return False 393 | magazine = magazine[:matchIndex]+magazine[matchIndex+1:] 394 | return True 395 | """ 396 | Leet code : 13. Roman to Integer 397 | """ 398 | class Solution: 399 | def romanToInt(self, s: str) -> int: 400 | roman_dict = { 401 | "I":1, "V":5, "X":10, "L":50, 402 | "C":100, "D":500, "M":1000} 403 | ans = 0 404 | for i in range(0, len(s)-1): 405 | if roman_dict[s[i]] < roman_dict[s[i+1]]: 406 | ans -= roman_dict[s[i]] 407 | else: 408 | ans += roman_dict[s[i]] 409 | return ans+roman_dict[s[-1]] 410 | 411 | """ 412 | 0(log n) Binary Search 413 | """ 414 | def binary_search(array, start, end, target): 415 | mid = (start+end)//2 416 | if start > end: 417 | return False 418 | if array[mid] == target: 419 | return True 420 | if array[mid] > target: 421 | return binary_search(array, start, mid-1, target) 422 | else: 423 | return binary_search(array, mid+1, end, target) 424 | 425 | li = [1, 2, 3, 4, 5, 6, 7, 8] 426 | target = 10 427 | start = 0 428 | end = len(li)-1 429 | print(binary_search(li, start, end, target)) 430 | 431 | """ 432 | O(n log n) Merge Sort 433 | """ 434 | def mergeSort(arr): 435 | if len(arr) < 2: 436 | return arr 437 | #finding mid point 438 | mid = len(arr)//2 439 | #creating two arrays 440 | left_arr = arr[0:mid] 441 | right_arr = arr[mid:len(arr)] 442 | #calling merge function it acts like recursion 443 | return merge(mergeSort(left_arr), mergeSort(right_arr)) 444 | 445 | #merge function 446 | def merge(left_arr, right_arr): 447 | #creating new array to save the sort merged list 448 | result = [] 449 | left_idx = 0 450 | right_idx = 0 451 | while left_idx < len(left_arr) and right_idx < len(right_arr): 452 | if left_arr[left_idx] < right_arr[right_idx]: 453 | result.append(left_arr[left_idx]) 454 | left_idx+=1 455 | else: 456 | result.append(right_arr[right_idx]) 457 | right_idx+=1 458 | return result+left_arr[left_idx:]+right_arr[right_idx:] 459 | 460 | li = [35, 43, 12, 27, 5, 90, 17, 8] 461 | print(mergeSort(li)) 462 | 463 | """ 464 | O(2^n) - Fibnoacci Series 465 | """ 466 | def fib_series(n): 467 | if n == 0: 468 | return 0 469 | if n == 1: 470 | return 1 471 | return fib_series(n-1)+fib_series(n-2) 472 | 473 | n = 10 474 | for i in range(n): 475 | print(fib_series(i), end=" ") 476 | 477 | """ 478 | O(n!) - factorial 479 | """ 480 | def fac(n): 481 | li = [] 482 | if n == 0: 483 | 484 | return 485 | for i in range(n): 486 | fac(n-1) 487 | 488 | fac(3) 489 | """ 490 | O(n) - Factorial 491 | """ 492 | def fac(n): 493 | if n==1: 494 | return 1 495 | else: 496 | temp = fac(n-1) 497 | temp*=n 498 | return temp 499 | 500 | """ 501 | O(n) - Permutattion 502 | """ 503 | def permutattion(str, packet=""): 504 | if len(str) == 0: 505 | print(packet) 506 | else: 507 | for i in range(len(str)): 508 | letter = str[i] 509 | front = str[0:i] 510 | back = str[i+1:] 511 | together = front+back 512 | permutation(together, letter+packet) 513 | """ 514 | GFG - GreedyFox - Time Complexity (0(n)) 515 | """ 516 | def greedyFox(arr): 517 | max_s = arr[0] 518 | cur_s = arr[0] 519 | for i in range(1, len(arr)): 520 | if arr[i] > arr[i-1]: 521 | cur_s+=arr[i] 522 | if cur_s > max_s: 523 | max_s = cur_s 524 | else: 525 | cur_s = arr[i] 526 | return max_s 527 | 528 | print(greedyFox([2, 1, 4, 7, 3, 6])) 529 | """ 530 | LeetCode - Climbing Stairs 531 | """ 532 | class Solution: 533 | def climbStairs(self, n: int) -> int: 534 | if n == 1: 535 | return 1 536 | if n == 2: 537 | return 2 538 | steps = [1, 1]+[0]*(n-1) 539 | for i in range(2, n+1): 540 | steps[i] = steps[i-1]+steps[i-2] 541 | return steps[n] 542 | """ 543 | LeetCode - Remove Duplicates from sorted linkedlist 544 | """ 545 | class Solution: 546 | def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: 547 | cur = head 548 | while cur: 549 | while cur.next and cur.next.val == cur.val: 550 | cur.next = cur.next.next 551 | cur = cur.next 552 | return head 553 | """ 554 | Pascal's Triangle Leetcode 555 | """ 556 | class Solution: 557 | def generate(self, numRows: int) -> List[List[int]]: 558 | result = [] 559 | if numRows == 0: 560 | return result 561 | result.append([1]) 562 | if numRows == 1: 563 | return result 564 | for i in range(1, numRows): 565 | prev_li = result[i-1] 566 | in_li = [] 567 | in_li.append(1) 568 | for j in range(i-1): 569 | in_li.append(prev_li[j]+prev_li[j+1]) 570 | in_li.append(1) 571 | result.append(in_li) 572 | return result 573 | """ 574 | Longest Common Prefix 575 | """ 576 | class Solution: 577 | def longestCommonPrefix(self, strs: List[str]) -> str: 578 | result = "" 579 | strs.sort() 580 | first_word = strs[0] 581 | last_word = strs[-1] 582 | for i in range(len(first_word)): 583 | if first_word[i] == last_word[i]: 584 | result+=first_word[i] 585 | else: 586 | break 587 | return result 588 | """ 589 | Insertion Sort 590 | """ 591 | def insertionSort(li): 592 | for i in range(1, len(li)): 593 | key = li[i] 594 | j = i-1 595 | while j>=0 and li[j] > key: 596 | li[j+1] = li[j] 597 | j-=1 598 | li[j+1] = key 599 | return li 600 | """ 601 | LeetCode 20. Valid Parenthesis 602 | """ 603 | class Solution: 604 | def isValid(self, s: str) -> bool: 605 | if len(s) < 2: 606 | return False 607 | li = [] 608 | for i in range(len(s)): 609 | if len(li) == 0 and s[i] in (")", "]", "}"): 610 | return False 611 | if s[i] == "(": 612 | li.append(")") 613 | elif s[i] == "[": 614 | li.append("]") 615 | elif s[i] == "{": 616 | li.append("}") 617 | elif s[i] == li[-1]: 618 | li.pop() 619 | else: 620 | return False 621 | if len(li) == 0: 622 | return True 623 | else: 624 | return False 625 | """ 626 | 121. Best time to buy and sell stock 627 | """ 628 | class Solution: 629 | def maxProfit(self, prices: List[int]) -> int: 630 | curr_pri = prices[0] 631 | max_pro = 0 632 | curr_pro = 0 633 | for i in range(1, len(prices)): 634 | if curr_pri < prices[i]: 635 | curr_pro = prices[i] - curr_pri 636 | if curr_pro > max_pro: 637 | max_pro = curr_pro 638 | else: 639 | curr_pri = prices[i] 640 | return max_pro 641 | """ 642 | 169. Majority Element - Solving using Voting Algorithm 643 | """ 644 | class Solution: 645 | def majorityElement(self, nums: List[int]) -> int: 646 | majority = nums[0] 647 | votes = 1 648 | for i in range(1, len(nums)): 649 | if nums[i] == majority: 650 | votes+=1 651 | else: 652 | if votes == 0: 653 | majority = nums[i] 654 | votes = 0 655 | else: 656 | votes-=1 657 | return majority 658 | """ 659 | Reverse an Integer 660 | """ 661 | #Reversing an intger 662 | def reverse_int(num): 663 | result = 0 664 | while num > 0: 665 | digit = num%10 666 | result = result*10+digit 667 | num//=10 668 | return result 669 | """ 670 | LeetCode 500: Keyboard Row 671 | """ 672 | class Solution: 673 | def findWords(self, words: List[str]) -> List[str]: 674 | keyboard = {'q': 1,'w': 1, 'e': 1, 'r': 1, 't': 1, 675 | 'y': 1,'u': 1, 'i': 1, 'o': 1, 'p': 1, 676 | 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 677 | 'h': 2, 'j': 2, 'k': 2, 'l': 2, 'z': 3, 678 | 'x': 3, 'c': 3, 'v': 3, 'b': 3, 'n': 3, 'm': 3} 679 | result = [] 680 | for i in range(len(words)): 681 | first_pos = keyboard[words[i][0].lower()] 682 | same_row = True 683 | for j in range(1, len(words[i])): 684 | if keyboard[words[i][j].lower()] != first_pos: 685 | same_row = False 686 | if same_row: 687 | result.append(words[i]) 688 | return result 689 | """ 690 | Leet Code 599: Minimum Index Sum of Two Lists 691 | """ 692 | class Solution: 693 | def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: 694 | result = [] 695 | sum_index = 0 696 | for i in range(len(list1)): 697 | if list1[i] in list2: 698 | total_index = list1.index(list1[i])+list2.index(list1[i]) 699 | if sum_index == 0 and len(result) == 0: 700 | result.append(list1[i]) 701 | sum_index = total_index 702 | elif total_index == sum_index: 703 | result.append(list1[i]) 704 | elif total_index < sum_index: 705 | result = [list1[i]] 706 | sum_index = total_index 707 | return result 708 | """ 709 | Leet Code 3042: Count suffix and prefix pairs 1 710 | """ 711 | class Solution: 712 | def countPrefixSuffixPairs(self, words: List[str]) -> int: 713 | count = 0 714 | for i in range(len(words)): 715 | for j in range(i+1, len(words)): 716 | if self.is_valid(words[i], words[j]): 717 | count+=1 718 | return count 719 | 720 | def is_valid(self, w1, w2): 721 | result = False 722 | if len(w1) > len(w2): 723 | return result 724 | for i in range(len(w1)): 725 | if w1[i] == w2[i] and w1[(len(w1)-1)-i] == w2[(len(w2)-1)-i]: 726 | result = True 727 | else: 728 | result = False 729 | break 730 | return result 731 | """ 732 | 748: Shortest Completing Word 733 | """ 734 | class Solution: 735 | def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: 736 | lp = "".join([i for i in licensePlate.lower() if i.isalpha()]) 737 | min_len = len(sorted(words, key=len)[-1])+1 738 | res = "" 739 | for i in range(len(words)): 740 | if self.isMatch(words[i], lp) and len(words[i]) < min_len: 741 | min_len = len(words[i]) 742 | res = words[i] 743 | return res 744 | 745 | def isMatch(self, word, lp): 746 | res = False 747 | for i in lp: 748 | if i in word and word.count(i) >= lp.count(i): 749 | res = True 750 | else: 751 | res = False 752 | return res 753 | return res 754 | """ 755 | 806: Number of Lines to write string 756 | """ 757 | class Solution: 758 | def numberOfLines(self, widths: List[int], s: str) -> List[int]: 759 | alp = ["a", "b", "c", "d", "e", 760 | "f", "g", "h", "i", "j", 761 | "k", "l", "m", "n", "o", 762 | "p", "q", "r", "s", "t", 763 | "u", "v", "w", "x", "y", "z"] 764 | alp_wid = {alp[i]:widths[i] for i in range(len(alp))} 765 | lines, total = 0, 0 766 | for i in s: 767 | total+=alp_wid[i] 768 | if total > 100: 769 | lines+=1 770 | total = alp_wid[i] 771 | if total > 0: 772 | lines+=1 773 | return [lines, total] 774 | 775 | -------------------------------------------------------------------------------- /linked_list_dsa.py: -------------------------------------------------------------------------------- 1 | """ 2 | LinkedList 3 | Node - [Done] 4 | LinkedList - [Done] 5 | Append - [Done] 6 | Length - [Done] 7 | Print - [Done] 8 | Insert in head - [Done] 9 | Insert using position - [Done] 10 | Indexing - [Done] 11 | Clear - [Done] 12 | Remove from head - [Done] 13 | pop [Remove from last] - [Done] 14 | remove by value - [Done] 15 | delete using index 'del' - [Done] 16 | count - [Done] 17 | reverse - [Done] 18 | maximum - [Done] 19 | """ 20 | #creating a Node 21 | class Node: 22 | def __init__(self, data): 23 | self.data = data 24 | self.next = None 25 | 26 | class LinkedList: 27 | def __init__(self): 28 | self.head = None 29 | self.n = 0 30 | 31 | #append to the list 32 | def append(self, value): 33 | if self.head == None: 34 | self.head = Node(value) 35 | else: 36 | curr = self.head 37 | while curr.next != None: 38 | curr = curr.next 39 | curr.next = Node(value) 40 | self.n+=1 41 | 42 | #length of the LL 43 | def __len__(self): 44 | return self.n 45 | 46 | #printing element 47 | def __str__(self): 48 | result = "" 49 | curr = self.head 50 | while curr != None: 51 | result = result+str(curr.data)+" -> " 52 | curr = curr.next 53 | return "[ " + result[:-4] + " ]" 54 | 55 | def __repr__(self): 56 | return self.__str__() 57 | 58 | #inserting from head 59 | def insert_from_head(self, value): 60 | new_node = Node(value) 61 | new_node.next = self.head 62 | self.head = new_node 63 | self.n+=1 64 | 65 | #insert using position 66 | def insert(self, pos, value): 67 | if pos < 0: 68 | raise Exception("Negative indexing on next version") 69 | if pos >= self.n: 70 | raise Exception("Index out of range") 71 | if pos == 0: 72 | self.insert_from_head(value) 73 | self.n+=1 74 | else: 75 | new_node = Node(value) 76 | curr = self.head 77 | i = 1 78 | while curr != None and i < self.n: 79 | if i == pos: 80 | break 81 | curr = curr.next 82 | i+=1 83 | new_node.next = curr.next 84 | curr.next = new_node 85 | self.n+=1 86 | 87 | #indexing 88 | def __getitem__(self, pos): 89 | if pos < 0: 90 | pos = self.n+pos 91 | if pos < 0: 92 | raise Exception("Index out of range") 93 | if pos >= self.n: 94 | raise Exception("Index out of range") 95 | if 0 <= pos < self.n: 96 | curr = self.head 97 | i = 0 98 | while curr != None and i < self.n: 99 | if i == pos: 100 | return curr.data 101 | curr = curr.next 102 | i+=1 103 | 104 | #clear 105 | def clear(self): 106 | self.head = None 107 | self.n = 0 108 | 109 | #remove from head 110 | def remove_from_head(self): 111 | if self.head != None: 112 | self.head = self.head.next 113 | self.n-=1 114 | else: 115 | return "Linked list is empty" 116 | 117 | #remove from last - pop 118 | def pop(self): 119 | if self.head == None: 120 | return "Linked List is empty" 121 | curr = self.head 122 | if curr.next == None: 123 | data = self.head.data 124 | self.head = None 125 | self.n = 0 126 | return data 127 | else: 128 | while curr.next.next != None: 129 | curr = curr.next 130 | data = curr.next.data 131 | curr.next = curr.next.next 132 | self.n-=1 133 | return data 134 | 135 | #remove using value 136 | def remove(self, value): 137 | if self.head == None: 138 | return "Linked List is Empty" 139 | if self.head.next == None: 140 | if self.head.data == value: 141 | self.head = None 142 | self.n = 0 143 | else: 144 | return f"{value} not in the Linked List" 145 | else: 146 | curr = self.head 147 | if curr.data == value: 148 | self.head = curr.next 149 | self.n-=1 150 | else: 151 | while curr.next != None: 152 | if curr.next.data == value: 153 | break 154 | curr = curr.next 155 | if curr.next != None: 156 | curr.next = curr.next.next 157 | self.n-=1 158 | else: 159 | return f"{value} not in the linked list" 160 | 161 | #delete using index and __delitem__ 162 | def __delitem__(self, pos): 163 | item = self.__getitem__(pos) 164 | self.remove(item) 165 | 166 | #count 167 | def count(self, value): 168 | if self.head == None: 169 | return "Linked list is empty" 170 | else: 171 | i = 0 172 | curr = self.head 173 | while curr != None: 174 | if curr.data == value: 175 | i+=1 176 | curr = curr.next 177 | return i 178 | 179 | #reversing a linked_list 180 | def reverse(self): 181 | if self.head == None: 182 | return "Linked List is empty" 183 | new_ = LinkedList() 184 | curr = self.head 185 | while curr != None: 186 | new_.insert_from_head(curr.data) 187 | curr = curr.next 188 | return new_ 189 | 190 | #maximum value of an linked list 191 | def maximum(self): 192 | if self.head == None: 193 | return "Linked List is empty" 194 | curr = self.head 195 | max_ = curr.data 196 | while curr != None: 197 | if max_ < curr.data: 198 | max_ = curr.data 199 | curr = curr.next 200 | return max_ 201 | -------------------------------------------------------------------------------- /number-guessing-game/number_gusessing_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | """ 4 | GAME LOGIC 5 | ------------ 6 | START GAME 7 | ↓ 8 | Generate a random number 9 | ↓ 10 | LOOP: 11 | Ask user for a guess 12 | ↓ 13 | If guess == number → WIN 14 | If guess < number → "Too low" 15 | If guess > number → "Too high" 16 | ↑ (loop until correct or limit reached) 17 | ↓ 18 | END GAME (show result and attempts) 19 | """ 20 | 21 | def generating_random_number(): 22 | return random.randint(1, 100) 23 | 24 | def check_the_integer(guessed_no:int, answer: int): 25 | if guessed_no > answer: 26 | if (guessed_no - answer) < 10: 27 | return False, "Very close, not too high!!" 28 | return False, "Too high!!" 29 | elif guessed_no < answer: 30 | if (answer - guessed_no) < 10: 31 | return False, "Very close, not too low!!" 32 | return False, "Too low!!" 33 | else: 34 | return True, "You got it!!" 35 | 36 | def game(): 37 | attempts = 0 38 | answer = generating_random_number() 39 | while attempts < 10: 40 | guess = input("Guess a number between 1 and 100: ") 41 | if not guess.isdigit(): 42 | print("Invalid, please enter number!!") 43 | attempts += 1 44 | print(f"You have {10-attempts} attempts left!!") 45 | continue 46 | else: 47 | result, message = check_the_integer(int(guess), answer) 48 | if result: 49 | print(message) 50 | print(f"You guessed it in {attempts} attempts!!") 51 | break 52 | else: 53 | print(message) 54 | attempts += 1 55 | print(f"You have {10-attempts} attempts left!!") 56 | 57 | welcome_message = r""" 58 | 59 | ________ ___________.__ ________ .__ .__ __ 60 | / _____/ __ __ ____ ______ ______ \__ ___/| |__ ____ \______ \ |__| ____ |__|/ |_ 61 | / \ ___| | \_/ __ \ / ___// ___/ | | | | \_/ __ \ | | \| |/ ___\| \ __\ 62 | \ \_\ \ | /\ ___/ \___ \ \___ \ | | | Y \ ___/ | ` \ / /_/ > || | 63 | \______ /____/ \___ >____ >____ > |____| |___| /\___ > /_______ /__\___ /|__||__| 64 | \/ \/ \/ \/ \/ \/ \/ /_____/ 65 | Created by: ARUN ARUNISTO 66 | """ 67 | def main(): 68 | print(welcome_message) 69 | while True: 70 | options = input("[1] Start the game [2] Quit the game \nEnter the option: ") 71 | if options == "1": 72 | game() 73 | elif options == "2": 74 | break 75 | else: 76 | print("Invalid option!!") 77 | 78 | if __name__ == "__main__": 79 | main() 80 | -------------------------------------------------------------------------------- /panda_xlsx.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "mount_file_id": "1fYumsMcspRVPyYwyQR1xiCgfwpXQHqUS", 8 | "authorship_tag": "ABX9TyNtxufo2KE48ADh4N0Pe4nP", 9 | "include_colab_link": true 10 | }, 11 | "kernelspec": { 12 | "name": "python3", 13 | "display_name": "Python 3" 14 | }, 15 | "language_info": { 16 | "name": "python" 17 | } 18 | }, 19 | "cells": [ 20 | { 21 | "cell_type": "markdown", 22 | "metadata": { 23 | "id": "view-in-github", 24 | "colab_type": "text" 25 | }, 26 | "source": [ 27 | "\"Open" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 3, 33 | "metadata": { 34 | "id": "zIdxhewGF5VF" 35 | }, 36 | "outputs": [], 37 | "source": [ 38 | "import pandas as pd" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "source": [ 44 | "file_xl = pd.read_excel(\"/content/drive/MyDrive/Datascience&MachineLearning/datasets/1PCMST.xlsx\")" 45 | ], 46 | "metadata": { 47 | "id": "azbF5RauGYdX" 48 | }, 49 | "execution_count": 4, 50 | "outputs": [] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "source": [ 55 | "print(file_xl)" 56 | ], 57 | "metadata": { 58 | "colab": { 59 | "base_uri": "https://localhost:8080/" 60 | }, 61 | "id": "MAJ1es12G0FY", 62 | "outputId": "adcfc7b4-6098-40a5-86a7-d9e309b3634a" 63 | }, 64 | "execution_count": 5, 65 | "outputs": [ 66 | { 67 | "output_type": "stream", 68 | "name": "stdout", 69 | "text": [ 70 | " DIST_CODE PCNO PCNAME_ENG PCNAME_TAM\n", 71 | "0 12 19 Nilgiris(SC) நீலகிரி (SC)\n", 72 | "1 12 20 Coimbatore கோயம்புத்தூர்\n", 73 | "2 12 21 Pollachi பொள்ளாச்சி\n" 74 | ] 75 | } 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "source": [ 81 | "file_xl.shape" 82 | ], 83 | "metadata": { 84 | "colab": { 85 | "base_uri": "https://localhost:8080/" 86 | }, 87 | "id": "zW-iQAcsG9AA", 88 | "outputId": "3b038b72-cea6-4ae0-d762-0702fdb2193c" 89 | }, 90 | "execution_count": 6, 91 | "outputs": [ 92 | { 93 | "output_type": "execute_result", 94 | "data": { 95 | "text/plain": [ 96 | "(3, 4)" 97 | ] 98 | }, 99 | "metadata": {}, 100 | "execution_count": 6 101 | } 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "source": [ 107 | "file_xl.head()" 108 | ], 109 | "metadata": { 110 | "colab": { 111 | "base_uri": "https://localhost:8080/", 112 | "height": 143 113 | }, 114 | "id": "gWK6vHgWHK_g", 115 | "outputId": "331372bc-a299-49e6-980f-62cbb9922ed2" 116 | }, 117 | "execution_count": 8, 118 | "outputs": [ 119 | { 120 | "output_type": "execute_result", 121 | "data": { 122 | "text/plain": [ 123 | " DIST_CODE PCNO PCNAME_ENG PCNAME_TAM\n", 124 | "0 12 19 Nilgiris(SC) நீலகிரி (SC)\n", 125 | "1 12 20 Coimbatore கோயம்புத்தூர்\n", 126 | "2 12 21 Pollachi பொள்ளாச்சி" 127 | ], 128 | "text/html": [ 129 | "\n", 130 | "
\n", 131 | "
\n", 132 | "\n", 145 | "\n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | "
DIST_CODEPCNOPCNAME_ENGPCNAME_TAM
01219Nilgiris(SC)நீலகிரி (SC)
11220Coimbatoreகோயம்புத்தூர்
21221Pollachiபொள்ளாச்சி
\n", 179 | "
\n", 180 | "
\n", 181 | "\n", 182 | "
\n", 183 | " \n", 191 | "\n", 192 | " \n", 232 | "\n", 233 | " \n", 257 | "
\n", 258 | "\n", 259 | "\n", 260 | "
\n", 261 | " \n", 272 | "\n", 273 | "\n", 362 | "\n", 363 | " \n", 385 | "
\n", 386 | "\n", 387 | "
\n", 388 | "
\n" 389 | ], 390 | "application/vnd.google.colaboratory.intrinsic+json": { 391 | "type": "dataframe", 392 | "variable_name": "file_xl", 393 | "summary": "{\n \"name\": \"file_xl\",\n \"rows\": 3,\n \"fields\": [\n {\n \"column\": \"DIST_CODE\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 12,\n \"max\": 12,\n \"num_unique_values\": 1,\n \"samples\": [\n 12\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"PCNO\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 19,\n \"max\": 21,\n \"num_unique_values\": 3,\n \"samples\": [\n 19\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"PCNAME_ENG\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"Nilgiris(SC)\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"PCNAME_TAM\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"\\u0ba8\\u0bc0\\u0bb2\\u0b95\\u0bbf\\u0bb0\\u0bbf (SC)\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" 394 | } 395 | }, 396 | "metadata": {}, 397 | "execution_count": 8 398 | } 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "source": [ 404 | "print(file_xl.columns)" 405 | ], 406 | "metadata": { 407 | "colab": { 408 | "base_uri": "https://localhost:8080/" 409 | }, 410 | "id": "fq7F9jwWHb5x", 411 | "outputId": "5db0abb5-f7d7-4809-f350-b0ee3852a944" 412 | }, 413 | "execution_count": 9, 414 | "outputs": [ 415 | { 416 | "output_type": "stream", 417 | "name": "stdout", 418 | "text": [ 419 | "Index(['DIST_CODE', 'PCNO', 'PCNAME_ENG', 'PCNAME_TAM'], dtype='object')\n" 420 | ] 421 | } 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "source": [ 427 | "print(file_xl[\"DIST_CODE\"])" 428 | ], 429 | "metadata": { 430 | "colab": { 431 | "base_uri": "https://localhost:8080/" 432 | }, 433 | "id": "lryXn0SwILKE", 434 | "outputId": "0ac3a180-c59b-4cb2-fc11-bb25c5049250" 435 | }, 436 | "execution_count": 10, 437 | "outputs": [ 438 | { 439 | "output_type": "stream", 440 | "name": "stdout", 441 | "text": [ 442 | "0 12\n", 443 | "1 12\n", 444 | "2 12\n", 445 | "Name: DIST_CODE, dtype: int64\n" 446 | ] 447 | } 448 | ] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "source": [ 453 | "dis_code = list(file_xl[\"DIST_CODE\"])\n", 454 | "print(dis_code)" 455 | ], 456 | "metadata": { 457 | "colab": { 458 | "base_uri": "https://localhost:8080/" 459 | }, 460 | "id": "CNjO53S2ITpp", 461 | "outputId": "4c9dcbf4-a84c-47bc-9c10-1f4f7d626f10" 462 | }, 463 | "execution_count": 11, 464 | "outputs": [ 465 | { 466 | "output_type": "stream", 467 | "name": "stdout", 468 | "text": [ 469 | "[12, 12, 12]\n" 470 | ] 471 | } 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "source": [ 477 | "pc_no, pc_name_en, pc_name_tam = list(file_xl[\"PCNO\"]), list(file_xl[\"PCNAME_ENG\"]), list(file_xl[\"PCNAME_TAM\"])" 478 | ], 479 | "metadata": { 480 | "id": "FrZdFpFCIjMp" 481 | }, 482 | "execution_count": 12, 483 | "outputs": [] 484 | }, 485 | { 486 | "cell_type": "code", 487 | "source": [ 488 | "#data row wise\n", 489 | "data_1 = file_xl.iloc[0]\n", 490 | "data_1" 491 | ], 492 | "metadata": { 493 | "colab": { 494 | "base_uri": "https://localhost:8080/" 495 | }, 496 | "id": "nO69dy05I9zL", 497 | "outputId": "d2abe7bb-397f-485e-eeb9-29110610a8cd" 498 | }, 499 | "execution_count": 13, 500 | "outputs": [ 501 | { 502 | "output_type": "execute_result", 503 | "data": { 504 | "text/plain": [ 505 | "DIST_CODE 12\n", 506 | "PCNO 19\n", 507 | "PCNAME_ENG Nilgiris(SC)\n", 508 | "PCNAME_TAM நீலகிரி (SC)\n", 509 | "Name: 0, dtype: object" 510 | ] 511 | }, 512 | "metadata": {}, 513 | "execution_count": 13 514 | } 515 | ] 516 | }, 517 | { 518 | "cell_type": "code", 519 | "source": [ 520 | "#length of rows\n", 521 | "num_rows = file_xl.shape[0]\n", 522 | "for i in range(num_rows):\n", 523 | " print(list(file_xl.iloc[i]))" 524 | ], 525 | "metadata": { 526 | "colab": { 527 | "base_uri": "https://localhost:8080/" 528 | }, 529 | "id": "Ok3N58SBJkXw", 530 | "outputId": "77111e1f-6aa0-4134-dc8f-c44394bc17a9" 531 | }, 532 | "execution_count": 14, 533 | "outputs": [ 534 | { 535 | "output_type": "stream", 536 | "name": "stdout", 537 | "text": [ 538 | "[12, 19, 'Nilgiris(SC)', 'நீலகிரி (SC)']\n", 539 | "[12, 20, 'Coimbatore', 'கோயம்புத்தூர்']\n", 540 | "[12, 21, 'Pollachi', 'பொள்ளாச்சி']\n" 541 | ] 542 | } 543 | ] 544 | }, 545 | { 546 | "cell_type": "code", 547 | "source": [ 548 | "new_li = []\n", 549 | "for i in range(num_rows):\n", 550 | " new_li.append(tuple(file_xl.iloc[i]))\n", 551 | "print(new_li)" 552 | ], 553 | "metadata": { 554 | "colab": { 555 | "base_uri": "https://localhost:8080/" 556 | }, 557 | "id": "xG3cb6KZKEKQ", 558 | "outputId": "ba8bdf48-a874-416e-d002-0557c6a61cff" 559 | }, 560 | "execution_count": 15, 561 | "outputs": [ 562 | { 563 | "output_type": "stream", 564 | "name": "stdout", 565 | "text": [ 566 | "[(12, 19, 'Nilgiris(SC)', 'நீலகிரி (SC)'), (12, 20, 'Coimbatore', 'கோயம்புத்தூர்'), (12, 21, 'Pollachi', 'பொள்ளாச்சி')]\n" 567 | ] 568 | } 569 | ] 570 | }, 571 | { 572 | "cell_type": "code", 573 | "source": [ 574 | "for i in new_li:\n", 575 | " print(i)" 576 | ], 577 | "metadata": { 578 | "colab": { 579 | "base_uri": "https://localhost:8080/" 580 | }, 581 | "id": "DGGL5geeKaHa", 582 | "outputId": "74155a06-cbaf-4672-df87-e48f3ad8d2d9" 583 | }, 584 | "execution_count": 16, 585 | "outputs": [ 586 | { 587 | "output_type": "stream", 588 | "name": "stdout", 589 | "text": [ 590 | "(12, 19, 'Nilgiris(SC)', 'நீலகிரி (SC)')\n", 591 | "(12, 20, 'Coimbatore', 'கோயம்புத்தூர்')\n", 592 | "(12, 21, 'Pollachi', 'பொள்ளாச்சி')\n" 593 | ] 594 | } 595 | ] 596 | }, 597 | { 598 | "cell_type": "code", 599 | "source": [ 600 | "file_xl.iloc[0][0]" 601 | ], 602 | "metadata": { 603 | "colab": { 604 | "base_uri": "https://localhost:8080/" 605 | }, 606 | "id": "WnPUygbxNd_j", 607 | "outputId": "5d20ba58-187b-4b2a-fc93-ecad0f0a93c5" 608 | }, 609 | "execution_count": 17, 610 | "outputs": [ 611 | { 612 | "output_type": "execute_result", 613 | "data": { 614 | "text/plain": [ 615 | "12" 616 | ] 617 | }, 618 | "metadata": {}, 619 | "execution_count": 17 620 | } 621 | ] 622 | }, 623 | { 624 | "cell_type": "code", 625 | "source": [ 626 | "#opening ps master\n", 627 | "xl_file = pd.read_excel(\"/content/drive/MyDrive/Datascience&MachineLearning/datasets/PSMaster.xlsx\")\n", 628 | "xl_file.head()" 629 | ], 630 | "metadata": { 631 | "colab": { 632 | "base_uri": "https://localhost:8080/", 633 | "height": 591 634 | }, 635 | "id": "OUd1WnVZTBTM", 636 | "outputId": "6b9f0005-f56d-45a0-f797-8f9784ad5790" 637 | }, 638 | "execution_count": 19, 639 | "outputs": [ 640 | { 641 | "output_type": "execute_result", 642 | "data": { 643 | "text/plain": [ 644 | " dist_code pc_no ac_no ps_sno \\\n", 645 | "0 12 20 111 1 \n", 646 | "1 12 20 111 2 \n", 647 | "2 12 20 111 3 \n", 648 | "3 12 20 111 4 \n", 649 | "4 12 20 111 5 \n", 650 | "\n", 651 | " ps_name_en \\\n", 652 | "0 Panchayat Union Elementary School,North Facing... \n", 653 | "1 Sri Sarguru adivasi Gurugula School, East Faci... \n", 654 | "2 Sri Sarguru adivasi Gurugula School, East Faci... \n", 655 | "3 Panchayat Union Elementary School, North Facin... \n", 656 | "4 Panchayat Union Elementary School, East facing... \n", 657 | "\n", 658 | " ps_area_en \\\n", 659 | "0 1.Nellithurai Ward No. 1\\n2.Nandhavanam Pudur... \n", 660 | "1 1.Narayanasamy Pudur W.No. 5\\n2.Naripallamroad... \n", 661 | "2 1.Kallar Pudur W.No. 2\\n2.Sachidhanantha Jothi... \n", 662 | "3 1.Kallar T.A.S Nagar W.No.5\\n2.Kallar Agasthi... \n", 663 | "4 1.Oomapalayam Keeltheru W.No 8\\n2.Oomapalayam ... \n", 664 | "\n", 665 | " ps_name_ta \\\n", 666 | "0 ஊராட்சி ஒன்றிய துவக்கப்பள்ளி, வடக்கு பார்த்த க... \n", 667 | "1 ஸ்ரீ சற்குரு ஆதிவாசிகள் குருகுலப்பள்ளி ,கிழக்க... \n", 668 | "2 ஸ்ரீ சற்குரு ஆதிவாசிகள் குருகுலப்பள்ளி ,கிழக்க... \n", 669 | "3 ஊராட்சி ஒன்றிய தொடக்கப்பள்ளி ,வடக்கு பார்த்த த... \n", 670 | "4 ஊராட்சி ஒன்றிய தொடக்கப்பள்ளி ,கிழக்குப் பார்த்... \n", 671 | "\n", 672 | " ps_area_ta ps_total_voters \n", 673 | "0 1.நெல்லித்துறை வார்டு எண். 1\\n2.நந்தவனம் புதூர... 1082.0 \n", 674 | "1 1.நாராயணசாமி புதூர் வார்டு எண்.5\\n2.நரிபள்ளம்ர... 1124.0 \n", 675 | "2 1.கல்லார் புதூர் வார்டு எண். 2\\n2.சச்சிதானந்த ... 762.0 \n", 676 | "3 1.கல்லார் டி.ஏ.எஸ் நகர் வார்டு எண். 5\\n2.கல்லா... 857.0 \n", 677 | "4 1.ஊமப்பாளையம் கீழ்த்தெரு வார்டு எண். 8\\n2.ஊமப்... 1003.0 " 678 | ], 679 | "text/html": [ 680 | "\n", 681 | "
\n", 682 | "
\n", 683 | "\n", 696 | "\n", 697 | " \n", 698 | " \n", 699 | " \n", 700 | " \n", 701 | " \n", 702 | " \n", 703 | " \n", 704 | " \n", 705 | " \n", 706 | " \n", 707 | " \n", 708 | " \n", 709 | " \n", 710 | " \n", 711 | " \n", 712 | " \n", 713 | " \n", 714 | " \n", 715 | " \n", 716 | " \n", 717 | " \n", 718 | " \n", 719 | " \n", 720 | " \n", 721 | " \n", 722 | " \n", 723 | " \n", 724 | " \n", 725 | " \n", 726 | " \n", 727 | " \n", 728 | " \n", 729 | " \n", 730 | " \n", 731 | " \n", 732 | " \n", 733 | " \n", 734 | " \n", 735 | " \n", 736 | " \n", 737 | " \n", 738 | " \n", 739 | " \n", 740 | " \n", 741 | " \n", 742 | " \n", 743 | " \n", 744 | " \n", 745 | " \n", 746 | " \n", 747 | " \n", 748 | " \n", 749 | " \n", 750 | " \n", 751 | " \n", 752 | " \n", 753 | " \n", 754 | " \n", 755 | " \n", 756 | " \n", 757 | " \n", 758 | " \n", 759 | " \n", 760 | " \n", 761 | " \n", 762 | " \n", 763 | " \n", 764 | " \n", 765 | " \n", 766 | " \n", 767 | " \n", 768 | " \n", 769 | " \n", 770 | " \n", 771 | " \n", 772 | " \n", 773 | "
dist_codepc_noac_nops_snops_name_enps_area_enps_name_taps_area_taps_total_voters
012201111Panchayat Union Elementary School,North Facing...1.Nellithurai Ward No. 1\\n2.Nandhavanam Pudur...ஊராட்சி ஒன்றிய துவக்கப்பள்ளி, வடக்கு பார்த்த க...1.நெல்லித்துறை வார்டு எண். 1\\n2.நந்தவனம் புதூர...1082.0
112201112Sri Sarguru adivasi Gurugula School, East Faci...1.Narayanasamy Pudur W.No. 5\\n2.Naripallamroad...ஸ்ரீ சற்குரு ஆதிவாசிகள் குருகுலப்பள்ளி ,கிழக்க...1.நாராயணசாமி புதூர் வார்டு எண்.5\\n2.நரிபள்ளம்ர...1124.0
212201113Sri Sarguru adivasi Gurugula School, East Faci...1.Kallar Pudur W.No. 2\\n2.Sachidhanantha Jothi...ஸ்ரீ சற்குரு ஆதிவாசிகள் குருகுலப்பள்ளி ,கிழக்க...1.கல்லார் புதூர் வார்டு எண். 2\\n2.சச்சிதானந்த ...762.0
312201114Panchayat Union Elementary School, North Facin...1.Kallar T.A.S Nagar W.No.5\\n2.Kallar Agasthi...ஊராட்சி ஒன்றிய தொடக்கப்பள்ளி ,வடக்கு பார்த்த த...1.கல்லார் டி.ஏ.எஸ் நகர் வார்டு எண். 5\\n2.கல்லா...857.0
412201115Panchayat Union Elementary School, East facing...1.Oomapalayam Keeltheru W.No 8\\n2.Oomapalayam ...ஊராட்சி ஒன்றிய தொடக்கப்பள்ளி ,கிழக்குப் பார்த்...1.ஊமப்பாளையம் கீழ்த்தெரு வார்டு எண். 8\\n2.ஊமப்...1003.0
\n", 774 | "
\n", 775 | "
\n", 776 | "\n", 777 | "
\n", 778 | " \n", 786 | "\n", 787 | " \n", 827 | "\n", 828 | " \n", 852 | "
\n", 853 | "\n", 854 | "\n", 855 | "
\n", 856 | " \n", 867 | "\n", 868 | "\n", 957 | "\n", 958 | " \n", 980 | "
\n", 981 | "\n", 982 | "
\n", 983 | "
\n" 984 | ], 985 | "application/vnd.google.colaboratory.intrinsic+json": { 986 | "type": "dataframe", 987 | "variable_name": "xl_file", 988 | "summary": "{\n \"name\": \"xl_file\",\n \"rows\": 2661,\n \"fields\": [\n {\n \"column\": \"dist_code\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 12,\n \"max\": 12,\n \"num_unique_values\": 1,\n \"samples\": [\n 12\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"pc_no\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 20,\n \"max\": 20,\n \"num_unique_values\": 1,\n \"samples\": [\n 20\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"ac_no\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 3,\n \"min\": 111,\n \"max\": 124,\n \"num_unique_values\": 9,\n \"samples\": [\n 123\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"ps_sno\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 348,\n \"samples\": [\n 256\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"ps_name_en\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2524,\n \"samples\": [\n \"Panchayat Union Middle School , New Building Facing South East Side Terraced Building ,Subbegoundenpudur (Near R.I Office) -642103\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"ps_area_en\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2633,\n \"samples\": [\n \"1 COIMBATORE(C) WARD NO 67 MANEESH COLONY_x000D_\\n2 COIMBATORE(C) WARD NO 83 PARK STREET_x000D_\\n3 COIMBATORE(C) WARD NO 83 CHELAPPAN STREET_x000D_\\n4 COIMBATORE(C) WARD NO 83 PARK STREET 2\\n999 OVERSEAS VOTERS\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"ps_name_ta\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2527,\n \"samples\": [\n \"\\u0b8e\\u0bb8\\u0bcd \\u0b8e\\u0ba9\\u0bcd \\u0bb5\\u0bbf \\u0b8e\\u0ba9\\u0bcd \\u0bb5\\u0bbf \\u0b85\\u0bb0\\u0b9a\\u0bbf\\u0ba9\\u0bb0\\u0bcd \\u0b86\\u0ba3\\u0bcd\\u0b95\\u0bb3\\u0bcd \\u0b89\\u0baf\\u0bb0\\u0bcd\\u0ba8\\u0bbf\\u0bb2\\u0bc8\\u0baa\\u0bcd\\u0baa\\u0bb3\\u0bcd\\u0bb3\\u0bbf \\u0ba4\\u0bc6\\u0bb1\\u0bcd\\u0b95\\u0bc1 \\u0baa\\u0b95\\u0bcd\\u0b95 \\u0b95\\u0b9f\\u0bcd\\u0b9f\\u0bbf\\u0b9f\\u0bae\\u0bcd \\u0bb5\\u0b9f\\u0b95\\u0bcd\\u0b95\\u0bc1 \\u0baa\\u0bbe\\u0bb0\\u0bcd\\u0ba4\\u0bcd\\u0ba4 8 \\u0bb5\\u0ba4\\u0bc1 \\u0bb5\\u0b95\\u0bc1\\u0baa\\u0bcd\\u0baa\\u0bc1 \\u0b85\\u0bb1\\u0bc8 \\u0b9a\\u0bbf\\u0b99\\u0bcd\\u0b95\\u0bbe\\u0ba8\\u0bb2\\u0bcd\\u0bb2\\u0bc2\\u0bb0\\u0bcd - 641005\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"ps_area_ta\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2636,\n \"samples\": [\n \"1.\\u0b87\\u0bb0\\u0ba3\\u0bcd\\u0b9f\\u0bbe\\u0bb5\\u0ba4\\u0bc1 \\u0bae\\u0bc6\\u0baf\\u0bbf\\u0ba9\\u0bcd \\u0bb5\\u0bc0\\u0ba4\\u0bbf \\u0bb5\\u0bbe\\u0bb0\\u0bcd\\u0b9f\\u0bc1 \\u0b8e\\u0ba3\\u0bcd 2\\n999.\\u0b85\\u0baf\\u0bb2\\u0bcd\\u0ba8\\u0bbe\\u0b9f\\u0bc1 \\u0bb5\\u0bbe\\u0bb4\\u0bcd \\u0bb5\\u0bbe\\u0b95\\u0bcd\\u0b95\\u0bbe\\u0bb3\\u0bb0\\u0bcd\\u0b95\\u0bb3\\u0bcd\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"ps_total_voters\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 255.18335194517275,\n \"min\": 230.0,\n \"max\": 1508.0,\n \"num_unique_values\": 944,\n \"samples\": [\n 876.0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" 989 | } 990 | }, 991 | "metadata": {}, 992 | "execution_count": 19 993 | } 994 | ] 995 | }, 996 | { 997 | "cell_type": "code", 998 | "source": [ 999 | "num_of_rows = xl_file.shape[0]\n", 1000 | "num_of_rows" 1001 | ], 1002 | "metadata": { 1003 | "colab": { 1004 | "base_uri": "https://localhost:8080/" 1005 | }, 1006 | "id": "yAGHyY7VTauM", 1007 | "outputId": "599ab98d-f1cd-44eb-c5df-4ca07d776750" 1008 | }, 1009 | "execution_count": 20, 1010 | "outputs": [ 1011 | { 1012 | "output_type": "execute_result", 1013 | "data": { 1014 | "text/plain": [ 1015 | "2661" 1016 | ] 1017 | }, 1018 | "metadata": {}, 1019 | "execution_count": 20 1020 | } 1021 | ] 1022 | }, 1023 | { 1024 | "cell_type": "code", 1025 | "source": [ 1026 | "xl_file.columns" 1027 | ], 1028 | "metadata": { 1029 | "colab": { 1030 | "base_uri": "https://localhost:8080/" 1031 | }, 1032 | "id": "BnyY4p8GXyve", 1033 | "outputId": "870f246a-69c6-44b7-9788-27ca402cefed" 1034 | }, 1035 | "execution_count": 23, 1036 | "outputs": [ 1037 | { 1038 | "output_type": "execute_result", 1039 | "data": { 1040 | "text/plain": [ 1041 | "Index(['dist_code', 'pc_no', 'ac_no', 'ps_sno', 'ps_name_en', 'ps_area_en',\n", 1042 | " 'ps_name_ta', 'ps_area_ta', 'ps_total_voters'],\n", 1043 | " dtype='object')" 1044 | ] 1045 | }, 1046 | "metadata": {}, 1047 | "execution_count": 23 1048 | } 1049 | ] 1050 | }, 1051 | { 1052 | "cell_type": "code", 1053 | "source": [ 1054 | "ac_master = pd.read_excel(\"/content/drive/MyDrive/Datascience&MachineLearning/datasets/2acmst.xlsx\")\n", 1055 | "ac_master.head()" 1056 | ], 1057 | "metadata": { 1058 | "colab": { 1059 | "base_uri": "https://localhost:8080/", 1060 | "height": 206 1061 | }, 1062 | "id": "WzAZQjkVUFW9", 1063 | "outputId": "49c7f00b-9d3a-47a7-db2b-3d742abb00d8" 1064 | }, 1065 | "execution_count": 21, 1066 | "outputs": [ 1067 | { 1068 | "output_type": "execute_result", 1069 | "data": { 1070 | "text/plain": [ 1071 | " dist_code pcno acno acname_eng acname_tam\n", 1072 | "0 12 19 111 Mettuppalayam மேட்டுப்பாளையம்\n", 1073 | "1 12 19 112 Avinashi அவிநாசி\n", 1074 | "2 12 20 115 Palladam பல்லடம்\n", 1075 | "3 12 20 116 Sulur சூலூர்\n", 1076 | "4 12 20 117 Kavundampalayam கவுண்டம்பாளையம்" 1077 | ], 1078 | "text/html": [ 1079 | "\n", 1080 | "
\n", 1081 | "
\n", 1082 | "\n", 1095 | "\n", 1096 | " \n", 1097 | " \n", 1098 | " \n", 1099 | " \n", 1100 | " \n", 1101 | " \n", 1102 | " \n", 1103 | " \n", 1104 | " \n", 1105 | " \n", 1106 | " \n", 1107 | " \n", 1108 | " \n", 1109 | " \n", 1110 | " \n", 1111 | " \n", 1112 | " \n", 1113 | " \n", 1114 | " \n", 1115 | " \n", 1116 | " \n", 1117 | " \n", 1118 | " \n", 1119 | " \n", 1120 | " \n", 1121 | " \n", 1122 | " \n", 1123 | " \n", 1124 | " \n", 1125 | " \n", 1126 | " \n", 1127 | " \n", 1128 | " \n", 1129 | " \n", 1130 | " \n", 1131 | " \n", 1132 | " \n", 1133 | " \n", 1134 | " \n", 1135 | " \n", 1136 | " \n", 1137 | " \n", 1138 | " \n", 1139 | " \n", 1140 | " \n", 1141 | " \n", 1142 | " \n", 1143 | " \n", 1144 | " \n", 1145 | " \n", 1146 | " \n", 1147 | " \n", 1148 | "
dist_codepcnoacnoacname_engacname_tam
01219111Mettuppalayamமேட்டுப்பாளையம்
11219112Avinashiஅவிநாசி
21220115Palladamபல்லடம்
31220116Sulurசூலூர்
41220117Kavundampalayamகவுண்டம்பாளையம்
\n", 1149 | "
\n", 1150 | "
\n", 1151 | "\n", 1152 | "
\n", 1153 | " \n", 1161 | "\n", 1162 | " \n", 1202 | "\n", 1203 | " \n", 1227 | "
\n", 1228 | "\n", 1229 | "\n", 1230 | "
\n", 1231 | " \n", 1242 | "\n", 1243 | "\n", 1332 | "\n", 1333 | " \n", 1355 | "
\n", 1356 | "\n", 1357 | "
\n", 1358 | "
\n" 1359 | ], 1360 | "application/vnd.google.colaboratory.intrinsic+json": { 1361 | "type": "dataframe", 1362 | "variable_name": "ac_master", 1363 | "summary": "{\n \"name\": \"ac_master\",\n \"rows\": 14,\n \"fields\": [\n {\n \"column\": \"dist_code\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 12,\n \"max\": 12,\n \"num_unique_values\": 1,\n \"samples\": [\n 12\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"pcno\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 19,\n \"max\": 21,\n \"num_unique_values\": 3,\n \"samples\": [\n 19\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"acno\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 4,\n \"min\": 111,\n \"max\": 126,\n \"num_unique_values\": 14,\n \"samples\": [\n 122\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"acname_eng\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 14,\n \"samples\": [\n \"Kinathukadavu\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"acname_tam\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 14,\n \"samples\": [\n \"\\u0b95\\u0bbf\\u0ba3\\u0ba4\\u0bcd\\u0ba4\\u0bc1\\u0b95\\u0b95\\u0b9f\\u0bb5\\u0bc1\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" 1364 | } 1365 | }, 1366 | "metadata": {}, 1367 | "execution_count": 21 1368 | } 1369 | ] 1370 | }, 1371 | { 1372 | "cell_type": "code", 1373 | "source": [ 1374 | "def panda_file_n_rows(path):\n", 1375 | " xl_file = pd.read_excel(path)\n", 1376 | " num_rows = xl_file.shape[0]\n", 1377 | " return (xl_file, num_rows)" 1378 | ], 1379 | "metadata": { 1380 | "id": "mpCr6KF9ZE47" 1381 | }, 1382 | "execution_count": 24, 1383 | "outputs": [] 1384 | }, 1385 | { 1386 | "cell_type": "code", 1387 | "source": [ 1388 | "xl_file, num_rows = panda_file_n_rows(\"/content/drive/MyDrive/Datascience&MachineLearning/datasets/PSMaster.xlsx\")\n", 1389 | "print(xl_file.iloc[0])" 1390 | ], 1391 | "metadata": { 1392 | "colab": { 1393 | "base_uri": "https://localhost:8080/" 1394 | }, 1395 | "id": "v5CVCk4kZVMV", 1396 | "outputId": "e7b0e369-8575-41f1-c22a-e76e39d44e9a" 1397 | }, 1398 | "execution_count": 25, 1399 | "outputs": [ 1400 | { 1401 | "output_type": "stream", 1402 | "name": "stdout", 1403 | "text": [ 1404 | "dist_code 12\n", 1405 | "pc_no 20\n", 1406 | "ac_no 111\n", 1407 | "ps_sno 1\n", 1408 | "ps_name_en Panchayat Union Elementary School,North Facing...\n", 1409 | "ps_area_en 1.Nellithurai Ward No. 1\\n2.Nandhavanam Pudur...\n", 1410 | "ps_name_ta ஊராட்சி ஒன்றிய துவக்கப்பள்ளி, வடக்கு பார்த்த க...\n", 1411 | "ps_area_ta 1.நெல்லித்துறை வார்டு எண். 1\\n2.நந்தவனம் புதூர...\n", 1412 | "ps_total_voters 1082.0\n", 1413 | "Name: 0, dtype: object\n" 1414 | ] 1415 | } 1416 | ] 1417 | }, 1418 | { 1419 | "cell_type": "code", 1420 | "source": [ 1421 | "print(num_rows)" 1422 | ], 1423 | "metadata": { 1424 | "colab": { 1425 | "base_uri": "https://localhost:8080/" 1426 | }, 1427 | "id": "YLm1qw3wZlEm", 1428 | "outputId": "7ca902e0-3576-4041-cbb1-fc8c4b96feb1" 1429 | }, 1430 | "execution_count": 26, 1431 | "outputs": [ 1432 | { 1433 | "output_type": "stream", 1434 | "name": "stdout", 1435 | "text": [ 1436 | "2661\n" 1437 | ] 1438 | } 1439 | ] 1440 | } 1441 | ] 1442 | } -------------------------------------------------------------------------------- /profiling_in_python.py: -------------------------------------------------------------------------------- 1 | # Profiling using time module 2 | """ 3 | time() module is a simple way to measure execution time. 4 | """ 5 | """ 6 | import time 7 | 8 | def slow_function(): 9 | total = 0 10 | for i in range(100000000): 11 | total+=i 12 | return total 13 | 14 | start_time = time.time() 15 | result = slow_function() 16 | end_time = time.time() 17 | 18 | print(f"Result: {result}") 19 | print(f"Time taken: {end_time-start_time:.4f} seconds") 20 | """ 21 | 22 | # cProfile 23 | """ 24 | cProfile is a python's built-in profiling tool, offering detailed statistics like call counts, total time, and per-call time. 25 | """ 26 | """ 27 | import cProfile 28 | 29 | def factorial(n): 30 | if n == 0: 31 | return 1 32 | return n * factorial(n-1) 33 | 34 | def main(): 35 | result = factorial(5) 36 | print(f"Result: {result}") 37 | 38 | cProfile.run("main()") 39 | """ 40 | # line_profiler 41 | """ 42 | line_profiler (install with pip install line_profiler) profiles code line by line. 43 | Use the @profile decorator and run with kernprof. 44 | """ 45 | """ 46 | @profile 47 | def expensive_loop(): 48 | total = 0 49 | for i in range(1000): 50 | total += i**2 51 | return total 52 | result = expensive_loop() 53 | print(f"Result: {result}") 54 | """ 55 | """ 56 | Run Commands: 57 | kernprof -l profiling_in_python.py 58 | python3 -m line_profiler profiling_in_python.py.lprof 59 | """ 60 | # memory_profiler 61 | """ 62 | memory_profiler (install with pip install memory_profiler) tracks memory consumption line by line. 63 | """ 64 | """ 65 | from memory_profiler import profile 66 | 67 | @profile 68 | def memory_hog(): 69 | a = [1] * (10 ** 6) 70 | b = [2] * (10 ** 6) 71 | return a+b 72 | 73 | if __name__ == "__main__": 74 | memory_hog() 75 | """ 76 | """ 77 | Run command: 78 | python -m memory_profiler profiling_in_python.py 79 | """ 80 | # timieit 81 | """ 82 | The timeit module, built into Python, measures execution time of small code snippets across multiple runs for accuracy. 83 | """ 84 | import timeit 85 | 86 | def list_comprehension(): 87 | return [x * x for x in range(1000)] 88 | 89 | execution_time = timeit.timeit(list_comprehension, number=1000) 90 | print(f"Execution time for 1000 runs: {execution_time:.4f} seconds") 91 | -------------------------------------------------------------------------------- /program_utils.py: -------------------------------------------------------------------------------- 1 | import smtplib, ssl 2 | from email.mime.text import MIMEText 3 | from email.mime.image import MIMEImage 4 | from email.mime.multipart import MIMEMultipart 5 | import os 6 | from dotenv import load_dotenv 7 | from twilio.rest import Client 8 | import re 9 | from github import Auth, Github 10 | 11 | 12 | 13 | load_dotenv() 14 | class programUtilities: 15 | def __init__(self): 16 | #mail 17 | self.smtp_server = "smtp.gmail.com" 18 | self.port = 587 19 | self.context = ssl.create_default_context() 20 | self.sender_mail = os.getenv("SENDER_MAIL") 21 | self.password = os.getenv("PASSWORD") 22 | self.server = smtplib.SMTP(self.smtp_server, self.port) 23 | self.server.ehlo() 24 | self.server.starttls(context=self.context) 25 | self.server.ehlo() 26 | self.msg = MIMEMultipart() 27 | 28 | #whatsapp 29 | self.from_ = os.getenv("FROM_") 30 | self.account_sid = os.getenv("ACCOUNT_SID") 31 | self.auth_token = os.getenv("AUTH_TOKEN") 32 | self.client = Client(self.account_sid, self.auth_token) 33 | 34 | 35 | 36 | #sending mail instantly 37 | def send_mail_instant(self, rec_mail, image_to_send): 38 | #image_data 39 | with open(image_to_send, 'rb') as f: 40 | img_data = f.read() 41 | self.msg["Subject"] = "Alert!! Stranger Detected!!" 42 | self.msg["FROM"] = self.sender_mail 43 | self.msg["TO"] = rec_mail 44 | text = MIMEText("Alert!! Stranger!!") 45 | self.msg.attach(text) 46 | image = MIMEImage(img_data, name=os.path.basename(image_to_send)) 47 | self.msg.attach(image) 48 | try: 49 | self.server.login(self.sender_mail, self.password) 50 | self.server.sendmail(self.sender_mail, rec_mail, self.msg.as_string()) 51 | except Exception as e: 52 | print(e) 53 | 54 | #final mail 55 | def final_mail(self, rec_mail, link): 56 | self.msg["Subject"] = "Daily Report!" 57 | self.msg["From"] = self.sender_mail 58 | self.msg["To"] = rec_mail 59 | text = MIMEText(f"Click on the link below \n{link}") 60 | self.msg.attach(text) 61 | try: 62 | self.server.login(self.sender_mail, self.password) 63 | self.server.sendmail(self.sender_mail, rec_mail, self.msg.as_string()) 64 | except Exception as e: 65 | print(e) 66 | 67 | #Whatsapp msg instant 68 | def send_whatsapp_msg_instant(self, rec_mobile, img_link): 69 | try: 70 | message = self.client.messages.create( 71 | body=f"Alert! Stranger Detected!", 72 | media_url="https://raw.githubusercontent.com/arun-arunisto/UploadingImages/todo/"+img_link, 73 | from_=self.from_, 74 | to=f"whatsapp:+91{rec_mobile}" 75 | ) 76 | print("Whatsapp message sid:",message.sid) 77 | except Exception as e: 78 | print(e) 79 | 80 | #Whatsapp msg final 81 | def send_whatsapp_msg_final(self, rec_mobile, link): 82 | try: 83 | message = self.client.messages.create( 84 | body=f"Daily Report!\nClick the below link!\n{link}", 85 | from_=self.from_, 86 | to=f"whatsapp:+91{rec_mobile}" 87 | ) 88 | print("Whatsapp message sid:",message.sid) 89 | except Exception as e: 90 | print(e) 91 | 92 | #creating folders to save images 93 | def images_save_path(self, folder_name): 94 | folder_name = re.sub(r'[<>:"/\\|?*]', '_', folder_name) 95 | path = os.path.join("images/", folder_name) 96 | try: 97 | os.mkdir(path) 98 | except FileExistsError: 99 | pass 100 | return path 101 | 102 | #uploading images to github for whatsapp 103 | def image_to_github(self, path_to_file): 104 | auth = Auth.Token(os.getenv("GIT_TOKEN")) 105 | user = Github(auth=auth) 106 | repo = user.get_repo(os.getenv("GIT_REPO")) 107 | try: 108 | with open(path_to_file, "rb") as file: 109 | data = file.read() 110 | 111 | repo.create_file(path_to_file, "uploading image", data, branch=os.getenv("GIT_BRANCH")) 112 | print("Git hub repo id:",repo.id) 113 | except Exception as e: 114 | print(e) 115 | 116 | 117 | 118 | if __name__ == "__main__": 119 | print(os.getenv("GIT_TOKEN")) 120 | -------------------------------------------------------------------------------- /python_mongob_cheatcode.py: -------------------------------------------------------------------------------- 1 | # to install pymongo use the below cmd 2 | """ 3 | pip install 'pymongo[srv]' 4 | """ 5 | import datetime 6 | 7 | from pymongo import MongoClient 8 | from dotenv import load_dotenv 9 | import os 10 | from bson.objectid import ObjectId 11 | import pprint 12 | 13 | load_dotenv() 14 | 15 | # the connection string i loaded on .env and it accessed using os 16 | MONGODB_URI = os.getenv("MONGODB_URI") 17 | 18 | #connecting to mongodb client using above string 19 | client = MongoClient(MONGODB_URI) 20 | 21 | #printing all database names inside the cluster 22 | #the below code print database names inside a cluster on a form of list 23 | #print("Databases:\n",client.list_database_names()) 24 | 25 | #geting refrence to database 26 | db = client.test 27 | 28 | #getting refrence to collection 29 | test_collec = db.test_collection 30 | 31 | 32 | #adding data inside a collection 33 | """ 34 | sample_data = { 35 | "name":"arun arunisto", 36 | "age":27, 37 | "tags":["developer", "tech geek"], 38 | "details":{ 39 | "job":"full-stack developer", 40 | "organisation":"nic" 41 | }, 42 | "created_at":datetime.datetime.utcnow() 43 | } 44 | 45 | # inserting one data using insert_one() function 46 | result = test_collec.insert_one(sample_data) 47 | 48 | #checking the inserted data using refrence_id 49 | document_id = result.inserted_id 50 | print("Inserted _id document:",document_id) 51 | """ 52 | 53 | # inserting multiple data using insert_many method 54 | """ 55 | sample_data_1 = { 56 | "name":"arun", 57 | "age":27, 58 | "tags":["pythonista", "cyborg"], 59 | "details":{ 60 | "job":"AI/ML", 61 | "organisation":"xAI" 62 | }, 63 | "created_at":datetime.datetime.utcnow() 64 | } 65 | 66 | sample_data_2 = { 67 | "name":"arunisto", 68 | "age":27, 69 | "tags":["backend", "fast api"], 70 | "details":{ 71 | "job":"IOT Engineer", 72 | "organisation":"tesla" 73 | }, 74 | "created_at":datetime.datetime.utcnow() 75 | } 76 | 77 | #using insert_many() function to insert multiple data 78 | result = test_collec.insert_many([sample_data_1, sample_data_2]) 79 | 80 | document_ids = result.inserted_ids 81 | print("No. Documents added:",len(document_ids)) 82 | print("_ids of inserted:\n",document_ids) 83 | """ 84 | 85 | #accessing a single data using find_one() function 86 | """ 87 | #query to access a data 88 | # for use Object id in your program u need to import it from the bson object 89 | id = {"_id":ObjectId('654e604707f115c93d316013')} 90 | result = test_collec.find_one(id) 91 | print("Retrieved data:\n",result) 92 | #pprint using to print in a document form 93 | pprint.pprint(result) 94 | """ 95 | 96 | #accessing all data/multiple data using find() function 97 | """ 98 | result = test_collec.find() 99 | for document in result: 100 | pprint.pprint(document) 101 | """ 102 | 103 | # updating a single data using update_one() function 104 | """ 105 | document_to_update = {'_id': ObjectId('654e5e80ad5db1b63c82220c')} 106 | field_to_update = {"$inc":{"age":1}} 107 | result = test_collec.update_one(document_to_update, field_to_update) 108 | print("Updated Count:",result.modified_count) 109 | """ 110 | 111 | #updating multiple document using update_many() function 112 | """ 113 | doc_filter = {"age":{"$eq":27}} 114 | add_new_field = {"$inc":{"age":1}} 115 | result = test_collec.update_many(doc_filter, add_new_field) 116 | print("Document Matched:",result.matched_count) 117 | print("Updated:",result.modified_count) 118 | """ 119 | 120 | #deleting documents using delete_one() and delete_many() method 121 | """ 122 | document_to_delete = {"name":"test1"} 123 | #deleting using delete_one() method 124 | result = test_collec.delete_one(document_to_delete) 125 | print("No. of deleted documents:",result.deleted_count) 126 | """ 127 | 128 | #deleting multiple elements using delete_many() method 129 | """ 130 | doc_to_filter = {"age":{"$eq":28}} 131 | result = test_collec.delete_many(doc_to_filter) 132 | print("No.of Documents deleted:",result.deleted_count) 133 | """ 134 | client.close() 135 | 136 | 137 | -------------------------------------------------------------------------------- /python_mysql_cheatcodes.py: -------------------------------------------------------------------------------- 1 | #pip install mysql-connector-python -> for install mysql-connector 2 | 3 | import mysql.connector 4 | from mysql.connector import errorcode 5 | 6 | config = { 7 | "user":"root", 8 | 'password':'arunisto', 9 | 'host':'localhost', 10 | 'database':'sample_database' 11 | } #add database only after creating the database and you can use database if already existed! 12 | 13 | db = mysql.connector.connect(**config) 14 | 15 | cursor = db.cursor() 16 | 17 | print("Connected Successfully!!") 18 | 19 | #Creating Database 20 | db_name = 'sample_database' 21 | """ 22 | cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name} DEFAULT CHARACTER SET 'utf8'") 23 | print("DB "+db_name+" created successfully") 24 | """ 25 | 26 | #Creating Table 27 | """ 28 | tables = {} 29 | 30 | tables['logs'] = ( 31 | "CREATE TABLE `logs` (" 32 | "`id` int(11) NOT NULL AUTO_INCREMENT," 33 | "`text` varchar(250) NOT NULL, " 34 | "`user` varchar(250) NOT NULL, " 35 | "`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, " 36 | "PRIMARY KEY (`id`)" 37 | ") ENGINE=InnoDB" 38 | ) 39 | 40 | cursor.execute("USE {}".format(db_name)) 41 | try: 42 | cursor.execute(tables['logs']) 43 | except mysql.connector.Error as err: 44 | if err.errno == errorcode.ER_TABLE_EXISTS_ERROR: 45 | print("Table already exists") 46 | else: 47 | print(err.msg) 48 | print("Table Created successfully!") 49 | """ 50 | 51 | 52 | #Adding data into database 53 | """ 54 | sql = "INSERT INTO logs(text, user) VALUES (%s, %s)" 55 | values = ("Added log one", "arun") 56 | cursor.execute(sql, values) 57 | db.commit() 58 | log_id = cursor.lastrowid 59 | print(log_id, "Data added successfully!!") 60 | """ 61 | 62 | 63 | #fetching data from database 64 | """ 65 | sql = "SELECT * FROM logs" 66 | cursor.execute(sql) 67 | result = cursor.fetchall() 68 | print(result) 69 | """ 70 | 71 | 72 | #fetching single data from database 73 | """ 74 | sql = "SELECT * FROM logs WHERE id=%s" 75 | cursor.execute(sql, (1,)) #the one is already existed in database thats why iam using 1 for fetch 76 | data = cursor.fetchone() 77 | print(data) 78 | """ 79 | 80 | 81 | #updating data 82 | """ 83 | sql = "UPDATE logs SET text = %s WHERE id = %s" 84 | values = ("text updated", 1) 85 | cursor.execute(sql, values) 86 | db.commit() 87 | print("Updated Successfully!!") 88 | """ 89 | 90 | 91 | #deleting data 92 | sql = "DELETE FROM logs WHERE id = %s" 93 | cursor.execute(sql, (1, )) 94 | db.commit() 95 | print("Deleted Successfully!!") -------------------------------------------------------------------------------- /python_oops_concept.py: -------------------------------------------------------------------------------- 1 | class Sample: 2 | full_name = "Arun Arunisto" #This is class attribute 3 | def __init__(self, name): #Initializing/creating instance attribute 4 | self.name = name #instance attribute 5 | 6 | obj = Sample("Arun") #Instantiate means creating an object using class 7 | 8 | #object can access class attribute and instance attribute like below 9 | print(obj.name) #instance attribute 10 | print(obj.full_name) #class attribute 11 | 12 | #you can change attributes value dynamically 13 | obj.name = "Arun Arunisto" 14 | obj.full_name = "Arun" 15 | print(obj.name) 16 | print(obj.full_name) 17 | 18 | #so the objects are mutable because it can change dynamically 19 | 20 | #### Dunder method __str__ representation ### 21 | class Person: 22 | species = "Homosapiens" 23 | def __init__(self, name, age): 24 | self.name = name 25 | self.age = age 26 | 27 | #instance method 28 | def details(self): 29 | return f"Name : {self.name} | Age:{self.age}" 30 | 31 | #Another instance method 32 | def name_change(self, name): 33 | self.name = name 34 | 35 | #this will represent the object 36 | def __str__(self): 37 | return f"Name: {self.name}" 38 | 39 | per1 = Person("Arun", 25) 40 | print(per1.details()) 41 | per1.name_change("Arun Arunisto") 42 | print(per1.details()) 43 | print(per1) #it will return a crytic type output shows where object saves in memory 44 | #but you can set the print option of an object by creating a __str__() method 45 | print(per1) #printing after the __str__() method 46 | 47 | #these type of methods (__init__, __str__) are called dunder methods 48 | #there are lots of dunder methods -> understanding the dunder methods is one of the key for mastering in oops 49 | 50 | ### Name Mangling ### 51 | class Sample: 52 | #name mangling is the process declaring methods/attributes public, non-public, or private 53 | def __init__(self, name): 54 | self.__name = name #private instance attributes 55 | 56 | def __details(self): #private instance method 57 | return self.__name 58 | 59 | def __str__(self): 60 | return self.__name 61 | 62 | def __doc__(self): 63 | return "Class to demonstrate Name Mangling" 64 | 65 | 66 | obj = Sample("Aruunisto") 67 | print(obj) 68 | print(vars(obj)) 69 | print(vars(Sample)) 70 | 71 | #you can't access private/non-public attributes/methods 72 | #but they're not strictly private you can access them by their mangled names 73 | print(obj._Sample__name) 74 | print(obj._Sample__details()) 75 | 76 | 77 | ### Adding instance attributes methods dynamically ### 78 | >>> class User: 79 | pass 80 | ... 81 | >>> arun = User() 82 | >>> arun.name = "Arun Arunisto" 83 | >>> arun.age = 25 84 | >>> arun.__dict__ 85 | {'name': 'Arun Arunisto', 'age': 25} 86 | 87 | >>> #adding instance attributes dynamically 88 | >>> arun = User() 89 | >>> arun.full_name = "arun arunisto" 90 | >>> arun.age = 25 91 | >>> arun.__dict__ 92 | {'full_name': 'arun arunisto', 'age': 25} 93 | >>> #and adding methods dynamically 94 | >>> def __init__(self, name, age): 95 | ... self.name = name 96 | ... self.age = age 97 | ... 98 | ... 99 | >>> User.__init__ = __init__ 100 | 101 | >>> def method(self): 102 | ... return self.name 103 | ... 104 | >>> User.method = method 105 | >>> arun = User("Arun", 25) 106 | >>> arun.method() 107 | 'Arun' 108 | 109 | #### Property & Descriptor based attribute #### 110 | from datetime import datetime 111 | 112 | class AgeCalculator: 113 | def __init__(self, year): 114 | self.year = year 115 | 116 | @property 117 | def year(self): 118 | return self._year 119 | 120 | @year.setter 121 | def year(self, value): 122 | if len(str(value)) != 4 or not isinstance(value, int) or value <= 0: 123 | raise ValueError("Not a valid year") 124 | self._year = value 125 | 126 | def age_calc(self): 127 | cur_year = datetime.now().year 128 | return int(cur_year) - self._year 129 | 130 | obj = AgeCalculator(1996) 131 | print(obj.age_cal()) #28 132 | obj.year = 2006 133 | print(obj.age_calc()) #18 134 | 135 | ##Error Cases 136 | obj.year = 19 #this will raise an error 137 | obj.year = 0000 #this will raise an error 138 | obj.year = 19.96 #this will raise an error 139 | obj.year = "1996" #this will also raise an error 140 | 141 | 142 | 143 | """ 144 | class : class is a blueprint for creating objects. 145 | it defines the attributes (data) and methods 146 | (function) that the objects will have 147 | object: object is an instance of a class 148 | """ 149 | #sample 150 | class Car: 151 | def __init__(self, brand, model): 152 | self.brand = brand 153 | self.model = model 154 | 155 | def drive(self): 156 | print(f"{self.brand} {self.model} is driving") 157 | 158 | #creating objects of the class 159 | car_1 = Car("Toyota", "Corolla") 160 | car_2 = Car("Tesla", "Model S") 161 | 162 | #calling methods on object 163 | car_1.drive() 164 | car_2.drive() 165 | 166 | """ 167 | Inheritance 168 | Inheritance allows a class(sub class) to inherit 169 | attributes and methods from another class (super class) 170 | """ 171 | class Employee_details: 172 | def __init__(self, name, age): 173 | self.name = name 174 | self.age = age 175 | 176 | def emp_details(self): 177 | print("Employee name:",self.name) 178 | print("Employee age:",self.age) 179 | 180 | class Employee_designation(Employee_details): 181 | def __init__(self, name, age, designation, salary): 182 | Employee_details.__init__(self, name, age) 183 | self.designation = designation 184 | self.salary = salary 185 | 186 | def emp_details_with_designation(self): 187 | print("Employee name:",self.name) 188 | print("Employee age:",self.age) 189 | print("Employee designation:",self.designation) 190 | print("Employee salary:",self.salary) 191 | 192 | #calling subclass on object 193 | emp_1 = Employee_designation("Arunisto", 25, "Developer", "$60k") 194 | 195 | #accessing child method 196 | emp_1.emp_details_with_designation() 197 | #accessing parent class too 198 | emp_1.emp_details() 199 | print(emp_1.name) 200 | 201 | """ 202 | Encapsulation: 203 | Encapsulation is the bundling data and methods on that single unit class 204 | """ 205 | class BankAccount: 206 | def __init__(self, account_no, balance): 207 | self.account_no = account_no 208 | self.__balance = balance #private variable 209 | 210 | def deposit_amount(self, amt): 211 | self.__balance+=amt 212 | 213 | def withdraw_amount(self, amt): 214 | self.__balance-=amt 215 | 216 | def get_balance(self): 217 | return self.__balance 218 | 219 | acc_1 = BankAccount("12345", 5000) 220 | print(acc_1.get_balance()) 221 | acc_1.deposit_amount(100) 222 | print(acc_1.get_balance()) 223 | print(acc_1._BankAccount__balance) #accessing private variable 224 | 225 | """ 226 | Data Abstraction: 227 | It involves the process of hiding the implementation details of a system and only showing the essential features of the object. 228 | """ 229 | from math import pi 230 | 231 | class Shape: 232 | def __init__(self, val): 233 | self.val = val 234 | def get_area(self): 235 | raise NotImplementedError("Not Accessible!") 236 | def get_perimeter(self): 237 | raise NotImplementedError("Not Accessible!") 238 | 239 | class Circle(Shape): 240 | #val represents radius here. 241 | def __init__(self, val): 242 | super().__init__(val) 243 | def get_area(self): 244 | return pi*self.val**2 245 | def get_perimeter(self): 246 | return 2*pi*self.val 247 | class Square(Shape): 248 | #val represents side here 249 | def __init__(self, val): 250 | super().__init__(val) 251 | def get_area(self): 252 | return 2*self.val 253 | def get_perimeter(self): 254 | return 4*self.val 255 | 256 | 257 | circle = Circle(14) 258 | print(circle.get_area()) 259 | square = Square(25) 260 | print(square.get_perimeter()) 261 | shape = Shape(25) 262 | print(shape.get_area()) #it will raise an error 263 | 264 | """ 265 | Abstract Base Classes: 266 | Using `abc` module for abstract the python classes 267 | """ 268 | from math import pi 269 | from abc import ABC, abstractmethod 270 | 271 | class Shape(ABC): 272 | def __init__(self, value): 273 | self.value = value 274 | 275 | @abstractmethod 276 | def get_area(self): 277 | pass 278 | @abstractmethod 279 | def get_perimeter(self): 280 | pass 281 | 282 | class Circle(Shape): 283 | #here value referesd as radius 284 | def __init__(self, value): 285 | super().__init__(value) 286 | 287 | def get_area(self): 288 | return pi*self.value**2 289 | def get_perimeter(self): 290 | return 2*pi*self.value 291 | 292 | """ 293 | MRO - Method Resolution Order 294 | It helps python to do the multiple inheritance 295 | """ 296 | #MRO - Test Case - 1 297 | class A: 298 | def __init__(self): 299 | print("Class A") 300 | 301 | class B(A): 302 | def __init__(self): 303 | super().__init__() 304 | print("Class B") 305 | 306 | class C(A): 307 | def __init__(self): 308 | super().__init__() 309 | print("Class C") 310 | 311 | class D(C, B): 312 | def __init__(self): 313 | super().__init__() 314 | print("Class D") 315 | # The MRO will be for this code 316 | obj = D() 317 | obj.__mro__ 318 | """ 319 | Class D --> Class C --> Class B --> Class A --> object 320 | """ 321 | 322 | """ 323 | MRO - Next approach changeing parent swap 324 | """ 325 | class A: 326 | def __init__(self): 327 | print("Class A") 328 | 329 | class B(A): 330 | def __init__(self): 331 | super().__init__() 332 | print("Class B") 333 | 334 | class C(A): 335 | def __init__(self): 336 | super().__init__() 337 | print("Class C") 338 | 339 | class D(B, C): 340 | def __init__(self): 341 | super().__init__() 342 | print("Class D") 343 | # The MRO will be for this code 344 | """ 345 | Class D --> Class B --> Class C --> Class A --> object 346 | """ 347 | -------------------------------------------------------------------------------- /python_postgresql_cheatcodes.py: -------------------------------------------------------------------------------- 1 | #>> pip install psycopg2 2 | 3 | import psycopg2 4 | from psycopg2 import Error 5 | 6 | connect = psycopg2.connect( 7 | user="postgres", 8 | password="arunisto", 9 | host="localhost", 10 | port="5433", 11 | database="sample", #change the database after creating it before it's template1(default) 12 | ) 13 | 14 | #cursor 15 | cursor = connect.cursor() 16 | #connect.autocommit = True 17 | 18 | #creating database 19 | """ 20 | sql = "CREATE DATABASE sample;" 21 | try: 22 | cursor.execute(sql) 23 | print("Database Created Successfully!") 24 | except (Exception, Error) as e: 25 | print(e) 26 | """ 27 | 28 | #creating table 29 | """ 30 | sql = ("CREATE TABLE logs (id SERIAL PRIMARY KEY," 31 | "text VARCHAR(250), name VARCHAR(100)," 32 | "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);") 33 | cursor.execute(sql) 34 | connect.commit() 35 | print("Table Created Successfully!") 36 | """ 37 | 38 | #Inserting data into table 39 | """ 40 | sql = "INSERT INTO logs (text, name) VALUES (%s, %s)" 41 | data = ("This is sample text", "arunisto") 42 | cursor.execute(sql, data) 43 | connect.commit() 44 | print("Data Added Successfully!") 45 | """ 46 | 47 | #fetching data from the table 48 | """ 49 | sql = "SELECT * FROM logs;" 50 | cursor.execute(sql) 51 | result = cursor.fetchall() 52 | print(result) 53 | """ 54 | 55 | #fetching one data from table 56 | """ 57 | sql = "SELECT * FROM logs WHERE id=1;" 58 | cursor.execute(sql) 59 | result = cursor.fetchone() 60 | print(result) 61 | """ 62 | 63 | #updating data on table 64 | """ 65 | sql = "UPDATE logs SET name=%s WHERE id=%s;" 66 | data = ("arun arunisto", "1") 67 | cursor.execute(sql, data) 68 | connect.commit() 69 | print("Data updated successfully!") 70 | """ 71 | 72 | #deleting data from table 73 | sql = ("DELETE FROM logs WHERE id=%s") 74 | data = ("1",) 75 | cursor.execute(sql, data) 76 | connect.commit() 77 | print("Deleted Successfully!") 78 | connect.close() -------------------------------------------------------------------------------- /python_speech_recognition_text_to_speech.py: -------------------------------------------------------------------------------- 1 | ###################################### 2 | '''dependencies''' 3 | # -> pip install speechrecognition 4 | # -> pip install pyaudio 5 | # -> pip install pyttsx3 6 | ###################################### 7 | 8 | import speech_recognition as sr 9 | import webbrowser 10 | import time 11 | import pyttsx3 12 | 13 | 14 | r = sr.Recognizer() 15 | 16 | #speech function 17 | engine = pyttsx3.init('sapi5') 18 | voices = engine.getProperty('voices') 19 | engine.setProperty('voice', voices[1].id) 20 | 21 | def speak(audio): 22 | engine.say(audio) 23 | engine.runAndWait() 24 | 25 | def record_audio(ask=False): 26 | if ask: 27 | speak(ask) 28 | with sr.Microphone() as source: 29 | audio = r.listen(source) 30 | voice_data = '' 31 | try: 32 | voice_data = r.recognize_google(audio) 33 | #print(voice_data) 34 | except sr.UnknownValueError: 35 | speak("Sorry i didn't get that") 36 | except sr.RequestError: 37 | speak("Sorry, my server is down") 38 | return voice_data 39 | 40 | 41 | def respond(voice_data): 42 | #search using google 43 | if 'search' in voice_data: 44 | search = record_audio('What do you want to search?') 45 | url = 'https://google.com/search?q=' + search 46 | webbrowser.get().open(url) 47 | speak('result found!') 48 | 49 | #google map location 50 | if 'find location' in voice_data: 51 | location = record_audio('What is the location?') 52 | url = 'https://google.nl/maps/place/'+location+'/&' 53 | webbrowser.get().open(url) 54 | speak('result found!') 55 | 56 | #to exit from the loop 57 | if 'exit' in voice_data: 58 | speak("Thank you for using me!") 59 | exit() 60 | 61 | time.sleep(1) 62 | speak("How can i help you!") 63 | while True: 64 | voice_record_data = record_audio() 65 | #print(voice_record_data) 66 | respond(voice_record_data) -------------------------------------------------------------------------------- /python_sqlite_cheatcodes.py: -------------------------------------------------------------------------------- 1 | #sqlite3 is a buit-in module you dont need to install anything 2 | import sqlite3 as sqlite 3 | 4 | # Connect to a new SQLite database (or create it if it doesn't exist) 5 | conn = sqlite.connect('example.db') 6 | 7 | # Create a cursor object to execute SQL commands 8 | cursor = conn.cursor() 9 | 10 | # Execute SQL commands to create tables 11 | cursor.execute("CREATE TABLE IF NOT EXISTS logs" 12 | "(id INTEGER PRIMARY KEY," 13 | "text TEXT," 14 | "user_name TEXT," 15 | "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)") 16 | 17 | # Commit changes 18 | conn.commit() 19 | print("Table Created Successfully!!") 20 | 21 | # Insert data into the 'logs' table 22 | sql = "INSERT INTO logs (text, user_name) VALUES (?, ?)" 23 | values = ("Added log one", "arunisto") 24 | cursor.execute(sql, values) 25 | conn.commit() 26 | print("Data Added Successfully!!") 27 | 28 | # Retrieve data from the 'logs' table 29 | cursor.execute("SELECT * FROM logs") 30 | data = cursor.fetchall() 31 | print("Retrieve using fetchall()\n",data) 32 | 33 | # Retrieve one data from the 'logs' table 34 | sql = "SELECT * FROM logs WHERE id=?" 35 | value = (1, ) 36 | cursor.execute(sql, value) 37 | data = cursor.fetchone() 38 | print("Retrieve using fetchone()\n",data) 39 | 40 | # Update the user_name of the user with name 'arun arunisto' 41 | sql = "UPDATE logs SET user_name=? WHERE id=?" 42 | values = ("arun arunisto", 1) 43 | cursor.execute(sql, values) 44 | conn.commit() 45 | print("Updated Successfully!") 46 | 47 | # Retrieve data from the 'logs' table 48 | cursor.execute("SELECT * FROM logs") 49 | data = cursor.fetchall() 50 | print("Retrieve after update\n",data) 51 | 52 | # Delete the user with id 1 53 | sql = "DELETE FROM logs WHERE id=?" 54 | values = (1, ) 55 | cursor.execute(sql, values) 56 | conn.commit() 57 | print("Deleted Successfully") 58 | 59 | #closing the connection 60 | conn.close() 61 | 62 | print("Connection Closed Successfully!") 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /rb_workoutfile_or_utils.py: -------------------------------------------------------------------------------- 1 | #### Generating a random 32 bits word ####### 2 | import string 3 | import random 4 | 5 | letters, digits, spl_chr = string.ascii_letters, string.digits, string.punctuation 6 | secret_key = ''.join(random.choices(letters+digits+spl_chr, k=32)) 7 | print(secret_key) 8 | -------------------------------------------------------------------------------- /recurssion_workoutfile.py: -------------------------------------------------------------------------------- 1 | #reverse string using recurssion 2 | def reverse_str(str, n, result=""): 3 | if n<0: 4 | return result 5 | letter = str[n] 6 | result+=letter 7 | return reverse_str(str, n-1, result) 8 | 9 | a = "Arun Arunisto" 10 | print(reverse_str(a, len(a)-1)) 11 | 12 | #reverse an integer using recurrsion 13 | def reverse_int(num, result=0): 14 | if num == 0: 15 | return result 16 | digit = num%10 17 | result = result*10+digit 18 | num//=10 19 | return reverse_int(num, result) 20 | print(reverse_int(123)) 21 | 22 | # 06.05.2024 23 | #reverse string 24 | def reverse_str(str, result=""): 25 | if str == "": 26 | return result 27 | result += str[-1] 28 | return reverse_str(str[:-1], result) 29 | 30 | #palindrome 31 | def palindrome_str(str): 32 | if str == "": 33 | return True 34 | if str[0] == str[-1]: 35 | return palindrome_str(str[1:-1]) 36 | return False 37 | 38 | #recursion with int 39 | #palindrome 40 | def palindrome_str(str): 41 | if str == "": 42 | return True 43 | if str[0] == str[-1]: 44 | return palindrome_str(str[1:-1]) 45 | return False 46 | 47 | #sum of natural numbers 48 | def sum_numbers(num, result=0): 49 | if num == 0: 50 | return result 51 | result+=num 52 | return sum_numbers(num-1, result) 53 | 54 | #sum of natural numbers - FCC 55 | def sum_of_num(num): 56 | if num <= 1: 57 | return num 58 | return num+sum_of_num(num-1) 59 | 60 | ## 07.05.2024 61 | #binary search 62 | def binary_search(li, start, end, target): 63 | if start > end: 64 | return False 65 | mid = (start+end)//2 66 | if li[mid] == target: 67 | return True 68 | if target < li[mid]: 69 | return binary_search(li, start, mid-1, target) 70 | else: 71 | return binary_search(li, mid+1, end, target) 72 | 73 | #fibonacci series 74 | def fib_series(n): 75 | if n <= 1: 76 | return n 77 | return fib_series(n-1) + fib_series(n-2) 78 | 79 | #merge sort 80 | def merge_sort(li): 81 | if len(li) < 2: 82 | return li 83 | mid = len(li)//2 84 | left_arr = li[0:mid] 85 | right_arr = li[mid:len(li)] 86 | return merge(merge_sort(left_arr), merge_sort(right_arr)) 87 | 88 | def merge(left_arr, right_arr): 89 | result = [] 90 | left_idx = 0 91 | right_idx = 0 92 | while left_idx < len(left_arr) and right_idx < len(right_arr): 93 | if left_arr[left_idx] < right_arr[right_idx]: 94 | result.append(left_arr[left_idx]) 95 | left_idx+=1 96 | else: 97 | result.append(right_arr[right_idx]) 98 | right_idx+=1 99 | return result+left_arr[left_idx:]+right_arr[right_idx:] 100 | 101 | -------------------------------------------------------------------------------- /sending_mails.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | 3 | #simple mail sending 4 | server = smtplib.SMTP('smtp.gmail.com', 587) 5 | server.starttls() 6 | server.login("", "") 7 | message = "message content" 8 | server.sendmail("", "", message) 9 | server.quit() 10 | 11 | #mail sending using user-agent 12 | from email.mime.text import MIMEText 13 | from email.mime.multipart import MIMEMultipart 14 | 15 | message = MIMEMultipart() 16 | message['From'] = "" 17 | message["To"] = "", "") 30 | server.sendmail("", "", message.as_string()) 31 | -------------------------------------------------------------------------------- /sortedPython.py: -------------------------------------------------------------------------------- 1 | #sorted 2 | a = [5, 1, 4, 3] 3 | print(sorted(a)) #[1, 3, 4, 5] 4 | #reverse = True sorting from backwards 5 | print(sorted(a, reverse=True)) #[5, 4, 3, 1] 6 | 7 | strs = ['ccc', 'aaaa', 'd', 'bb'] 8 | #key= - to specify the sort 9 | #len - #by length of the data 10 | print(sorted(strs, key=len)) #['d', 'bb', 'ccc', 'aaaa'] 11 | 12 | strs = ['aa', 'BB', 'zz', 'CC'] 13 | #str.lower - to treat upper and lowercase as same 14 | print(sorted(strs, key=str.lower)) #['aa', 'BB', 'CC', 'zz'] 15 | 16 | #using own function in key= 17 | def MyFn(s): 18 | return s[-1] #to sort the list by last letter 19 | 20 | strs = ['xc', 'zb', 'yd' ,'wa'] 21 | print(sorted(strs, key=MyFn)) #['wa', 'zb', 'xc', 'yd'] 22 | 23 | #using itemgetter and attrgetter 24 | from operator import itemgetter 25 | grade = [('Freddy', 'Frank', 3), 26 | ('Anil', 'Frank', 100), ('Anil', 'Wang', 24)] 27 | print(sorted(grade, key=itemgetter(0, 0, 2))) 28 | 29 | -------------------------------------------------------------------------------- /stack_dsa_tutorial.py: -------------------------------------------------------------------------------- 1 | ## 08.05.2024 2 | # Creating stack using linkedlist 3 | """ 4 | Stack operations: 5 | creating node - [Done] 6 | creating stack - [Done] 7 | push - To insert an element to last - [Done] 8 | pop - To remove/out from the last (LIFO) concept - [Done] 9 | peak - To retreive data of the top - [Done] 10 | is_empty - to check the stack is empty - [Done] 11 | length - to get the size of the stack - [Done] 12 | traverse - to print the elements in the stack - [Done] 13 | """ 14 | 15 | class Node: 16 | def __init__(self, value): 17 | self.data = value 18 | self.next = None 19 | 20 | class Stack: 21 | def __init__(self): 22 | self.top = None 23 | 24 | def is_empty(self): 25 | return self.top == None 26 | 27 | def push(self, value): 28 | new_node = Node(value) 29 | new_node.next = self.top 30 | self.top = new_node 31 | 32 | def pop(self): 33 | if self.is_empty(): 34 | return "Stack is empty!!" 35 | data = self.top.data 36 | self.top = self.top.next 37 | return data 38 | 39 | def peak(self): 40 | if self.is_empty(): 41 | return "Stack is empty!!" 42 | return self.top.data 43 | 44 | def __len__(self): 45 | size = 0 46 | if self.is_empty(): 47 | return size 48 | curr = self.top 49 | while curr != None: 50 | size+=1 51 | curr = curr.next 52 | return size 53 | 54 | def __str__(self): 55 | result = "" 56 | curr = self.top 57 | while curr != None: 58 | result = result+str(curr.data)+", " 59 | curr = curr.next 60 | return "[ "+result[:-2]+" ]" 61 | -------------------------------------------------------------------------------- /subprocess_in_python.py: -------------------------------------------------------------------------------- 1 | #running a simple shell command 2 | import subprocess 3 | 4 | #list all files in a directory 5 | """ 6 | #for linux 7 | result = subprocess.run(['ls', '-l'], shell=True, 8 | capture_output=True, text=True) 9 | print(result.stdout) 10 | 11 | #for windows 12 | result = subprocess.run(['dir'], shell=True, 13 | capture_output=True, text=True) 14 | print(result.stdout) 15 | """ 16 | 17 | #checking disk space 18 | """ 19 | #for linux 20 | result = subprocess.run(['df', '-h'], shell=True, 21 | capture_output=True, text=True) 22 | print(result.stdout) 23 | 24 | #for windows 25 | result = subprocess.run(['tasklist'], shell=True, 26 | capture_output=True, text=True) 27 | print(result.stdout) 28 | """ 29 | 30 | #running an external program 31 | #linux 32 | server = "google.com" 33 | result = subprocess.run(["ping", "-c", "4", server], 34 | capture_output=True, text=True) 35 | 36 | if result.returncode == 0: 37 | print("Server is reachable") 38 | print(result.stdout) 39 | else: 40 | print("Server is unreachable") 41 | print(result.stderr) 42 | 43 | #windows 44 | server = "google.com" 45 | result = subprocess.run(["ping", "-n", "4", server], 46 | capture_output=True, text=True) 47 | 48 | if result.returncode == 0: 49 | print("Server is reachable") 50 | print(result.stdout) 51 | else: 52 | print("Server is unreachable") 53 | print(result.stderr) 54 | -------------------------------------------------------------------------------- /ternary_operations.py: -------------------------------------------------------------------------------- 1 | # ternary operations using if-else 2 | signal = "Green" 3 | result = "Move" if signal == "Green" else "Stop" 4 | print(result) # output: Move 5 | 6 | # ternary operations using tuple 7 | signal = "Green" 8 | result = ("Stop", "Move")[signal=="Green"] 9 | print(result) # output: Move 10 | 11 | # ternary operations using list 12 | signal = "Green" 13 | result = ["Stop", "Move"][signal == "Green"] 14 | print(result) #output: Move 15 | 16 | # ternary operations using dict 17 | signal = "Green" 18 | result = {"Green":"Move"} 19 | output = result.get(signal, "Stop") 20 | print(output) 21 | -------------------------------------------------------------------------------- /timeComplexityProgramms.py: -------------------------------------------------------------------------------- 1 | #O(1) - Constant 2 | def mid_idx(arr): 3 | mid = len(arr)//2 4 | return mid 5 | print(mid_idx([1, 2, 3, 4, 5, 6])) 6 | #O(n) - Linear Search 7 | def linearSearch(arr, target): 8 | for i in range(len(arr)): 9 | if arr[i] == target: 10 | return i 11 | return -1 12 | print(linearSearch([1, 2, 3, 4, 5, 6], 5)) 13 | #O(n^2) - Bubble Sort Algorithm 14 | def bubbleSort(arr): 15 | for i in range(len(arr)): 16 | for j in range(len(arr)-1): 17 | if arr[j] > arr[j+1]: 18 | arr[j], arr[j+1] = arr[j+1], arr[j] 19 | return arr 20 | print(bubbleSort([34, 12, 23, 55, 99, 101, 6])) 21 | #O(log n) - Binary Search Algorithm 22 | def binarySearch(arr, start, end, target): 23 | if start > end: 24 | return -1 25 | mid = (start+end)//2 26 | if arr[mid] == target: 27 | return mid 28 | if target < arr[mid]: 29 | return binarySearch(arr, start, mid-1, target) 30 | else: 31 | return binarySearch(arr, mid+1, end, target) 32 | li = [1, 2, 3, 4, 5, 6, 7, 8] 33 | print(binarySearch(li, 0, len(li)-1, 7)) 34 | #O(n log n) - Merge Sort Algorithm 35 | def mergeSort(arr): 36 | if len(arr) < 2: 37 | return arr 38 | mid = len(arr)//2 39 | left_arr = arr[0:mid] 40 | right_arr = arr[mid:len(arr)] 41 | return merge(mergeSort(left_arr), mergeSort(right_arr)) 42 | def merge(left_arr, right_arr): 43 | result = [] 44 | left_idx = 0 45 | right_idx = 0 46 | while left_idx < len(left_arr) and right_idx < len(right_arr): 47 | if left_arr[left_idx] < right_arr[right_idx]: 48 | result.append(left_arr[left_idx]) 49 | left_idx+=1 50 | else: 51 | result.append(right_arr[right_idx]) 52 | right_idx+=1 53 | return result+left_arr[left_idx:]+right_arr[right_idx:] 54 | li = [34, 12, 23, 55, 99, 101, 6] 55 | print(mergeSort(li)) 56 | #O(2^n) - Fibnoacci Series 57 | def fib_series(n): 58 | if n == 0: 59 | return 0 60 | if n == 1: 61 | return 1 62 | return fib_series(n-1) + fib_series(n-2) 63 | 64 | for i in range(5): 65 | print(fib_series(i), end=" ") 66 | #O(n!) - Factorial 67 | def factorial(n): 68 | if n == 0: 69 | print("*****") 70 | return 71 | for i in range(n): 72 | factorial(n-1) 73 | factorial(3) 74 | 75 | 76 | -------------------------------------------------------------------------------- /unittest_folder/project/__pycache__/test_str.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/__pycache__/test_str.cpython-311.pyc -------------------------------------------------------------------------------- /unittest_folder/project/__pycache__/tests.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/__pycache__/tests.cpython-311.pyc -------------------------------------------------------------------------------- /unittest_folder/project/code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/code/__init__.py -------------------------------------------------------------------------------- /unittest_folder/project/code/__pycache__/__init__.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/code/__pycache__/__init__.cpython-310.pyc -------------------------------------------------------------------------------- /unittest_folder/project/code/__pycache__/__init__.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/code/__pycache__/__init__.cpython-311.pyc -------------------------------------------------------------------------------- /unittest_folder/project/code/__pycache__/calculations.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/code/__pycache__/calculations.cpython-310.pyc -------------------------------------------------------------------------------- /unittest_folder/project/code/__pycache__/calculations.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/code/__pycache__/calculations.cpython-311.pyc -------------------------------------------------------------------------------- /unittest_folder/project/code/__pycache__/string_operations.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/code/__pycache__/string_operations.cpython-310.pyc -------------------------------------------------------------------------------- /unittest_folder/project/code/__pycache__/string_operations.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arun-arunisto/Python-Education/63a366d2914054489038db5eb8e3748f2ef3b82e/unittest_folder/project/code/__pycache__/string_operations.cpython-311.pyc -------------------------------------------------------------------------------- /unittest_folder/project/code/calculations.py: -------------------------------------------------------------------------------- 1 | class Calculator: 2 | def __init__(self, a, b): 3 | self.a = a 4 | self.b = b 5 | 6 | #addition 7 | def add(self): 8 | return self.a+self.b 9 | #subtraction 10 | def sub(self): 11 | return self.a-self.b 12 | #multiplication 13 | def mul(self): 14 | return self.a*self.b 15 | #division 16 | def div(self): 17 | return self.a/self.b 18 | 19 | -------------------------------------------------------------------------------- /unittest_folder/project/code/string_operations.py: -------------------------------------------------------------------------------- 1 | class StringOperations: 2 | def __init__(self, string): 3 | self.string = string 4 | #reverse string 5 | def reverse_string(self): 6 | return self.string[::-1] 7 | #upper case 8 | def upper_case(self): 9 | return self.string.upper() 10 | #lower case 11 | def lower_case(self): 12 | return self.string.lower() 13 | 14 | if __name__ == '__main__': 15 | string_op = StringOperations('arunisto') 16 | print(string_op.reverse_string()) 17 | print(string_op.upper_case()) 18 | print(string_op.lower_case()) 19 | -------------------------------------------------------------------------------- /unittest_folder/project/test_str.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from code.string_operations import StringOperations 3 | 4 | class testStringOperations(unittest.TestCase): 5 | def setUp(self): 6 | self.str_op = StringOperations('arunisto') 7 | def test_reverse_string(self): 8 | self.assertEqual(self.str_op.reverse_string(), 9 | 'otsinura', "Failed") 10 | def test_upper_case(self): 11 | self.assertEqual(self.str_op.upper_case(), 12 | 'ARUNISTO', "Failed") 13 | def test_lower_case(self): 14 | self.assertEqual(self.str_op.lower_case(), 15 | 'arunisto', "Failed") 16 | 17 | if __name__ == '__main__': 18 | unittest.main() 19 | 20 | -------------------------------------------------------------------------------- /unittest_folder/project/tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from code.calculations import Calculator 3 | 4 | 5 | class TestCalculator(unittest.TestCase): 6 | #calc = Calculator(24, 36) 7 | def setUp(self): 8 | self.calc = Calculator(24, 36) 9 | #test for addition 10 | def test_add(self): 11 | self.assertEqual(self.calc.add(),60, 12 | "The add() method is wrong") 13 | #test for subtraction 14 | def test_sub(self): 15 | self.assertEqual(self.calc.sub(), -12, 16 | "The sub() method is wrong") 17 | #test for multiplication 18 | def test_mul(self): 19 | self.assertEqual(self.calc.mul(), 864, 20 | "The mul() method is wrong") 21 | #test for division 22 | def test_div(self): 23 | self.assertEqual(self.calc.div(), 0.6666666666666666, 24 | "The div() method is wrong") 25 | 26 | if __name__ == '__main__': 27 | unittest.main() 28 | --------------------------------------------------------------------------------