CCF:201912-2 回收站选址 Python实现(含解析)

题目回顾:

CCF:201912-2 回收站选址 Python实现(含解析)_第1张图片

题目释义:

  1. 第一行输入垃圾点坐标个数i,后1+i行输入坐标的x值与y值以空格隔开。
  2. 可以作为回收点的要求:1.必须是garbage点。2.该点的上下左右点必须有垃圾即(x,y+1),(x,y-1),(x+1,y),(x-1,y)点必须有垃圾
  3. 回收点评分标准:回收点的四个对角位置有垃圾则加一分(0-4分)即(x-1,y-1),(x-1,y+1),(x+1,y-1),(x+1,y+1)点作为加分标准。
  4. 我们的任务是把回收点的分数分布统计出来

剖析任务点:

  1. 将坐标以list的形式存储
  2. 判断坐标是否为garbage
  3. 判断garbage坐标是否可作为回收点
  4. 回收点评分
  5. 回收点分数统计

算法实现:

# 判断是否为垃圾
def getIsGarbage(x, y, garbageXY):
    flag = False
    for i in garbageXY:
        if i[0] == x and i[1] == y:
            flag = True
            break
        else:
            continue
    return flag

# 判断garbageXY能否作为回收点
def getIsRecovery(x, y, garbageXY):
    flag = False
    judge_list= []
    tupa = (x, y+1)
    judge_list.append(tupa)
    tupb = (x, y-1)
    judge_list.append(tupb)
    tupc = (x+1, y)
    judge_list.append(tupc)
    tupd = (x-1, y)
    judge_list.append(tupd)
    for n in judge_list:
        if getIsGarbage(n[0], n[1], garbageXY) == True:
            flag = True
            continue
        else:
            flag = False
            break
    return flag

# 回收点评分
def getScore(x, y, garbageXY):
    score = 0
    data_list = []
    tup2 = (x-1, y-1)
    data_list.append(tup2)
    tup3 = (x-1, y+1)
    data_list.append(tup3)
    tup4 = (x+1, y-1)
    data_list.append(tup4)
    tup5 = (x+1, y+1)
    data_list.append(tup5)

    for k in data_list:
        if getIsGarbage(k[0], k[1], garbageXY) == True:
            score = score + 1
        else:
            continue
    return score

if __name__ == "__main__":
    # 输入
    n = int(input())
    garbageXY = []
    for i in range(0, n):
        x, y = map(int, input().split())
        tup1 = (x, y)
        garbageXY.append(tup1)
    # 判断垃圾坐标能否作为回收站,若能做回收站则给其评分,并将分数存入score_list中
    # 将score_list中的分数统计至字典dict_score中
    dict_score = {
     '0': 0, '1': 0, '2': 0, '3': 0, '4': 0}
    score_list = []
    for i in garbageXY:
        if getIsRecovery(i[0], i[1], garbageXY) == True:
            score_list.append(getScore(i[0], i[1], garbageXY))
    # print(score_list)
    for i in score_list:
        dict_score['{}'.format(i)] += 1
    # print(dict_score)
    print(dict_score['0'])
    print(dict_score['1'])
    print(dict_score['2'])
    print(dict_score['3'])
    print(dict_score['4'])

运行结果:

CCF:201912-2 回收站选址 Python实现(含解析)_第2张图片

你可能感兴趣的:(算法,python,leetcode)