├── README.md └── Algorithms Analysis and Design from Scratch Course-Code.ipynb /README.md: -------------------------------------------------------------------------------- 1 | ### Algorithms-Analysis-and-Design-from-Scratch-Course 2 | -------------------------------------------------------------------------------- /Algorithms Analysis and Design from Scratch Course-Code.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "fba7c058", 6 | "metadata": {}, 7 | "source": [ 8 | "## Circle Area" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 14, 14 | "id": "9efaeca1", 15 | "metadata": {}, 16 | "outputs": [ 17 | { 18 | "name": "stdout", 19 | "output_type": "stream", 20 | "text": [ 21 | "what the area radius? 2\n", 22 | "circle area = 12.566370614359172\n" 23 | ] 24 | } 25 | ], 26 | "source": [ 27 | "import numpy as np\n", 28 | "def circle_area():\n", 29 | " radius=float(input('what the area radius? '))\n", 30 | " # Area = πr²\n", 31 | " area=(np.pi) * (radius**2) \n", 32 | " print(f'circle area = {area}')\n", 33 | " \n", 34 | "circle_area() " 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "id": "e09ad085", 40 | "metadata": {}, 41 | "source": [ 42 | "## Parallelogram Area" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 15, 48 | "id": "4ced6d61", 49 | "metadata": {}, 50 | "outputs": [ 51 | { 52 | "name": "stdout", 53 | "output_type": "stream", 54 | "text": [ 55 | "what is the base? 2\n", 56 | "what is the height? 8\n", 57 | "parallelogram area = 16.0\n" 58 | ] 59 | } 60 | ], 61 | "source": [ 62 | "def parallelogram_area():\n", 63 | " base = float(input('what is the base? '))\n", 64 | " height=float(input('what is the height? '))\n", 65 | " # A = bh\n", 66 | " area = base * height\n", 67 | " print(f'parallelogram area = {area}')\n", 68 | " \n", 69 | "parallelogram_area()" 70 | ] 71 | }, 72 | { 73 | "cell_type": "markdown", 74 | "id": "5f9f9312", 75 | "metadata": {}, 76 | "source": [ 77 | "## Trapezoid Area" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 16, 83 | "id": "fadf4b34", 84 | "metadata": {}, 85 | "outputs": [ 86 | { 87 | "name": "stdout", 88 | "output_type": "stream", 89 | "text": [ 90 | "what is the short base? 3\n", 91 | "what is the long base? 7\n", 92 | "what is the height? 5\n", 93 | "trapezoid area = 25.0\n" 94 | ] 95 | } 96 | ], 97 | "source": [ 98 | "def trapezoid_area():\n", 99 | " short_base=float(input('what is the short base? '))\n", 100 | " long_base=float(input('what is the long base? '))\n", 101 | " height=float(input('what is the height? '))\n", 102 | " # A = (a+b)/2 * h\n", 103 | " area= (short_base+long_base)/2 * height\n", 104 | " print(f'trapezoid area = {area}')\n", 105 | "\n", 106 | "trapezoid_area()" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "id": "b60331da", 112 | "metadata": {}, 113 | "source": [ 114 | "## Standard deviation" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": 17, 120 | "id": "44e97a20", 121 | "metadata": {}, 122 | "outputs": [ 123 | { 124 | "name": "stdout", 125 | "output_type": "stream", 126 | "text": [ 127 | "total number of array elements: 8\n", 128 | "array element 0: 10\n", 129 | "array element 1: 12\n", 130 | "array element 2: 23\n", 131 | "array element 3: 23\n", 132 | "array element 4: 16\n", 133 | "array element 5: 23\n", 134 | "array element 6: 21\n", 135 | "array element 7: 16\n", 136 | "standard deviation = 4.898979485566356\n" 137 | ] 138 | } 139 | ], 140 | "source": [ 141 | "def standard_deviation():\n", 142 | " array_length=int(input('total number of array elements: '))\n", 143 | " array=[]\n", 144 | " for i in range(array_length):\n", 145 | " array.append(float(input(f'array element {i}: ')))\n", 146 | " \n", 147 | " # σ = squre_root(∑( X − μ )²/ n)\n", 148 | " mean=sum(array)/array_length\n", 149 | " squared_difference=0\n", 150 | " for i in array:\n", 151 | " squared_difference +=(i-mean)**2\n", 152 | " standard_deviation = np.sqrt(squared_difference/array_length)\n", 153 | " print(f'standard deviation = {standard_deviation}')\n", 154 | " \n", 155 | "standard_deviation()" 156 | ] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "id": "37ab23a7", 161 | "metadata": {}, 162 | "source": [ 163 | "## Correlation Coefficient" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 20, 169 | "id": "2a5d46a7", 170 | "metadata": {}, 171 | "outputs": [ 172 | { 173 | "name": "stdout", 174 | "output_type": "stream", 175 | "text": [ 176 | "sample size: 5\n", 177 | "first array element 0: 2\n", 178 | "first array element 1: 4\n", 179 | "first array element 2: 6\n", 180 | "first array element 3: 1\n", 181 | "first array element 4: 4\n", 182 | "second array element 0: 11\n", 183 | "second array element 1: 6\n", 184 | "second array element 2: 17\n", 185 | "second array element 3: 3\n", 186 | "second array element 4: 4\n", 187 | "correlation coefficient = 0.6097367084753432\n" 188 | ] 189 | } 190 | ], 191 | "source": [ 192 | "def correlation_coefficient():\n", 193 | " array_length=int(input('sample size: '))\n", 194 | " first_array=[]\n", 195 | " second_array=[]\n", 196 | " for i in range(array_length):\n", 197 | " first_array.append(float(input(f'first array element {i}: ')))\n", 198 | " for j in range(array_length):\n", 199 | " second_array.append(float(input(f'second array element {j}: ')))\n", 200 | " \n", 201 | " # r= (∑(x − X)(y-Y))/square_root(∑(x − X)² ∑( y − Y)²)\n", 202 | " first_array_mean=sum(first_array)/array_length\n", 203 | " second_array_mean=sum(second_array)/array_length\n", 204 | " x_y_difference=0\n", 205 | " x_squared_difference=0\n", 206 | " y_squared_difference=0\n", 207 | " for i,j in zip(first_array,second_array):\n", 208 | " x_y_difference += (i-first_array_mean)*(j-second_array_mean)\n", 209 | " x_squared_difference += (i-first_array_mean)**2\n", 210 | " y_squared_difference += (j-second_array_mean)**2\n", 211 | " correlation_coefficient = (x_y_difference)/np.sqrt(x_squared_difference*y_squared_difference)\n", 212 | " \n", 213 | " print(f'correlation coefficient = {correlation_coefficient}')\n", 214 | " \n", 215 | "correlation_coefficient()" 216 | ] 217 | }, 218 | { 219 | "cell_type": "markdown", 220 | "id": "4ed1e1a6", 221 | "metadata": {}, 222 | "source": [ 223 | "## Insertion Sort" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": 21, 229 | "id": "35547ac0", 230 | "metadata": {}, 231 | "outputs": [ 232 | { 233 | "name": "stdout", 234 | "output_type": "stream", 235 | "text": [ 236 | "total number of array elements: 9\n", 237 | "array element 0: 16\n", 238 | "array element 1: 27\n", 239 | "array element 2: 19\n", 240 | "array element 3: 2\n", 241 | "array element 4: 30\n", 242 | "array element 5: 10\n", 243 | "array element 6: 10\n", 244 | "array element 7: 27\n", 245 | "array element 8: 55\n", 246 | "sorted array is: [2, 10, 10, 16, 19, 27, 27, 30, 55]\n" 247 | ] 248 | } 249 | ], 250 | "source": [ 251 | "def insertion_sort():\n", 252 | " array_length=int(input('total number of array elements: '))\n", 253 | " array=[]\n", 254 | " for i in range(array_length):\n", 255 | " array.append(int(input(f'array element {i}: ')))\n", 256 | " \n", 257 | " # loop on every element in the array starting from second element\n", 258 | " # store the elemnt in temporary variaable\n", 259 | " for i in range(1,array_length):\n", 260 | " k=array[i]\n", 261 | " # loop on all previous elemnts\n", 262 | " for j in range(i-1,-1,-1):\n", 263 | " # check if previus is bigger\n", 264 | " if array[j] > k:\n", 265 | " array[j+1]=array[j]\n", 266 | " else:\n", 267 | " break\n", 268 | " array[j]=k\n", 269 | " \n", 270 | " print(f'sorted array is: {array}')\n", 271 | "\n", 272 | "insertion_sort()" 273 | ] 274 | }, 275 | { 276 | "cell_type": "markdown", 277 | "id": "ea5ab634", 278 | "metadata": {}, 279 | "source": [ 280 | "## Merge Sort" 281 | ] 282 | }, 283 | { 284 | "cell_type": "code", 285 | "execution_count": 22, 286 | "id": "a65d1830", 287 | "metadata": {}, 288 | "outputs": [ 289 | { 290 | "data": { 291 | "text/plain": [ 292 | "'sorted array = [1, 2, 5, 7, 9, 12]'" 293 | ] 294 | }, 295 | "execution_count": 22, 296 | "metadata": {}, 297 | "output_type": "execute_result" 298 | } 299 | ], 300 | "source": [ 301 | "def merge_sort(array):\n", 302 | " \n", 303 | " # recursion\n", 304 | " # check baase condition\n", 305 | " if len(array) > 1:\n", 306 | " # divide and conquer\n", 307 | " mid = len(array)//2\n", 308 | " left_array=array[:mid]\n", 309 | " right_array=array[mid:]\n", 310 | " merge_sort(left_array)\n", 311 | " merge_sort(right_array)\n", 312 | " # temporary variables for looping\n", 313 | " i=j=k=0\n", 314 | " while i < len(left_array) and j < len(right_array):\n", 315 | " if left_array[i] < right_array[j]:\n", 316 | " array[k] = left_array[i]\n", 317 | " i+=1\n", 318 | " k+=1\n", 319 | " else:\n", 320 | " array[k] = right_array[j]\n", 321 | " j+=1\n", 322 | " k+=1\n", 323 | " while i < len(left_array):\n", 324 | " array[k]=left_array[i]\n", 325 | " i+=1\n", 326 | " k+=1\n", 327 | " while j < len(right_array):\n", 328 | " array[k]=right_array[j]\n", 329 | " j+=1\n", 330 | " k+=1\n", 331 | " \n", 332 | " return f'sorted array = {array}'\n", 333 | "\n", 334 | "merge_sort([2,5,1,9,7,12])" 335 | ] 336 | }, 337 | { 338 | "cell_type": "markdown", 339 | "id": "a2a840b8", 340 | "metadata": {}, 341 | "source": [ 342 | "## Binary Search" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 23, 348 | "id": "4126c0c7", 349 | "metadata": {}, 350 | "outputs": [ 351 | { 352 | "data": { 353 | "text/plain": [ 354 | "('Not found', 1)" 355 | ] 356 | }, 357 | "execution_count": 23, 358 | "metadata": {}, 359 | "output_type": "execute_result" 360 | } 361 | ], 362 | "source": [ 363 | "def binary_search(array,item):\n", 364 | " # inputs\n", 365 | " # function arguments: sorted array and item to search for\n", 366 | " \n", 367 | " # process\n", 368 | " # divide the array and check at the mid point\n", 369 | " low = 0\n", 370 | " high = len(array) - 1\n", 371 | " while low <= high:\n", 372 | " mid = (low + high) // 2\n", 373 | " if item == array[mid]:\n", 374 | " return mid\n", 375 | " else:\n", 376 | " if item > array[mid]:\n", 377 | " low = mid + 1\n", 378 | " else:\n", 379 | " high = mid - 1\n", 380 | " return 'Not found'\n", 381 | " \n", 382 | "binary_search([2,5,8,10],700),binary_search([23,28,66,101],28)" 383 | ] 384 | }, 385 | { 386 | "cell_type": "markdown", 387 | "id": "4e6ff87d", 388 | "metadata": {}, 389 | "source": [ 390 | "## Segregate Positive and Negative Numbers" 391 | ] 392 | }, 393 | { 394 | "cell_type": "code", 395 | "execution_count": 24, 396 | "id": "c181f0fb", 397 | "metadata": {}, 398 | "outputs": [ 399 | { 400 | "data": { 401 | "text/plain": [ 402 | "'segregated array = [-2, -3, -1, -11, 2, 4, 5, 6, 9]'" 403 | ] 404 | }, 405 | "execution_count": 24, 406 | "metadata": {}, 407 | "output_type": "execute_result" 408 | } 409 | ], 410 | "source": [ 411 | "def segregate_positive_negative(array):\n", 412 | " # input\n", 413 | " # array of positive and negative numbers in function arguments\n", 414 | " \n", 415 | " # process\n", 416 | " # using merge sort \n", 417 | " if len(array) > 1:\n", 418 | " mid=len(array)//2\n", 419 | " left_array=array[:mid]\n", 420 | " righ_array=array[mid:]\n", 421 | " segregate_positive_negative(left_array)\n", 422 | " segregate_positive_negative(righ_array)\n", 423 | " i=j=k=0\n", 424 | " while i < len(left_array) and j < len(righ_array):\n", 425 | " if left_array[i] < 0:\n", 426 | " array[k]=left_array[i]\n", 427 | " i+=1\n", 428 | " k+=1\n", 429 | " elif righ_array[j] < 0:\n", 430 | " array[k]=righ_array[j]\n", 431 | " j+=1\n", 432 | " k+=1\n", 433 | " else:\n", 434 | " break\n", 435 | " while i < len(left_array):\n", 436 | " array[k]=left_array[i]\n", 437 | " i+=1\n", 438 | " k+=1\n", 439 | " while j < len(righ_array):\n", 440 | " array[k]=righ_array[j]\n", 441 | " j+=1\n", 442 | " k+=1\n", 443 | " \n", 444 | " return f'segregated array = {array}'\n", 445 | "\n", 446 | "segregate_positive_negative([2,4,-2,5,-3,6,9,-1,-11])\n", 447 | " " 448 | ] 449 | }, 450 | { 451 | "cell_type": "markdown", 452 | "id": "6753b4fd", 453 | "metadata": {}, 454 | "source": [ 455 | "## Greedy Algorithm- Activity Selection Problem" 456 | ] 457 | }, 458 | { 459 | "cell_type": "code", 460 | "execution_count": 25, 461 | "id": "51e85dd1", 462 | "metadata": {}, 463 | "outputs": [ 464 | { 465 | "data": { 466 | "text/plain": [ 467 | "\"selected activites = ['A', 'C', 'D', 'F']\"" 468 | ] 469 | }, 470 | "execution_count": 25, 471 | "metadata": {}, 472 | "output_type": "execute_result" 473 | } 474 | ], 475 | "source": [ 476 | "# class for activity[name,start time,end time]\n", 477 | "class Activity():\n", 478 | " def __init__(self,name,start=0,end=0):\n", 479 | " self.name=name\n", 480 | " self.start=start\n", 481 | " self.end=end\n", 482 | "A,B,C=Activity('A',9,11),Activity('B',10,11),Activity('C',11,12)\n", 483 | "D,E,F=Activity('D',12,14),Activity('E',13,15),Activity('F',15,16)\n", 484 | "all_activities=[A,B,C,D,E,F]\n", 485 | "\n", 486 | "def select_activities(activities):\n", 487 | " selected=[activities[0].name]\n", 488 | " for i in range(1,len(activities)):\n", 489 | " if activities[i].start >= activities[i-1].end:\n", 490 | " selected.append(activities[i].name)\n", 491 | " \n", 492 | " return f'selected activites = {selected}'\n", 493 | "\n", 494 | "select_activities(all_activities)" 495 | ] 496 | }, 497 | { 498 | "cell_type": "markdown", 499 | "id": "38ebca30", 500 | "metadata": {}, 501 | "source": [ 502 | "## Greedy Algorithm - Sorted Characters Frequencies" 503 | ] 504 | }, 505 | { 506 | "cell_type": "markdown", 507 | "id": "a651ae95", 508 | "metadata": {}, 509 | "source": [ 510 | "### ASCII-Characters" 511 | ] 512 | }, 513 | { 514 | "cell_type": "code", 515 | "execution_count": 26, 516 | "id": "6f93e6bf", 517 | "metadata": {}, 518 | "outputs": [ 519 | { 520 | "data": { 521 | "text/plain": [ 522 | "[['w', 1.0],\n", 523 | " ['r', 1.0],\n", 524 | " ['h', 1.0],\n", 525 | " ['e', 1.0],\n", 526 | " ['d', 1.0],\n", 527 | " [' ', 1.0],\n", 528 | " ['o', 2.0],\n", 529 | " ['l', 3.0]]" 530 | ] 531 | }, 532 | "execution_count": 26, 533 | "metadata": {}, 534 | "output_type": "execute_result" 535 | } 536 | ], 537 | "source": [ 538 | "import numpy as np\n", 539 | "def ASCIIMethod(string):\n", 540 | " # ASCII encode all english characters and numbers and special characters in 128 code starting from 0 to 127\n", 541 | " # start empty array of same size\n", 542 | " char_freq=np.zeros(127)\n", 543 | " for i in string:\n", 544 | " current_code=ord(i) # covert the character to its code in ASCII\n", 545 | " char_freq[current_code]+=1 # increase its value in the freq array\n", 546 | " frequency={} \n", 547 | " for j in range(len(char_freq)):\n", 548 | " if char_freq[j]>0:\n", 549 | " frequency[chr(j)]=char_freq[j]\n", 550 | " frequency_list=[[i,j] for i , j in frequency.items()]\n", 551 | " \n", 552 | " def merge_sort(array):\n", 553 | " if len(array) > 1:\n", 554 | " midpoint=len(array)//2\n", 555 | " left_array=array[:midpoint]\n", 556 | " right_array=array[midpoint:]\n", 557 | " merge_sort(left_array)\n", 558 | " merge_sort(right_array)\n", 559 | " i=j=k=0\n", 560 | " while i< len(left_array) and j < len(right_array):\n", 561 | " if left_array[i][1] 1:\n", 627 | " midpoint=len(array)//2\n", 628 | " left_array=array[:midpoint]\n", 629 | " right_array=array[midpoint:]\n", 630 | " merge_sort(left_array)\n", 631 | " merge_sort(right_array)\n", 632 | " i=j=k=0\n", 633 | " while i< len(left_array) and j < len(right_array):\n", 634 | " if left_array[i][1] 1:\n", 693 | " left_node=heappop(minheap)\n", 694 | " right_node=heappop(minheap)\n", 695 | " for data in left_node[1:]:\n", 696 | " data[1]='0'+data[1]\n", 697 | " for data in right_node[1:]:\n", 698 | " data[1]='1'+data[1]\n", 699 | " heappush(minheap,[left_node[0]+right_node[0]]+left_node[1:]+right_node[1:])\n", 700 | " huffman_list = right_node[1:] + left_node[1:]\n", 701 | " return huffman_list\n", 702 | "huffman_encoding('internet')" 703 | ] 704 | }, 705 | { 706 | "cell_type": "markdown", 707 | "id": "6947bd4e", 708 | "metadata": {}, 709 | "source": [ 710 | "## Greedy Algorithm- Fractional knapsack Problem" 711 | ] 712 | }, 713 | { 714 | "cell_type": "code", 715 | "execution_count": 29, 716 | "id": "89dab80a", 717 | "metadata": {}, 718 | "outputs": [ 719 | { 720 | "data": { 721 | "text/plain": [ 722 | "[['b', 2, 9, 4.5],\n", 723 | " ['a', 1, 4, 4.0],\n", 724 | " ['d', 4, 11, 2.75],\n", 725 | " ['e', 3, 6, 2.0],\n", 726 | " ['c', 2, 2.4, 1.2]]" 727 | ] 728 | }, 729 | "execution_count": 29, 730 | "metadata": {}, 731 | "output_type": "execute_result" 732 | } 733 | ], 734 | "source": [ 735 | "names=['a','b','c','d','e','f']\n", 736 | "weights=[1,2,10,4,3,5]\n", 737 | "values=[4,9,12,11,6,5]\n", 738 | "ratios=[i/j for i,j in zip(values,weights)]\n", 739 | "data=[[a,b,c,d] for a,b,c,d in zip(names,weights,values,ratios)]\n", 740 | "data.sort(key=lambda x:x[3],reverse=True)\n", 741 | "def knapsac_fill(data,k):\n", 742 | " curent_weight=0\n", 743 | " avaliable_weight=k-curent_weight\n", 744 | " knapsack=[]\n", 745 | " while curent_weight < k:\n", 746 | " for i in data:\n", 747 | " if i[1]<= avaliable_weight:\n", 748 | " knapsack.append(i)\n", 749 | " curent_weight+=i[1]\n", 750 | " avaliable_weight-=i[1]\n", 751 | " else:\n", 752 | " i[1]=avaliable_weight\n", 753 | " i[2]=avaliable_weight * i[3]\n", 754 | " knapsack.append(i)\n", 755 | " curent_weight+=i[1]\n", 756 | " avaliable_weight-=i[1]\n", 757 | " break\n", 758 | " return knapsack\n", 759 | "\n", 760 | "knapsac_fill(data,12) " 761 | ] 762 | }, 763 | { 764 | "cell_type": "markdown", 765 | "id": "818cc1d3", 766 | "metadata": {}, 767 | "source": [ 768 | "## Dynamic Programming-Stagecoach Problem" 769 | ] 770 | }, 771 | { 772 | "cell_type": "code", 773 | "execution_count": 30, 774 | "id": "a781bfa5", 775 | "metadata": {}, 776 | "outputs": [ 777 | { 778 | "name": "stdout", 779 | "output_type": "stream", 780 | "text": [ 781 | "optimum route is: ['A', 'C', 'E', 'H', 'J']\n", 782 | "cost : 11\n" 783 | ] 784 | } 785 | ], 786 | "source": [ 787 | "labels=list(map(chr,range(ord('A'),ord('J')+1)))\n", 788 | "A=[['B','C','D'],[2,4,3]]\n", 789 | "B=[['E','F','G'],[7,4,6]]\n", 790 | "C=[['E','F','G'],[3,2,4]]\n", 791 | "D=[['E','F','G'],[4,1,5]]\n", 792 | "E=[['H','I'],[1,4]]\n", 793 | "F=[['H','I'],[6,3]]\n", 794 | "G=[['H','I'],[3,3]]\n", 795 | "H=[['J'],[3]] \n", 796 | "I=[['J'],[4]] \n", 797 | "all_routes=[\n", 798 | " [0,A[1][0],A[1][1],A[1][2],0,0,0,0,0,0],\n", 799 | " [0,0,0,0,B[1][0],B[1][1],B[1][2],0,0,0],\n", 800 | " [0,0,0,0,C[1][0],C[1][1],C[1][2],0,0,0],\n", 801 | " [0,0,0,0,D[1][0],D[1][1],D[1][2],0,0,0],\n", 802 | " [0,0,0,0,0,0,0,E[1][0],E[1][1],0],\n", 803 | " [0,0,0,0,0,0,0,F[1][0],F[1][1],0],\n", 804 | " [0,0,0,0,0,0,0,G[1][0],G[1][1],0],\n", 805 | " [0,0,0,0,0,0,0,0,0,H[1][0]],\n", 806 | " [0,0,0,0,0,0,0,0,0,I[1][0]],\n", 807 | " [0,0,0,0,0,0,0,0,0,0]]\n", 808 | "def find_min_route(routes):\n", 809 | " \n", 810 | " minimum_route=routes[-1]\n", 811 | " minimum_route[-1]={'from':'','to':'','cost':0}\n", 812 | " max_num=float('inf')\n", 813 | " for i in range(len(routes)-2,-1,-1):\n", 814 | " minimum_route[i]={'from':labels[i],'to':labels[i+1],'cost':max_num}\n", 815 | " for j in range(i+1,len(routes)):\n", 816 | " if routes[i][j]==0:\n", 817 | " continue\n", 818 | " newcost=routes[i][j]+minimum_route[j]['cost']\n", 819 | " if newcost< minimum_route[i]['cost']:\n", 820 | " minimum_route[i]['to']=labels[j]\n", 821 | " minimum_route[i]['cost']=newcost\n", 822 | " \n", 823 | " optimum_route=['A']\n", 824 | " for i in minimum_route:\n", 825 | " if i['from']=='A':\n", 826 | " optimum_route.append(i['to'])\n", 827 | " x=i['to']\n", 828 | " else:\n", 829 | " if i['from']==x:\n", 830 | " optimum_route.append(i['to'])\n", 831 | " x=i['to']\n", 832 | " print(f'optimum route is: {optimum_route}')\n", 833 | " print('cost : ',minimum_route[0]['cost'])\n", 834 | " \n", 835 | " \n", 836 | "find_min_route(all_routes)" 837 | ] 838 | }, 839 | { 840 | "cell_type": "markdown", 841 | "id": "a75ce721", 842 | "metadata": {}, 843 | "source": [ 844 | "## Dynamic Programming-Longest Common Subsequence Problem" 845 | ] 846 | }, 847 | { 848 | "cell_type": "code", 849 | "execution_count": 31, 850 | "id": "b5535134", 851 | "metadata": {}, 852 | "outputs": [ 853 | { 854 | "name": "stdout", 855 | "output_type": "stream", 856 | "text": [ 857 | "[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", 858 | " [0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1.]\n", 859 | " [0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n", 860 | " [0. 1. 2. 2. 2. 2. 2. 2. 2. 2. 2.]\n", 861 | " [0. 1. 2. 3. 3. 3. 3. 3. 3. 3. 3.]\n", 862 | " [0. 1. 2. 3. 3. 4. 4. 4. 4. 4. 4.]\n", 863 | " [0. 1. 2. 3. 3. 4. 4. 4. 4. 4. 5.]]\n", 864 | "longest common subsequent string is : helod\n" 865 | ] 866 | } 867 | ], 868 | "source": [ 869 | "import numpy as np\n", 870 | "def Longest_common_subsequence(string1,string2):\n", 871 | " table=np.zeros((len(string2)+1,len(string1)+1))\n", 872 | " for i in range(1,len(string2)+1):\n", 873 | " for j in range(1,len(string1)+1):\n", 874 | " if string2[i-1]!=string1[j-1]:\n", 875 | " table[i,j]=max(table[i-1,j],table[i,j-1])\n", 876 | " else:\n", 877 | " table[i,j]=1+table[i-1,j-1]\n", 878 | " print(table)\n", 879 | " i=len(string2)\n", 880 | " j=len(string1)\n", 881 | " long_string=''\n", 882 | " while i > 0 and j > 0:\n", 883 | " if table[i,j]>table[i,j-1]:\n", 884 | " if table[i,j]==table[i-1,j]:\n", 885 | " i-=1\n", 886 | " else:\n", 887 | " long_string=string2[i-1]+long_string\n", 888 | " i-=1\n", 889 | " j-=1\n", 890 | " else:\n", 891 | " j-=1\n", 892 | " print('longest common subsequent string is : ',long_string)\n", 893 | " \n", 894 | "Longest_common_subsequence('helloworld','ohelod')" 895 | ] 896 | }, 897 | { 898 | "cell_type": "markdown", 899 | "id": "c0461da0", 900 | "metadata": {}, 901 | "source": [ 902 | "## Dynamic Programming-0/1 Knapsack Problem" 903 | ] 904 | }, 905 | { 906 | "cell_type": "code", 907 | "execution_count": 32, 908 | "id": "a2526e32", 909 | "metadata": {}, 910 | "outputs": [ 911 | { 912 | "name": "stdout", 913 | "output_type": "stream", 914 | "text": [ 915 | " item weight profit\n", 916 | "0 A 1 4\n", 917 | "1 B 3 9\n", 918 | "2 C 5 12\n", 919 | "3 D 4 11\n", 920 | "[[ 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", 921 | " [ 0. 4. 4. 4. 4. 4. 4. 4. 4.]\n", 922 | " [ 0. 4. 4. 9. 13. 13. 13. 13. 13.]\n", 923 | " [ 0. 4. 4. 9. 13. 13. 16. 16. 21.]\n", 924 | " [ 0. 4. 4. 9. 13. 15. 16. 20. 24.]]\n", 925 | "items selected: ['D', 'B', 'A']\n" 926 | ] 927 | } 928 | ], 929 | "source": [ 930 | "import numpy as np\n", 931 | "import pandas as pd\n", 932 | "weights=np.array([1,3,5,4])\n", 933 | "profits=np.array([4,9,12,11])\n", 934 | "items=['A','B','C','D']\n", 935 | "data1=pd.DataFrame([items,weights,profits],index=['item','weight','profit'])\n", 936 | "data1=data1.T\n", 937 | "print(data1)\n", 938 | "def knapsac_all_or_none(data,capacity):\n", 939 | " table=np.zeros((len(data)+1,capacity+1))\n", 940 | " for i in range(len(data)):\n", 941 | " for j in range(1,capacity+1):\n", 942 | " if data['weight'][i]<= j:\n", 943 | " table[i+1,j]=max(table[i,j],(data['profit'][i]+table[i,j-data['weight'][i]]))\n", 944 | " else:\n", 945 | " table[i+1,j]=table[i,j]\n", 946 | " print(table)\n", 947 | " i=len(data)-1\n", 948 | " j=capacity\n", 949 | " remain=capacity\n", 950 | " soln=[]\n", 951 | " while remain > 0 :\n", 952 | " if table[i+1,j]>table[i][j]:\n", 953 | " soln.append(data['item'][i])\n", 954 | " remain=remain-data['weight'][i]\n", 955 | " i-=1\n", 956 | " j=remain\n", 957 | " else:\n", 958 | " i-=1\n", 959 | " print(f'items selected: {soln}')\n", 960 | "knapsac_all_or_none(data1,8)" 961 | ] 962 | }, 963 | { 964 | "cell_type": "markdown", 965 | "id": "eebbd6cb", 966 | "metadata": {}, 967 | "source": [ 968 | "## Graph-Prim's Minimum Spanning Tree Algorithm\n", 969 | "\n", 970 | "\n" 971 | ] 972 | }, 973 | { 974 | "cell_type": "code", 975 | "execution_count": 33, 976 | "id": "98c48241", 977 | "metadata": {}, 978 | "outputs": [ 979 | { 980 | "name": "stdout", 981 | "output_type": "stream", 982 | "text": [ 983 | " 1 2 3 4 5 6\n", 984 | "1 0.0 6.7 5.2 2.8 5.6 3.6\n", 985 | "2 6.7 0.0 5.7 7.3 5.1 3.2\n", 986 | "3 5.2 5.7 0.0 3.4 8.5 4.0\n", 987 | "4 2.8 7.3 3.4 0.0 8.0 4.4\n", 988 | "5 5.6 5.1 8.5 8.0 0.0 5.6\n", 989 | "6 3.6 3.2 4.0 4.4 4.6 0.0\n", 990 | "========================\n", 991 | "1 - 4 : 2.8\n", 992 | "4 - 3 : 3.4\n", 993 | "1 - 6 : 3.6\n", 994 | "6 - 2 : 3.2\n", 995 | "6 - 5 : 4.6\n" 996 | ] 997 | } 998 | ], 999 | "source": [ 1000 | "import numpy as np\n", 1001 | "labels=np.arange(1,7)\n", 1002 | "tree=[[0,6.7,5.2,2.8,5.6,3.6],\n", 1003 | " [6.7,0,5.7,7.3,5.1,3.2],\n", 1004 | " [5.2,5.7,0,3.4,8.5,4],\n", 1005 | " [2.8,7.3,3.4,0,8,4.4],\n", 1006 | " [5.6,5.1,8.5,8,0,5.6],\n", 1007 | " [3.6,3.2,4,4.4,4.6,0]]\n", 1008 | "tree=pd.DataFrame(tree,columns=labels,index=labels)\n", 1009 | "print(tree)\n", 1010 | "print('========================')\n", 1011 | "def min_spanning_tree(graph):\n", 1012 | " selected_nodes=np.zeros(6)\n", 1013 | " selected_nodes[0]=1\n", 1014 | " edges=0\n", 1015 | " while edges < len(graph)-1:\n", 1016 | " minimum=float('inf')\n", 1017 | " from_node=0\n", 1018 | " to_node=0\n", 1019 | " for i in range(len(graph)):\n", 1020 | " if selected_nodes[i]==1:\n", 1021 | " for j in range(len(graph)):\n", 1022 | " if selected_nodes[j]==0 and graph.iloc[i,j]:\n", 1023 | " if minimum > graph.iloc[i,j]:\n", 1024 | " minimum=graph.iloc[i,j]\n", 1025 | " from_node=i\n", 1026 | " to_node=j\n", 1027 | " print(from_node+1,'-',to_node+1,':',minimum)\n", 1028 | " selected_nodes[to_node]=1\n", 1029 | " edges+=1\n", 1030 | " \n", 1031 | "min_spanning_tree(tree)" 1032 | ] 1033 | }, 1034 | { 1035 | "cell_type": "markdown", 1036 | "id": "3fd7fc58", 1037 | "metadata": {}, 1038 | "source": [ 1039 | "## Graph-Breadth First Search Algorithm" 1040 | ] 1041 | }, 1042 | { 1043 | "cell_type": "code", 1044 | "execution_count": 61, 1045 | "id": "1013ee12", 1046 | "metadata": {}, 1047 | "outputs": [ 1048 | { 1049 | "name": "stdout", 1050 | "output_type": "stream", 1051 | "text": [ 1052 | "A - B\n", 1053 | "A - C\n", 1054 | "B - D\n", 1055 | "B - E\n", 1056 | "C - F\n", 1057 | "F - H\n", 1058 | "H - G\n", 1059 | "H - I\n" 1060 | ] 1061 | } 1062 | ], 1063 | "source": [ 1064 | "from queue import Queue\n", 1065 | "table={'A':['B','C'],\n", 1066 | " 'B':['A','D','E'],\n", 1067 | " 'C':['A','D','F'],\n", 1068 | " 'D':['B','C','F'],\n", 1069 | " 'E':['B','F'],\n", 1070 | " 'F':['C','D','E','H'],\n", 1071 | " 'H':['F','G','I'],\n", 1072 | " 'G':['H','I'],\n", 1073 | " 'I':['G','H']}\n", 1074 | "def Breadth_First_search(graph):\n", 1075 | " queue=Queue()\n", 1076 | " visited=['A']\n", 1077 | " queue.put('A')\n", 1078 | " while queue.qsize() > 0 :\n", 1079 | " current_vetex=queue.get()\n", 1080 | " destintions=graph[current_vetex]\n", 1081 | " for i in range(len(destintions)):\n", 1082 | " if destintions[i] not in visited:\n", 1083 | " queue.put(destintions[i])\n", 1084 | " visited.append(destintions[i])\n", 1085 | " print(f'{current_vetex} - {destintions[i]}')\n", 1086 | "Breadth_First_search(table)" 1087 | ] 1088 | }, 1089 | { 1090 | "cell_type": "markdown", 1091 | "id": "5edb51a3", 1092 | "metadata": {}, 1093 | "source": [ 1094 | "## Graph-Depth First Search Algorithm" 1095 | ] 1096 | }, 1097 | { 1098 | "cell_type": "code", 1099 | "execution_count": 63, 1100 | "id": "cddfea35", 1101 | "metadata": {}, 1102 | "outputs": [ 1103 | { 1104 | "name": "stdout", 1105 | "output_type": "stream", 1106 | "text": [ 1107 | "A-B\n", 1108 | "B-D\n", 1109 | "D-C\n", 1110 | "C-F\n", 1111 | "F-E\n", 1112 | "F-H\n", 1113 | "H-G\n", 1114 | "G-I\n" 1115 | ] 1116 | } 1117 | ], 1118 | "source": [ 1119 | "class vertex:\n", 1120 | " def __init__(self,name,neighbors=None,visited=False):\n", 1121 | " self.name=name\n", 1122 | " self.neighbors=neighbors\n", 1123 | " self.visited=visited\n", 1124 | " \n", 1125 | "A,B,C,D,E=vertex('A'),vertex('B'),vertex('C'),vertex('D'),vertex('E'),\n", 1126 | "F,H,G,I,J=vertex('F'),vertex('H'),vertex('G'),vertex('I'),vertex('J')\n", 1127 | "A.neighbors=[B,C] \n", 1128 | "B.neighbors=[A,D,E]\n", 1129 | "C.neighbors=[A,D,F]\n", 1130 | "D.neighbors=[B,C,F]\n", 1131 | "E.neighbors=[B,F]\n", 1132 | "F.neighbors=[C,D,E,H]\n", 1133 | "H.neighbors=[F,G,I]\n", 1134 | "G.neighbors=[H,I]\n", 1135 | "I.neighbors=[G,H]\n", 1136 | "graph=[A,B,C,D,E,F,G,H,I,J]\n", 1137 | "\n", 1138 | "def Depth_First_search(vertex):\n", 1139 | " if not vertex.visited:\n", 1140 | " vertex.visited=True\n", 1141 | " for neighbor in vertex.neighbors:\n", 1142 | " if not neighbor.visited:\n", 1143 | " print(f'{vertex.name}-{neighbor.name}')\n", 1144 | " Depth_First_search(neighbor)\n", 1145 | "Depth_First_search(graph[0])\n" 1146 | ] 1147 | }, 1148 | { 1149 | "cell_type": "markdown", 1150 | "id": "72b0b08e", 1151 | "metadata": {}, 1152 | "source": [ 1153 | "## Graph-Dijkstra's Shortest Path Algorithm" 1154 | ] 1155 | }, 1156 | { 1157 | "cell_type": "code", 1158 | "execution_count": 64, 1159 | "id": "c6eea9dd", 1160 | "metadata": {}, 1161 | "outputs": [ 1162 | { 1163 | "name": "stdout", 1164 | "output_type": "stream", 1165 | "text": [ 1166 | "[None-A-0]\n", 1167 | "[A-B-2]\n", 1168 | "[A-C-4]\n", 1169 | "[A-D-3]\n", 1170 | "[C-E-3]\n", 1171 | "[D-F-1]\n", 1172 | "[C-G-4]\n", 1173 | "[E-H-1]\n", 1174 | "[F-I-3]\n", 1175 | "[H-J-3]\n", 1176 | "============================\n", 1177 | "shortest-route is [ A-C-E-H-J ] cost= 11\n" 1178 | ] 1179 | } 1180 | ], 1181 | "source": [ 1182 | "class vertex:\n", 1183 | " def __init__(self,name,neighbors=None,best_source=None,source_length=float('inf'),total_length=0):\n", 1184 | " self.name=name\n", 1185 | " self.neighbors=neighbors\n", 1186 | " self.best_source=best_source\n", 1187 | " self.source_length=source_length\n", 1188 | " self.total_length=total_length\n", 1189 | " \n", 1190 | "A,B,C,D,E=vertex('A'),vertex('B'),vertex('C'),vertex('D'),vertex('E'),\n", 1191 | "F,H,G,I,J=vertex('F'),vertex('H'),vertex('G'),vertex('I'),vertex('J')\n", 1192 | "A.neighbors=[[B,C,D],[2,4,3]]\n", 1193 | "B.neighbors=[[E,F,G],[7,4,6]]\n", 1194 | "C.neighbors=[[E,F,G],[3,2,4]]\n", 1195 | "D.neighbors=[[E,F,G],[4,1,5]]\n", 1196 | "E.neighbors=[[H,I],[1,4]]\n", 1197 | "F.neighbors=[[H,I],[6,3]]\n", 1198 | "G.neighbors=[[H,I],[3,3]]\n", 1199 | "H.neighbors=[[J],[3]]\n", 1200 | "I.neighbors=[[J],[4]]\n", 1201 | "J.neighbors=[[],[]]\n", 1202 | "A.source_length=0\n", 1203 | "graph=[A,B,C,D,E,F,G,H,I,J]\n", 1204 | "\n", 1205 | "def Dijkstras_Shortest_Path(graph):\n", 1206 | " for i in graph:\n", 1207 | " for j in graph:\n", 1208 | " if i in j.neighbors[0]:\n", 1209 | " if j.neighbors[1][j.neighbors[0].index(i)]