Using Python to solve two written test questions from Alibaba music system

Posted by SystemOverload on Wed, 29 Jan 2020 17:08:27 +0100

Catalog

Preface

When a friend comes to Ali for an interview and shares two small questions, the blogger will try to solve them in Python when he is free. There must be many ways to realize them, and the advantages and disadvantages will be different. Welcome to exchange.

Topic 1

Three threads alternately print ABC ABC ABC , one print a, one print b, one print c.

Analysis

The typical thread synchronization problem, the solution is mutually exclusive lock, three threads through the lock to complete the mutually exclusive cooperation synchronization.

Realization

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()

Topic two

There is an array of String type arr = {"a", "B", "d", "d", "a", "d", "a", "e", "d", "C"}. Please code to count the number of character repetitions in the array and reorder the output of a,b,c,d,e from more to less.

Analysis

If it is implemented in C language, it is still a bubble sorting algorithm. For Python, this is a simple proficiency test, which can be easily implemented by using the collections module.

Realization

from collections import Counter


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

or

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))

Topics: Python less Lambda C