这是问题所在。输入是整数列表。如果三个相邻的数字彼此相邻出现,则应将其删除,然后再次进行操作。iPhone应用程序具有相同颜色的球。输出应该是将要销毁的球的数量。
例:
input = [3,3,4,4,4,3,4]
第一次迭代
output: [3,3,3,4]
最终输出:
6
第一次迭代有4,4,4,所以有三个球。第二个是3,3,3。总体六分。
我的代码如下。它将删除4,4,4,但之后将失败,因为列表索引将很快超出范围。
def balls(a):
curr_index = 0
removed_count = 0
while len(a) > 2:
if (a[curr_index] == a[curr_index+1]) and (a[curr_index] == a[curr_index+2]):
a.remove(a[curr_index])
a.remove(a[curr_index+1])
a.remove(a[curr_index+2])
curr_index += 1
removed_count += 3
return removed_count
a = [3, 3, 4, 4, 4, 3, 4]
print(balls(a)) # should print 6
有任何想法吗?
input_values = [3,3,4,4,4,3,4]
values = input_values
while len(values) >= 3:
for x in range(0,len(values)-2):
# if we find 3 values in ar row
if values[x] == values[x+1] and values[x] == values[x+2]:
# update values by cutting out the series
values = values[:x] + values[x+3:]
# break this for loop
break
else:
# for loops can have an else statement
# this means that we came at the end of the for loop
# this if we didn't break the loop (and didn't found a valid triple)
# then we brea
break
#result - amount of removed balls
values, len(input_values) - len(values)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句