Pythonic Data Structures and Algorithms(Array 3)
2017-09-18 09:14
399 查看
#coding:utf-8 ''' Created on 2017-9-18 @author: 刘帅 ''' # There is a parking lot with only one empty spot. Given the initial state # of the parking lot and the final state. Each step we are only allowed to # move a car # out of its place and move it into the empty spot. # The goal is to find out the least movement needed to rearrange # the parking lot from the initial state to the final state. # Say the initial state is an array: # [1,2,3,0,4], # where 1,2,3,4 are different cars, and 0 is the empty spot. # And the final state is # [0,3,2,1,4]. # We can swap 1 with 0 in the initial array to get [0,2,3,1,4] and so on. # Each step swap with 0 only. def garage(initial, final): steps = 0 while initial != final: zero = initial.index(0) if zero != final.index(0): car_to_move = final[zero] pos = initial.index(car_to_move) print pos initial[zero], initial[pos] = initial[pos], initial[zero] else: for i in range(len(initial)): if initial[i] != final[i]: initial[zero], initial[i] = initial[i], initial[zero] break steps += 1 return steps if __name__ == "__main__": initial = [1, 2, 3, 0, 4] final = [0, 3, 2, 1, 4] print("initial:", initial) print("final:", final) print(garage(initial, final))
相关文章推荐
- Pythonic Data Structures and Algorithms(Array 2)
- Pythonic Data Structures and Algorithms(Array 4)
- Pythonic Data Structures and Algorithms(Array 1)
- 基于Problem Solving with Algorithms and Data Structures using Python的学习记录(5)——Sorting
- Problem Solving with algorithms and data structures using Python 翻译计划
- 下载电子书Problem Solving with Algorithms and Data Structures using Python
- Data Structures and Algorithms in Python:Python中的数据结构和算法
- 剪短的python数据结构和算法的书《Data Structures and Algorithms Using Python》
- Python数据结构与算法分析学习记录(1)——基于Problem Solving with Algorithms and Data Structures using Python的学习
- 基于Problem Solving with Algorithms and Data Structures using Python的学习记录(6-1)——Tree
- 基于Problem Solving with Algorithms and Data Structures using Python的学习记录(3)——Basic Data Structures
- Python数据结构与算法分析学习记录(2)——基于Problem Solving with Algorithms and Data Structures using Python的学习
- Data Structures And Algorithms With Object-Oriented+Design+Patterns in C#
- 数据结构与算法的学习问题——The Data Structures and Algorithms Learning Problem
- Data Structures and Algorithms
- Data Structures and Algorithms with Object-Oriented Design Patterns (5)
- Basic Data Structures and Algorithms in the Linux Kernel--reference
- Data Structures and Algorithms with Object-Oriented Design Patterns (3)
- 数据结构与算法 Data Structures and Algorithms(作业1)
- Data Structures and Algorithms in Java