_Mizanur

code

Oct 26th, 2021
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.87 KB | None | 0 0
  1. 1.Tower of Hanoi
  2.  
  3. def TOH(n,A,B,C):
  4.     if n>0:
  5.         TOH(n-1,A,C,B)
  6.         print('Moved disk',n,'from',A,'to',C)
  7.         TOH(n-1,B,A,C)
  8. n=int(input("Enter How many disk:"))
  9. TOH(n,'A','B','C')
  10.  
  11. 2.kruskal
  12.  
  13. # Write a program to find the shortest path from a graph using Kruskal’s Algorithm.
  14.  
  15. from collections import defaultdict
  16. # Part of Cosmos by OpenGenus Foundation
  17. class Graph:
  18.     def __init__(self,vertices):
  19.         self.V= vertices
  20.         self.graph = []
  21.     def addEdge(self,u,v,w):
  22.         self.graph.append([u,v,w])
  23.     def find(self, parent, i):
  24.         if parent[i] == i:
  25.             return i
  26.         return self.find(parent, parent[i])
  27.     def union(self, parent, rank, x, y):
  28.         xroot = self.find(parent, x)
  29.         yroot = self.find(parent, y)
  30.         if rank[xroot] < rank[yroot]:
  31.             parent[xroot] = yroot
  32.         elif rank[xroot] > rank[yroot]:
  33.             parent[yroot] = xroot
  34.         else :
  35.             parent[yroot] = xroot
  36.             rank[xroot] += 1
  37.     def KruskalMST(self):
  38.         result =[]
  39.         i,e = 0,0
  40.         self.graph =  sorted(self.graph,key=lambda item: item[2])
  41.         parent = [] ; rank = []
  42.         for node in range(self.V):
  43.             parent.append(node)
  44.             rank.append(0)
  45.         while e < self.V -1 :
  46.             u,v,w =  self.graph[i]
  47.             i = i + 1
  48.             x = self.find(parent, u)
  49.             y = self.find(parent ,v)
  50.             if x != y:
  51.                 e = e + 1
  52.                 result.append([u,v,w])
  53.                 self.union(parent, rank, x, y)
  54.         print("Constructed MST :")
  55.         print("Vertex A    Vertex B  Weight")
  56.         for u,v,weight  in result:
  57.             print ("    %d          %d        %d" % (u,v,weight))
  58. vetx = int(input("Enter no. of vertices :"))
  59. eegde = int(input("Enter no. of edges :"))
  60. g = Graph(vetx)
  61. print("For each edge input (Source vertex , Destination vertex , Weight of the edge ) :")
  62. for x in range(eegde):
  63.     qq,xx,yy = map(int,input().split(" "))
  64.     g.addEdge(qq, xx, yy)
  65. g.KruskalMST()
  66.  
  67.  
  68.  
  69. 3.knapsack
  70.  
  71. '''
  72. Write a program to solve the following 0/1 Knapsack using dynamic programming
  73. approach profits p=(15,25,13,23),weight W=(2,6,12,9),Knapsack C=20 and number of items n=4.
  74. '''
  75.  
  76. # A Dynamic Programming based Python
  77. # Program for 0-1 Knapsack problem
  78. # Returns the maximum value that can
  79. # be put in a knapsack of capacity W
  80.  
  81. def knapSack(W, wt, val, n):
  82.     K = [[0 for x in range(W + 1)] for x in range(n + 1)]
  83.  
  84.     # Build table K[][] in bottom up manner
  85.     for i in range(n + 1):
  86.         for w in range(W + 1):
  87.             if i == 0 or w == 0:
  88.                 K[i][w] = 0
  89.             elif wt[i-1] <= w:
  90.                 K[i][w] = max(val[i-1]
  91.                         + K[i-1][w-wt[i-1]],
  92.                             K[i-1][w])
  93.             else:
  94.                 K[i][w] = K[i-1][w]
  95.  
  96.     return K[n][W]
  97.  
  98.  
  99. # Driver code
  100. wt=[]
  101. val=[]
  102. W,n=input("Enter the capacity of Knapsack and number of item:").split()
  103. W=int(W)
  104. n=int(n)
  105. print('Enter weight and their corresponding value with space:')
  106. for mn in range(0,n):
  107.     x,y=input().split()
  108.     wt.append(int(x))
  109.     val.append(int(y))
  110.  
  111. print("Output:",knapSack(W, wt, val, n))
  112.  
  113. 4.job sequence
  114.  
  115. '''Write a program using greedy method to solve this problem when no of job n=5,
  116. profits (P1,P2,P3,P4,P5) = (3,25,1,6,30) and deadlines (d1,d2,d3,d4,d5) = (1,3,2,1,2).
  117. '''
  118.  
  119. # Program to find the maximum profit
  120. # job sequence from a given array
  121. # of jobs with deadlines and profits
  122.  
  123. # function to schedule the jobs take 2
  124. # arguments array and no of jobs to schedule
  125. def printJobScheduling(arr, t):
  126.     # length of array
  127.     n = len(arr)
  128.  
  129.     # Sort all jobs according to
  130.     # decreasing order of profit
  131.     for i in range(n):
  132.         for j in range(n - 1 - i):
  133.             if arr[j][2] < arr[j + 1][2]:
  134.                 arr[j], arr[j + 1] = arr[j + 1], arr[j]
  135.  
  136.                 # To keep track of free time slots
  137.     result = [False] * t
  138.  
  139.     # To store result (Sequence of jobs)
  140.     job = ['-1'] * t
  141.  
  142.     # Iterate through all given jobs
  143.     for i in range(len(arr)):
  144.  
  145.         # Find a free slot for this job
  146.         # (Note that we start from the
  147.         # last possible slot)
  148.         for j in range(min(t - 1, arr[i][1] - 1), -1, -1):
  149.  
  150.             # Free slot found
  151.             if result[j] is False:
  152.                 result[j] = True
  153.                 job[j] = arr[i][0]
  154.                 break
  155.  
  156.     # print the sequence
  157.     print(job)
  158.  
  159.  
  160. # Driver COde
  161. arr = [['J1', 1, 3],  # Job Array
  162.        ['J2', 3, 25],
  163.        ['J3', 2, 1],
  164.        ['J4', 1, 6],
  165.        ['J5', 2, 30]]
  166.  
  167. print("Following is maximum profit sequence of jobs")
  168. printJobScheduling(arr, 3)  # Function Call
  169.  
  170.  
  171. 5.n queen
  172.  
  173. #Write a program to solve n-queen’s problem using backtracking.
  174.  
  175. #Number of queens
  176. print ("Enter the number of queens")
  177. N = int(input())
  178.  
  179. #chessboard
  180. #NxN matrix with all elements 0
  181. board = [[0 for x in range(N)]for x in range(N)]
  182.  
  183. def is_attack(i, j):
  184.     #checking if there is a queen in row or column
  185.     for k in range(0,N):
  186.         if board[i][k]==1 or board[k][j]==1:
  187.             return True
  188.     #checking diagonals
  189.     for k in range(0,N):
  190.         for l in range(0,N):
  191.             if (k+l==i+j) or (k-l==i-j):
  192.                 if board[k][l]==1:
  193.                     return True
  194.     return False
  195.  
  196. def N_queen(n):
  197.     #if n is 0, solution found
  198.     if n==0:
  199.         return True
  200.     for i in range(0,N):
  201.         for j in range(0,N):
  202.             '''checking if we can place a queen here or not
  203.            queen will not be placed if the place is being attacked
  204.            or already occupied'''
  205.             if (not(is_attack(i,j))) and (board[i][j]!=1):
  206.                 board[i][j] = 1
  207.                 #recursion
  208.                 #wether we can put the next queen with this arrangment or not
  209.                 if N_queen(n-1)==True:
  210.                     return True
  211.                 board[i][j] = 0
  212.  
  213.     return False
  214.  
  215. N_queen(N)
  216. for i in board:
  217.     print (i)
  218.  
  219. 6.merge sort
  220.  
  221. # A program to sort a linear array using merge sort algorithm.
  222. def mergeSort(arr):
  223.     if len(arr) > 1:
  224.  
  225.         # Finding the mid of the array
  226.         mid = len(arr)//2 # take floor division
  227.  
  228.         # Dividing the array elements
  229.         L = arr[:mid]
  230.  
  231.         # into 2 halves
  232.         R = arr[mid:]
  233.  
  234.         # Sorting the first half
  235.         mergeSort(L)
  236.  
  237.         # Sorting the second half
  238.         mergeSort(R)
  239.  
  240.         i = j = k = 0
  241.  
  242.         # Copy data to temp arrays L[] and R[]
  243.         while i < len(L) and j < len(R):
  244.             if L[i] < R[j]:
  245.                 arr[k] = L[i]
  246.                 i += 1
  247.             else:
  248.                 arr[k] = R[j]
  249.                 j += 1
  250.             k += 1
  251.  
  252.         # Checking if any element was left
  253.         while i < len(L):
  254.             arr[k] = L[i]
  255.             i += 1
  256.             k += 1
  257.  
  258.         while j < len(R):
  259.             arr[k] = R[j]
  260.             j += 1
  261.             k += 1
  262.     print('Merging ',arr)
  263. #Take input from user
  264. n=int(input('How many numbers:'))
  265. arr=list(map(int,input('Enter the elements:').split()[:n]))
  266. print('Before sorting the array is',arr)
  267. #call mergesort function
  268. mergeSort(arr)
  269. print('After sort the array is',arr)
  270.  
Add Comment
Please, Sign In to add comment