这是在线类(class)作业的一部分,要求我们为 2048 游戏构建合并功能。该函数将一个列表作为参数并遍历它以返回另一个列表,其中合并了相同的元素,并更新了列表。
到目前为止,我能够检查空 block “零”并返回包含其余数字的列表。代码:
def merge(line):
"""
A function that merges a single row or column in 2048.
"""
output = [0]* len(line)
output1 = [0]* len(line)
for num in line:
if num != 0:
output.insert(-1,num)
del output[0]
我卡住的下一步是如何评估新列表以合并具有相同值的“总和”项。
我想将功能扩展到执行此操作的东西:
for num in output:
if num == "the next item in list":
return the sum of both items and skip to the next item
output1.insert(-1, "the sum of the two items")
del output1[0]
我们提供了运行测试以查看我们的代码是否正常运行
[2, 0, 2, 4] should return [4, 4, 0, 0],
[0, 0, 2, 2] should return [4, 0, 0, 0],
[2, 2, 0, 0] should return [4, 0, 0, 0],
[2, 2, 2, 2, 2] should return [4, 4, 2, 0, 0],
[8, 16, 16, 8] should return [8, 32, 8, 0]
非常感谢您的帮助
请您参考如下方法:
我也是分两步完成的。向左移动所有数字,删除所有零。然后遍历组合 2 个相似数字的数字列表。我用了itertools.groupby使类似数字的迭代更容易。
groupby 为每组类似的数字返回一个迭代器,因此:
[2,2,0,0]
成为
[(2, [2, 2]), (0, [0, 0])]
这样可以更轻松地将每个相似的组作为一个单独的 block 进行处理。
对于像 [2,2] 或 [2,2,2] 这样的相似数字组,输出将始终是长度减半的列表列表中的项目都将是 2*n(对于奇数长度列表,还有一个额外的最后一个元素将只是 n)。
from itertools import groupby
def merge(line):
cnt = len(line)
# Move all numbers left, removing zeros
line = [num for num in line if num != 0]
out = []
# Combine like numbers
for num, niter in groupby(line):
ncnt = len(list(niter))
out.extend([num * 2] * (ncnt // 2))
if ncnt % 2:
out.append(num)
# Right pad the list with zeros to the original line length
out.extend([0] * (cnt - len(out)))
return out
