Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def FrameStewartSolution(ndisks,start=1,end=4,pegs=set([1,2,3,4])):
- if ndisks ==0 or start == end: #zero disks require zero moves
- return []
- if ndisks == 1 and len(pegs) > 1: #if there is only 1 disk it will only take one move
- return ["move(%s,%s)"%(start,end)]
- if len(pegs) == 3:#3 pegs is well defined optimal solution of 2^n-1
- return towers3(ndisks,start,end,pegs)
- if len(pegs) >= 3 and ndisks > 0:
- best_solution = float("inf")
- best_score = float("inf")
- for kdisks in range(1,ndisks):
- helper_pegs = list(pegs.difference([start,end]))
- LHSMoves = FrameStewartSolution(kdisks,start,helper_pegs[0],pegs)
- pegs_for_my_moves = pegs.difference([helper_pegs[0]]) # cant use the peg our LHS stack is sitting on
- MyMoves = FrameStewartSolution(ndisks-kdisks,start,end,pegs_for_my_moves) #misleading variable name but meh
- RHSMoves = FrameStewartSolution(kdisks,helper_pegs[0],end,pegs)#move the intermediat stack to
- if any(move is None for move in [LHSMoves,MyMoves,RHSMoves]):continue #bad path :(
- move_list = LHSMoves + MyMoves + RHSMoves
- if(len(move_list) < best_score):
- best_solution = move_list
- best_score = len(move_list)
- if best_score < float("inf"):
- return best_solution
- #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk)
- return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement