Advertisement
Guest User

Untitled

a guest
Oct 24th, 2014
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. def FrameStewartSolution(ndisks,start=1,end=4,pegs=set([1,2,3,4])):
  2.     if ndisks ==0 or start == end: #zero disks require zero moves
  3.         return []
  4.     if  ndisks == 1 and len(pegs) > 1: #if there is only 1 disk it will only take one move
  5.         return ["move(%s,%s)"%(start,end)]  
  6.     if len(pegs) == 3:#3 pegs is well defined optimal solution of 2^n-1
  7.         return towers3(ndisks,start,end,pegs)
  8.     if len(pegs) >= 3 and ndisks > 0:
  9.         best_solution = float("inf")
  10.         best_score = float("inf")
  11.         for kdisks in range(1,ndisks):
  12.             helper_pegs = list(pegs.difference([start,end]))
  13.             LHSMoves = FrameStewartSolution(kdisks,start,helper_pegs[0],pegs)
  14.             pegs_for_my_moves = pegs.difference([helper_pegs[0]]) # cant use the peg our LHS stack is sitting on
  15.             MyMoves = FrameStewartSolution(ndisks-kdisks,start,end,pegs_for_my_moves) #misleading variable name but meh
  16.             RHSMoves = FrameStewartSolution(kdisks,helper_pegs[0],end,pegs)#move the intermediat stack to
  17.             if any(move is None for move in [LHSMoves,MyMoves,RHSMoves]):continue #bad path :(
  18.             move_list = LHSMoves + MyMoves + RHSMoves
  19.             if(len(move_list) < best_score):
  20.                 best_solution = move_list
  21.                 best_score = len(move_list)
  22.         if best_score < float("inf"):      
  23.             return best_solution
  24.     #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk)
  25.     return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement