简体   繁体   中英

Is there a way to iterate through a list in a specific order of indexes in python

Okay so it has been a long time since I've worked in python. But basically I am doing the classic 8-puzzle problem so given a string such as "12-453786" my program solves it for the desired "12345678-". I am using breadth-first search to solve it currently and am storing visited nodes and the node the came from in the below example. However to trace the path or the amount of moves it actually takes to complete the puzzle I need to be able to start at the solved tuple and trace my way back through my list of tuples to the start state

I was considering doing some sort of while solved.= startstate loop but that wont exactly work.

 def breadth_first_search(puz):
    qu = queue.Queue()
    laststate=""
    qu.put((puz, laststate))
    startstate=puz
    visited=[]
    #visited[puz] = puz

    while queue: 

        puz = qu.get()
        visited.append(puz)

        pos = puz[0].index('-')
        nebs = neighborcells(pos)
        #print(*visited)
        if puz[0] == "12345678-":

            break
        else:
            for i in nebs:

                swapped=swap(puz,i,pos)
                if swapped in visited:
                    pass #?
                else:
                    qu.put((swapped, puz[0]))
     #some sort of linked list like function to get the path of result to start
     #here

EXAMPLE OF VISITED NODES (list of tuples)

[('12-453786', ''), 
 ('1-2453786', '12-453786'), 
 ('12345-786', '12-453786'), 
 ('-12453786', '1-2453786'), 
 ('12-453786', '1-2453786'), 
 ('1524-3786', '1-2453786'), 
 ('1234-5786', '12345-786'), 
 ('12345678-', '12345-786')]

The expected result for this particular puzzle should be 2 moves

Using your current data structure (array of (nextState, prevState) tuples) you can definitely work your way back to the start state, but it would not be very efficient since you have to scan the whole list every time to find the state you're looking for. Instead you could use a simple data structure for storing your BFS graph. That way when you reach the end state, you can just follow the back links to the initial state.

Also in your current code, you're not guarding against states you have visited before, so you could get into infinite loop situations and your while loop will never break.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM