我的代码未运行,但不会产生错误。我正在尝试合并一个列表,例如在2048中。例如,[2,2,4,4]应该变成[4,1,8,1],[4,4,4,4]应该变成[8 ,1、8、1]等。我现在无法弄清楚缩进,因此可以通过此repl.it链接https://repl.it/@lidstromfan5/2048访问代码。
def combine_left(num_list):
new_list = []
for i in range(3):
print(i)
while i <= 2:
if num_list[i] != 1 and num_list[i] == num_list[i+1]:
new_list.append(num_list[i] * 2)
new_list.append(1)
i += 1
else:
new_list.append(num_list[i])
else:
if num_list[3] != 1 and num_list[3] != num_list[2]:
new_list.append(num_list[3])
elif num_list[3] == 1 and num_list[3] != num_list[2]:
new_list.append(1)
break
num_list = new_list
return num_list # or, return combine_right(num_list[::-1])[::-1]
def combine_right(num_list):
return combine_left(num_list[::-1])[::-1]
# TESTS
# add more as you see fit
print(combine_left([2, 2, 4, 4])) # [4, 1, 8, 1]
print(combine_left([2, 2, 1, 1])) # [4, 1, 1, 1]
print(combine_left([1, 1, 2, 2])) # [1, 1, 4, 1]
print(combine_left([2, 2, 2, 1])) # [4, 1, 2, 1]
print(combine_left([4, 4, 4, 4])) # [8, 1, 8, 1]