Python List Merge for game 2048 (part1)
来源:互联网 发布:sybase数据网站 编辑:程序博客网 时间:2024/04/28 14:28
<pre name="code" class="python">def merge(line): """ Function that merges a single row or column in 2048. """ resultlist=[] for item in range(len(line)): resultlist.append(0) #slide non-zero tiles to the front of list times=-1 for item in range(len(line)): if not line[item] == 0: times += 1 resultlist.insert(times, line[item]) resultlist.pop() #merge the same number if len(resultlist) > 1: for item in range(1, len(resultlist)): if resultlist[item-1] == resultlist[item]: resultlist[item-1] = resultlist[item-1] * 2 resultlist.pop(item) resultlist.append(0) return resultlist
功能merge:将list中的非0的数值移到list前端,并且相邻数值合并。 e.g [2,2,0,4] 返还[4,4,0,0]
原理:运行任意 list(line), 创建新的 list (resultlist) 并给予其与原来line相同 数量的 元素 (值为 0)。 loop原list,如果元素值不等于0, 将该元素值插入新的list并且移除新list中最后一个值为0的元素,保持新list的长度与原有的相同。接下来loop新的list,如果list中的元素值与loop前一项元素值相等,那么前一项元素值翻倍,同时移除loop时那一项的元素值,同时在末尾添加数值为0 的 元素(保持list原有长度)。小记:在loop新list时,考虑到 list的长度可能只有1 (e.g. [4]) 或者list最前项和最后项相等。 如果 loop时 从 0开始,那么结果就会有误差。 所以在 loop新list下, 设置loop从 1开始, 这样就解决了可能 出现的问题。
0 0
- Python List Merge for game 2048 (part1)
- Data.Structures.For.Game.Programmers.PART1.Concepts.1&2
- python 小练习题for初学者 part1
- 2 Dimension list (list中的list)game 2048 part2
- [LeetCode] merge sort for linked list
- Python list for用法
- Linked List part1 : node
- ios Game-Center 开发 part1
- Python Scripting for the Game Engine
- Beginning Game Programming for Teens with Python
- Beginning Game Programming for Teens with Python
- 青少年Python游戏编程入门(Beginning Game Programming for Teens with Python译文)
- python列表解析([ x for x in list])
- Python sourcecode analysis-part1
- python学习日记:part1
- python学习笔记 part1
- python常用模块part1
- Hayday name list for apple Game Center (GC) 150307
- 黑马程序员java之多态和异常
- tomcat搭建成功后,无法进入管理页面的解决方法
- 贪心算法的思考
- 19.模板方法模式
- 平衡二叉树
- Python List Merge for game 2048 (part1)
- HDU 2086 A1 = ?(规律)
- Softmax回归
- TCP的发送系列 — tcp_sendmsg()的实现(二)
- 集合心得
- 1053. Path of Equal Weight (30)
- Active Defense Harbinger Distribution
- GCJ 2009 Round2 A (Crazy Rows)
- 开发线程安全的Servlet