『面试测试题』贪婪是好事

116 阅读2分钟

测试面试题

题目:贪婪是好事

贪婪是一种用五个六面骰子玩的骰子游戏。如果你选择接受,你的任务就是按照这些规则得分。而你总是会得到一个有五个六边骰子值的数组。

积分规则:

三个 1 => 1000 分
三个 6 => 600 分
三个 5 => 500 分
三个 4 => 400 分
三个 3 => 300 分
三个 2 => 200 分
一个 1 => 100 分
一个 5 => 50 分

举例:

Throw       Score
---------   ------------------
5 1 3 4 1   250:  50  + 2 * 100
1 1 1 3 1   1100: 1000  + 100
2 4 4 5 4   450:  400  + 50

代码如下:

Python

方法一:

def score(dice):
    sum1 = 0
    counter = [0, 0, 0, 0, 0, 0]
    points = [1000, 200, 300, 400, 500, 600]
    extra = [100, 0, 0, 0, 50, 0]
    for die in dice:
        counter[die - 1] += 1

    for (i, count) in enumerate(counter):
        sum1 += (points[i] if count >= 3 else 0) + extra[i] * (count % 3)

    return sum1

方法二:

def score(dice):
    # 1. 查看列表内重复元素
    # 2. 重复次数为1,则判断是否为1或者5
    # 3. 重复次数大于3时,按照3+1来计算积分

    points = 0
    dice.sort()

    for i in range(1, 7):
        arr = dice.count(i)

        if arr < 3 and (i == 1 or i == 5):
            for j in range(arr):
                if i == 1:
                    points += 100
                elif i == 5:
                    points += 50
        elif arr > 3:
            if arr == 3:
                if i == 1:
                    points += 1000
                elif i == 2:
                    points += 200
                elif i == 3:
                    points += 300
                elif i == 4:
                    points += 400
                elif i == 5:
                    points += 500
                elif i == 6:
                    points += 600
            else:
                if i == 1:
                    points += 1000
                elif i == 2:
                    points += 200
                elif i == 3:
                    points += 300
                elif i == 4:
                    points += 400
                elif i == 5:
                    points += 500
                elif i == 6:
                    points += 600

                arr -= 3
                for j in range(arr):
                    if i == 1:
                        points += 100
                    elif i == 5:
                        points += 50
        elif arr == 3:
            if i == 1:
                points += 1000
            elif i == 2:
                points += 200
            elif i == 3:
                points += 300
            elif i == 4:
                points += 400
            elif i == 5:
                points += 500
            elif i == 6:
                points += 600

    # print(points)
    return points