CodeWars 13 : Help the bookseller !


問題の説明
A bookseller has lots of books classified in 26 categories labeled A, B, ... Z. Each book has a code c of 3, 4, 5 or more characters. The 1st character of a code is a capital letter which defines the book category.
In the bookseller's stocklist each code c is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock.
For example an extract of a stocklist could be:
L = {"ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"}.
or
L = ["ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"] or ....
You will be given a stocklist (e.g. : L) and a list of categories in capital letters e.g :
M = {"A", "B", "C", "W"} 
or
M = ["A", "B", "C", "W"] or ...
and your task is to find all the books of L with codes belonging to each category of M and to sum their quantity according to each category.
For the lists L and M of example you have to return the string (in Haskell/Clojure/Racket a list of pairs):
(A : 20) - (B : 114) - (C : 50) - (W : 0)
where A, B, C, W are the categories, 20 is the sum of the unique book of category A, 114 the sum corresponding to "BKWRK"and "BTSQZ", 50 corresponding to "CDXEF"and 0 to category 'W' since there are no code beginning with W.
要旨:リストM(アルファベットグループ)のアルファベットを基準として、リストL(書名グループ)の最初のアルファベットとMのアルファベットが一致するすべての本の数字を加算し、(알파벳 : 숫자의합) - (알파벳 : 숫자의합)と同じ文字列を生成して返す.
せいげんじょうけん
If L or M are empty return string is ""
Note:
In the result codes and their values are in the same order as in M.
いずれかのパラメータが空の場合は、「」(空白)を返します.
また、戻り値は、パラメータMと同じ順序でリストされる必要があります.
I/O例
L = ["ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"]
M = ["A", "B", "C", "W"]

결과값 : (A : 20) - (B : 114) - (C : 50) - (W : 0)
に答える
import re
def stock_list(listOfArt, listOfCat):
    result = ''
    for v in listOfCat:
        words = f' - ({v} : {v.lower()})' if len(result) > 0 else f'({v} : {v.lower()})'
        number = sum(map(int, re.findall('\d+', ' '.join(filter(lambda x : x[0]==v, listOfArt)))))
        result += words.replace(v.lower(), str(number))
    return result if listOfArt and listOfCat else ''
私のプール
  • は以下の手順で行います.
  • まずlistOfCat(アルファベットグループ)をforループに変換し、「A:a-B:b」などのアルファベット大文字と小文字の文字列を作成します.
  • はまた、フィルタ&正規表現map&sumを使用して、アルファベットに一致するすべての書籍の数字を抽出し、その総和を求める.(一致する文字列の検索->文字列から数を減算してリストを置換->int)
  • 生成された
  • 文字列の小文字を合計に置き換えます.
  • の3つの演算子を使用して、パラメータが入力されていないときに空白("")を返します.
  • 別の解釈
    def stock_list(listOfArt, listOfCat):
        if listOfArt and listOfCat:
            return " - ".join(['(%s : %d)' % (c, sum([int(i.split(" ")[1]) for i in listOfArt if c==i[0]])) for c in listOfCat])
        else:
            return ""