rishiilluri

Untitled

Oct 10th, 2022
930
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. #!/usr/local/bin/python3
  2. # solve_birds.py : Bird puzzle solver
  3. #
  4. # Code by: name IU ID
  5. #
  6. # Based on skeleton code by D. Crandall & B551 course staff, Fall 2022
  7. #
  8. # N birds stand in a row on a wire, each wearing a t-shirt with a number.
  9. # In a single step, two adjacent birds can swap places. How can
  10. # they rearrange themselves to be in order from 1 to N in the fewest
  11. # possible steps?
  12.  
  13. # !/usr/bin/env python3
  14. import sys
  15. from queue import PriorityQueue
  16.  
  17. N=5
  18.  
  19. #####
  20. # THE ABSTRACTION:
  21. #
  22. # Initial state:
  23.  
  24. # Goal state:
  25. # given a state, returns True or False to indicate if it is the goal state
  26. def is_goal(state):
  27.     return state == list(range(1, N+1))
  28.  
  29. # Successor function:
  30. # given a state, return a list of successor states
  31. def successors(state):
  32.     return [ state[0:n] + [state[n+1],] + [state[n],] + state[n+2:] for n in range(0, N-1) ]
  33.  
  34. # Heuristic function:
  35. # given a state, return an estimate of the number of steps to a goal from that state
  36. def h(state):
  37.     distance = 0
  38.     for i in range(N):
  39.         distance += abs(state[i]-i-1)
  40.     return distance
  41.  
  42. #########
  43. #
  44. # THE ALGORITHM:
  45. #
  46. # This is a generic solver using BFS.
  47. #
  48. def solve(initial_state):
  49.     fringe = PriorityQueue()
  50.     fringe.put((0, initial_state, [],))
  51.     while not fringe.empty():
  52.         (priority, state, path) = fringe.get()
  53.        
  54.         if is_goal(state):
  55.             return path+[state,]
  56.  
  57.         for s in successors(state):
  58.             fringe.put((len(path)+1+h(state), s, path+[state,]))
  59.  
  60.     return []
  61.  
  62. # Please don't modify anything below this line
  63. #
  64. if __name__ == "__main__":
  65.     if(len(sys.argv) != 2):
  66.         raise(Exception("Error: expected a test case filename"))
  67.  
  68.     test_cases = []
  69.     with open(sys.argv[1], 'r') as file:
  70.         for line in file:
  71.             test_cases.append([ int(i) for i in line.split() ])
  72.     for initial_state in test_cases:
  73.             print('From state ' + str(initial_state) + " found goal state by taking path: " + str(solve(initial_state)))
  74.  
  75.    
Advertisement
Add Comment
Please, Sign In to add comment