Advertisement
Hend_Sayed

Untitled

May 12th, 2024
644
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.08 KB | None | 0 0
  1. #AI ALGORISMS
  2.  
  3. #1-BFS
  4.  
  5. #declaring the graph as a dictionary
  6. graph = {
  7.   'S' : [ 'A','B','D'],
  8.   'A' : ['C'],
  9.   'B' : ['D'],
  10.   'C' : ['D','G'],
  11.   'D' : ['G'],
  12.   'G' : []
  13. }
  14. def bfs(graph, start, goal):
  15.     #create a list to store the visited nodes and a queue to store the nodes
  16.     visited = []
  17.     queue = [[start]]
  18.    
  19.     #loop through the queue if it's not empty
  20.     while queue:
  21.         path = queue.pop(0) #remove from the left
  22.         node = path[-1]
  23.  
  24.         if node == visited:
  25.             continue
  26.         visited.append(node)
  27.         if node == goal:
  28.             return path
  29.         else:
  30.             adjacent_nodes = graph.get(node, [])
  31.             for adjacent_node in adjacent_nodes:
  32.                 new_path = path.copy()
  33.                 new_path.append(adjacent_node)
  34.                 queue.append(new_path)
  35.     return print("The queue is empty, no solution found.")
  36.  
  37. solution = bfs(graph,'S','G')
  38. print('Solution is ' , solution)
  39.  
  40.  
  41. #2-DFS
  42.  
  43. #declaring the graph as a dictionary
  44. graph = {
  45.   'S' : [ 'A','B','D'],
  46.   'A' : ['C'],
  47.   'B' : ['D'],
  48.   'C' : ['D','G'],
  49.   'D' : ['G'],
  50.   'G' : []
  51. }
  52. def dfs(graph, start, goal):
  53.     #create a list to store the visited nodes and a stack to store the nodes
  54.     visited = []
  55.     stack = [[start]]
  56.    
  57.     #loop through the stack if it's not empty
  58.     while stack:
  59.         path = stack.pop() #remove from the right
  60.         node = path[-1]
  61.  
  62.         if node == visited:
  63.             continue
  64.         visited.append(node)
  65.         if node == goal:
  66.             return path
  67.         else:
  68.             adjacent_nodes = graph.get(node, [])
  69.             for adjacent_node in adjacent_nodes:
  70.                 new_path = path.copy()
  71.                 new_path.append(adjacent_node)
  72.                 stack.append(new_path)
  73.     return print("The stack is empty, no path found.")
  74.  
  75. solution = dfs(graph,'S','G')
  76. print('Solution is ' , solution)
  77.  
  78.  
  79. #3-AlphaBeta
  80. import math
  81.  
  82. def alpha_beta_minimax(cd, node, alpha, beta, maxt, scr, td):
  83.     if cd == td:
  84.         return scr[node]
  85.     if maxt:
  86.         v = -math.inf
  87.         for child in [node*2, node*2+1]:
  88.             v = max(v, alpha_beta_minimax(cd+1, child, alpha, beta, False, scr, td))
  89.             alpha = max(alpha, v)
  90.             if alpha >= beta:
  91.                 break
  92.         return v
  93.     else:
  94.         v = math.inf
  95.         for child in [node*2, node*2+1]:
  96.             v = min(v, alpha_beta_minimax(cd+1, child, alpha, beta, True, scr, td))
  97.             beta = min(beta, v)
  98.             if alpha >= beta:
  99.                 break
  100.         return v
  101.  
  102. scr = []
  103. x = int(input('Enter Total Number of leaf nodes: '))
  104. for i in range(x):
  105.     y = int(input('Enter leaf value: '))
  106.     scr.append(y)
  107.  
  108. td = math.log(len(scr), 2)
  109. cd = int(input('Enter current depth value: '))
  110. nodev = int(input('Enter node value: '))
  111. alpha = -math.inf
  112. beta = math.inf
  113. maxt = True
  114.  
  115.  
  116. answer = alpha_beta_minimax(cd, nodev, alpha, beta, maxt, scr, td)
  117. print('The answer is: ',answer)
  118.  
  119. #4-GBS
  120.  
  121. #NOTE that Gready_best_search depends on H_cost only
  122. graph={
  123.     'S':[('A',1),('B',4)],
  124.     'A':[('B',2),('C',5),('G',12)],
  125.     'B':[('C',2)],
  126.     'C':[('G',3)]
  127. }
  128. # The hurestic of each node
  129. H_table={
  130.     'S':7,
  131.     'A':6,
  132.     'B':4,
  133.     'C':2,
  134.     'G':0
  135. }
  136. #To calculate the H_cost of any path
  137. def path_h_cost(path):
  138.     for (node,cost) in path:
  139.        last_node = path[-1][0] #C
  140.        h_cost = H_table[last_node] #2
  141.     return h_cost , last_node    
  142.  
  143. #to check the path_h_cost function
  144. # path=[('S', 0), ('A', 1), ('C', 5)]
  145. # print(path_f_cost (path))
  146. #SOLUTION = (2 , C)
  147.  
  148. def gready_best_search(graph, start, goal):
  149.  
  150.     visited=[]
  151.     queue=[[(start,0)]]
  152.  
  153.     while queue:
  154.  
  155.         queue.sort(key=path_h_cost) #sorting by least f-cost
  156.         path = queue.pop(0) #pop from left
  157.         node = path[-1][0]
  158.         if node in visited:
  159.             continue
  160.         visited.append(node)
  161.         if node == goal:
  162.              return path
  163.         else:
  164.             adjacent_nodes = graph.get(node,[])                            
  165.             for (adjacent_node,cost) in adjacent_nodes:
  166.                 new_path =path.copy()
  167.                 new_path.append((adjacent_node, cost))
  168.                 queue.append(new_path)
  169.  
  170.  
  171. solution= gready_best_search(graph, 'S', 'G')
  172. print('Solution is : ', solution)
  173. solution_path = [node for (node,_) in solution] #_ to ignore the cost of nodes
  174. print('The path of Solution : ', solution_path)
  175. print('H_cost of solution is', path_h_cost(solution)[0])
  176.  
  177. #5-A*
  178. #NOTE that a* depends on F_cost = G_cost + H_cost
  179.  
  180. graph={
  181.     'S':[('A',1),('B',4)],
  182.     'A':[('B',2),('C',5),('G',12)],
  183.     'B':[('C',2)],
  184.     'C':[('G',3)]
  185. }
  186. # The hurestic of each node
  187. H_table={
  188.     'S':7,
  189.     'A':6,
  190.     'B':4,
  191.     'C':2,
  192.     'G':0
  193. }
  194.  
  195. #To calculate the F_cost of any path
  196. def path_f_cost(path):
  197.     g_cost= 0
  198.     for (node,cost) in path:
  199.         g_cost += cost
  200.     last_node = path[-1][0] #C
  201.     h_cost = H_table[last_node] #2
  202.     f_cost = g_cost + h_cost
  203.     return f_cost , last_node    
  204.  
  205. #to check the path_f_cost function
  206. # path=[('S', 0), ('A', 1), ('C', 5)]
  207. # print(path_f_cost (path))
  208. #SOLUTION = (8 , C)
  209.  
  210. def a_star_search(graph, start, goal):
  211.  
  212.     visited=[]
  213.     queue=[[(start,0)]]
  214.  
  215.     while queue:
  216.  
  217.         queue.sort(key=path_f_cost) #sorting by least f-cost
  218.         path = queue.pop(0) #pop from left
  219.         node = path[-1][0]
  220.         if node in visited:
  221.             continue
  222.         visited.append(node)
  223.         if node == goal:
  224.              return path
  225.         else:
  226.             adjacent_nodes = graph.get(node,[])                            
  227.             for (adjacent_node,cost) in adjacent_nodes:
  228.                 new_path =path.copy()
  229.                 new_path.append((adjacent_node, cost))
  230.                 queue.append(new_path)
  231.  
  232.  
  233. solution= a_star_search(graph, 'S', 'G')
  234. print('Solution is : ', solution)
  235. solution_path = [node for (node,_) in solution] #_ to ignore the cost of nodes
  236. print('The path of Solution : ', solution_path)
  237. print('F_cost of solution is', path_f_cost(solution)[0])
  238.  
  239. #6-UCS
  240.  
  241. #NOTE that Uniform_cost_search depends on G_cost of path
  242.  
  243. #create a function to calculate path_cost
  244. def path_cost(path):
  245.     total_cost = 0
  246.     for (node , cost) in path:
  247.         total_cost += cost
  248.     return total_cost , path[-1][0]
  249.  
  250. #declaring the graph as a dictionary with it's cost
  251. graph = {
  252.   'S' : [ ('A',2),('B',3),('D',5)],
  253.   'A' : [('C',4)],
  254.   'B' : [('D',4)],
  255.   'C' : [('D',1),('G',2)],
  256.   'D' : [('G',5)],
  257.   'G' : []
  258. }
  259. def ucs(graph, start, goal):
  260.     #create a list to store the visited nodes and a queue to store the nodes
  261.     visited = []
  262.     queue = [[(start,0)]]
  263.    
  264.     #loop through the queue if it's not empty
  265.     while queue:
  266.         queue.sort(key=path_cost) #sorting by lowest path_cost
  267.         path = queue.pop(0)
  268.         node = path[-1][0]
  269.  
  270.         if node in visited:
  271.             continue
  272.         visited.append(node)
  273.         if node == goal:
  274.             return path
  275.         else:
  276.             adjacent_nodes = graph.get(node, [])
  277.             for (adjacent_node,cost) in adjacent_nodes:
  278.                 new_path = path.copy()
  279.                 new_path.append((adjacent_node,cost))
  280.                 queue.append(new_path)
  281.     return print("The queue is empty, no solution found.")
  282.  
  283. solution = ucs(graph,'S','G')
  284. print('Solution is ' , solution)
  285. print('Cost of solution is ' , path_cost(solution)[0])
  286.  
  287. #7-MinMax
  288.  
  289. import math
  290. def Minmax(cd,node,maxt,scr,td):
  291.     if(cd==td):
  292.         return scr[node]
  293.     if(maxt):
  294.         return max(Minmax(cd+1,node*2,False,scr,td),Minmax(cd+1,node*2+1,False,scr,td))
  295.     else:
  296.         return min(Minmax(cd+1,node*2,True,scr,td),Minmax(cd+1,node*2+1,True,scr,td))
  297.    
  298.    
  299. scr=[]
  300. x=int(input('Enter Total Nymber of leaf node= '))
  301. for i in range (x):
  302.     y=int(input('Enter leaf value: '))
  303.     scr.append(y)
  304.  
  305.  
  306.  
  307. td=math.log(len(scr),2)
  308. cd=int(input('Enter current depth value: '))
  309. nodev=int(input('Enter node value: '))
  310. maxt=True
  311. print('The answer is : ',end=" ")
  312. answer=Minmax(cd,nodev,maxt,scr,td)
  313. print(answer)
  314.  
  315.  
  316.  
  317.  
  318.  
  319.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement