代码改变世界

用 Python 解答两道来自阿里伯乐系统的笔试题

2018-07-29 11:04  云物互联  阅读(918)  评论(0编辑  收藏  举报

目录

前言

朋友到阿里面试,分享两道小题,博主比较闲就试着用 Python 解答一下,实现方式肯定是多种多样的,优劣也会各有不同,欢迎交流。

题目一

三个线程交替打印 abcabcabc…,一个打印 a,一个打印 b,一个打印 c。

分析

典型的线程同步问题,解决思路是互斥锁,三个线程通过锁来完成互斥下的协作同步。

这里写图片描述

实现

import threading


lock_a = threading.Lock()
lock_b = threading.Lock()
lock_c = threading.Lock()


def print_a(num):
    if num < 0:
        return

    lock_a.acquire()
    print('a')
    lock_b.release()

    print_a(num-1)


def print_b(num):
    if num < 0:
        return

    lock_b.acquire()
    print('b')
    lock_c.release()

    print_b(num-1)


def print_c(num):
    if num < 0:
        return

    lock_c.acquire()
    print('c')
    lock_a.release()

    print_c(num-1)


def main():
    num = 9

    thread_a = threading.Thread(target=print_a, args=(num,))
    thread_b = threading.Thread(target=print_b, args=(num,))
    thread_c = threading.Thread(target=print_c, args=(num,))

    lock_b.acquire()
    lock_c.acquire()
    thread_a.start()
    thread_b.start()
    thread_c.start()


if __name__ == '__main__':
    main()

题目二

有一个 String 类型数组 arr = { "a", "b", "d", "d", "a", "d", "a", "e", "d", "c" },请编码实现统计该数组中字符重复次数并由多到少的顺序对 a,b,c,d,e 重新排序输出。

分析

如果用 C 语言实现,那么姑且还是一道冒泡排序算法题。对于 Python 而言,这题就是比较单纯的熟练度考验,使用 collections 模块可以轻松实现。

实现

from collections import Counter


li1 = ["a", "b", "d", "d", "a", "d", "a", "e", "d", "c"]
print(Counter(li1))

from collections import defaultdict
from collections import OrderedDict


li1 = ["a", "b", "d", "d", "a", "d", "a", "e", "d", "c"]
d = defaultdict(int)


for k in li1:
    d[k] += 1
print OrderedDict(sorted(d.items(), key=lambda t: t[1], reverse=True))