拼多多:笔试题(20190901)

寻找优先级的Top N

先将序列分成奇数和偶数部分,分别就地排序后合并。输出前N个数字

def top_n_of_array(seq, k):
    left = [lu for lu in seq if lu % 2 == 0]
    right = [ru for ru in seq if ru % 2 != 0]
    left.sort(reverse=True)
    right.sort(reverse=True)
    return (left+right)[:k]


if __name__ == '__main__':
    values = input().strip().split(';')
    seq, k = list(map(int, values[0].split(','))), int(values[1])
    res = top_n_of_array(seq, k)
    res = list(map(lambda ru: str(ru), res))
    print(','.join(res))

扑克游戏

由于长度小于等于8,直接bfs最多三层的复杂度进行求解。

class Game:
    def __init__(self):
        self.res = None
        self.pos = None

    def kind_of_games(self, left, right):
        self.find(left, "", right)
        return self.res

    def find(self, one, cur, two):
        if self.res is None:
            self.res = []
        if self.pos is None:
            self.pos = []
        if cur == two:
            self.res.append(' '.join(self.pos) + 'd'*len(one))
        if not one:
            return

        element = one[0]
        remain = one[1:]
        self.pos.append('d')
        self.find(remain, cur, two)
        self.pos.pop()

        self.pos.append('l')
        self.find(remain, element+cur, two)
        self.pos.pop()

        self.pos.append('r')
        self.find(remain, cur+element, two)
        self.pos.pop()


if __name__ == '__main__':
    num = int(input().strip())
    for _ in range(num):
        left = input().strip()
        right = input().strip()
        result = Game().kind_of_games(left, right)
        print("{")
        result.sort()
        for ru in result:
            print(ru)
        print("}")

掷骰子

对各个骰子升序排序后,建立字典,每次对其中的一个骰子进行比较更新骰子。其中,要注意,每次遍历一个骰子的点数是降序。

from collections import Counter


def average(result):
    result.sort()
    values = [list(range(1, ru+1)) for ru in result]
    possible = Counter(values[0])
    for vi in range(1, len(values)):
        right = values[vi]
        for ru in right[::-1]:
            var = count(possible, ru)
            possible[ru] = var
    factor = sum([pk*pv for pk, pv in possible.items()])
    freq = sum(possible.values())
    return "{:.2f}".format(factor/freq)


def count(possible, cur):
    res = 0
    for pk, pu in possible.items():
        if pk < cur:
            res += pu
        elif pk == cur:
            res += pk * pu
    return res


if __name__ == '__main__':
    num = int(input().strip())
    result = list(map(int, input().strip().split()))
    res = average(result)
    print(res)

第k大的元素

不管是常规还是使用堆排序,仅通过数量少的30%。

from heapq import heappush, heappop, heapify


def cal_k_number(seq, k):
    for _ in range(k-1):
        heappop(seq)
    return -heappop(seq)


if __name__ == '__main__':
    [n, m, k] = list(map(int, input().strip().split()))
    seq = [-nu*mu for nu in range(1, n+1) for mu in range(1, m+1)]
    heapify(seq)
    print(cal_k_number(seq, k))

(最近更新:2019年09月01日)

你可能感兴趣的:(PROGRAM)