|
17 | 17 | # Each step swap with 0 only.
|
18 | 18 |
|
19 | 19 |
|
20 |
| -def garage(beg, end): |
21 |
| - moves = 0 |
| 20 | +def count_moves(beg,end): |
22 | 21 | i = 0
|
23 |
| - while beg != end : |
24 |
| - if beg[i] != end[i] and beg[i] != 0: |
25 |
| - car = beg[i] #car that we will move |
26 |
| - empty = beg.index(0) |
27 |
| - beg[beg.index(car)], beg[empty] = beg[empty], beg[beg.index(car)] |
28 |
| - moves += 1 |
29 |
| - ## move car that's not in correct place into free space |
30 |
| - print(beg) |
31 |
| - if beg.index(car) != end.index(car): |
32 |
| - # if the recently moved car is still not in its correct place |
33 |
| - # then we want to move another car into the free space where |
34 |
| - # it will be in its correct position |
35 |
| - beg[beg.index(end[i])] = 0 |
36 |
| - beg[i] = end[i] |
37 |
| - print(beg) |
38 |
| - moves += 1 |
39 |
| - i += 1 #move onto the next car, check again |
| 22 | + count = 0 |
| 23 | + while beg != end: |
| 24 | + if beg[i] != 0 and beg[i] != end[i]: |
| 25 | + current_car = beg[i] |
| 26 | + empty_slot = beg.index(0) |
| 27 | + final_pos = end.index(beg[i]) |
| 28 | + if empty_slot != final_pos: |
| 29 | + beg[final_pos], beg[empty_slot] = beg[empty_slot], beg[final_pos] |
| 30 | + print beg |
| 31 | + empty_slot = beg.index(0) |
| 32 | + beg[beg.index(current_car)], beg[empty_slot] = beg[empty_slot], beg[beg.index(current_car)] |
| 33 | + print beg |
| 34 | + count += 2 |
| 35 | + else: |
| 36 | + beg[beg.index(current_car)], beg[empty_slot] = beg[empty_slot], beg[beg.index(current_car)] |
| 37 | + print beg |
| 38 | + count += 1 |
| 39 | + i += 1 |
40 | 40 | if i == len(beg):
|
41 | 41 | i = 0
|
42 |
| - return moves |
43 |
| - |
| 42 | + return count |
| 43 | + |
| 44 | + |
44 | 45 | initial = [1,2,3,0,4]
|
45 | 46 | final = [0,3,2,1,4]
|
46 |
| -print("initial:", initial) |
47 |
| -print("final:", final) |
48 |
| -print(garage(initial, final)) |
| 47 | +print ('Initially:',initial) |
| 48 | +print ('Final',final) |
| 49 | +print count_moves(initial,final) |
0 commit comments