给定一系列放置在圆形中的各种彩色球,请删除相同的连续彩色球并打印不连续的彩色球

时间:2019-05-16 08:48:16

标签: python algorithm data-structures

该阵列将以圆形形式排列,应移除连续的相同色球,然后再次形成圆并移除相同的连续色球。最终打印出阵列中没有任何连续颜色的单个球。

'''input
'''
arr = ["red", "white", "black", "black", "white", "blue", "red"]

'''output
["blue"]
'''

2 个答案:

答案 0 :(得分:0)

尝试:

def has_consecutive_duplicates(arr):
    changed = True

    if len(arr) == 1:
        return False
    for i,color in enumerate(arr):
        try:
            next_color = arr[i+1]
        except Exception:
            next_color = arr[0]

        if color == next_color:

            if next_color == arr[0]:
                arr.remove(arr[0])
                arr.remove(color)
            else:
                arr.remove(next_color)
                arr.remove(arr[i])


            return changed
    else:
        print("All done")
        changed = False

return changed

while True:
    if not has_consecutive_duplicates(arr):
        break
print(arr)

答案 1 :(得分:0)

如果您有字符串列表,整数列表,浮点列表或包含字符串,整数和浮点的混合列表,则可以使用:

import itertools as itr

def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False

def groupCosecutive(lst):
    return [list(x[1]) for x in itr.groupby(lst)]

def remCircular(lst):
    if len(lst) <= 1:
        return lst
    lst = list(map(str, lst))
    while True:
        lst  = groupCosecutive(lst)
        if set(lst[0])==set(lst[-1]):
            lst = list(filter(lambda x: len(x) < 2, lst[1:-1]))
            lst = list(itr.chain(*lst))
        else :
            lst = list(filter(lambda x: len(x) < 2, lst))
            lst = list(itr.chain(*lst))

        if len(lst) <= 1:
            break

        elif sum(map(len, groupCosecutive(lst))) == len(groupCosecutive(lst)) and set(lst[0]) != set(lst[-1]):
            break

    return [int(x) if x.isdigit() else float(x) if isfloat(x) else x for x in lst]

print(remCircular(your_list))

输入:["red", "white", "black", "black", "white", "blue", "red"]
输出:['blue']
输入:[1,1,1,1,1,1,2,3,4,4,5,1,2]
输出:[3,5,1]
输入:[2.2, "red", "white", "black", "black", 1, 9, 9, 3.987, 2.2]
输出:['red', 'white', 1, 3.987]