找出距离自己最近的指定元素

# 找出距离H最近的G
# input lst = ['H', 'H', 'G', 'H', 'G', 'H', 'H', 'G', 'H']
# output [2, 1, 0, 1, 0, 1, 1, 0, 1]  # 第一个"H"最近的"G"相差距离为2


lst = ['H', 'H', 'G', 'H', 'G', 'H', 'H', 'G', 'H']


def find_min_distance(lst):
    lst = ''.join(lst)
    ret = []
    n = len(lst)
    for i in range(n):
        if lst[i] == 'G':
            ret.append(0)
            continue
        else:
            index1 = lst.find('G', i)
            index2 = lst[::-1].find('G', n-i)

            if index1 and index2:
                if abs(index1 - i) < abs(index2-n+i+1):
                    ret.append(abs(index1-i))
                else:
                    ret.append(abs(index2-n+i+1))
            elif index1:
                ret.append(abs(index1-i))
            elif index2:
                ret.append(abs(index2-n+i))
    return ret

print(find_min_distance(lst))