python discord Summer Code Jam 2020 참가 qualifier.py 풀기

July 13,2020

, 3 min read

이미지를 불러오지 못했습니다..ㅠㅠ

우연히 파이썬관련 커뮤니티를 찾다가 python discrod 라는 커뮤니티를 찾게되었고, 자체적으로 스폰서도 받아 잘 code jam을 잘 운영하고 있어 대회에 참가하게되었다.

Code Jam

참가를 위해서는 qualifier 문제를 풀어야한다. 즉, 테스트 코드를 PASS 하는 qualifier.py 코드를 작성하면 된다.

테스트 코드는 PASS

qualifier.py의 테스트 코드는 합격했다.

이제 본선(?)으로 가는 티켓의 결과를 기다리고 있다.

테스트코드 합격

제출은 google form에 작성해서 제출한다. 혹시나해서 짧은 영어로 한번더 물어보니 맞다고한다.

whywhyy : Should I copy and submit the qualifier.py code? or github url ?

kosayoda : just paste the contents of qualifier.py straight into the text field

whywhyy : Yeah. Thank you.

복붙해서 잘 제출했다.

테스팅코드를 통해 배우다.

TDD 기반으로 된 문제를 푸는 정말 좋은 기회였다.

문제를 풀기위해 테스트 코드를 읽어야 하는데, 이 테스팅 코드가 작성되어 동작하는것을 보는것 자체가 일단은 배울점이다.

클래스를 커스터마이징 하기위해 repr, len, lt 를 다루는 점도 좋았다.

클래스 객체를 다루는 set, get 도 다뤄보는 좋은 기회였다.

문제중 class 의 내부 id 를 핸들링하는것도 좋았다.


정답 : https://github.com/python-discord/summer-code-jam-2020-qualifier/blob/master/solution.py

아래는 내가 제출한 코드이다.

import datetime
import typing
import re
from itertools import count

class ArticleField:
    """The `ArticleField` class for the Advanced Requirements."""

    def __init__(self, field_type: typing.Type[typing.Any]):
        self._field_type = field_type
    
    def __set__(self, obj, val):
        if type(val) == str:
          raise TypeError("""expected an instance of type 'int' for attribute 'attribute', got 'str' instead""")
        obj._field_type = val

    def __get__(self, obj, val):
        return obj._field_type

class Article:
    """The `Article` class you need to write for the qualifier."""
    
    _ids = count(0)

    def __init__(self, title: str, author: str, publication_date: datetime.datetime, content: str):
        self._title = title
        self._author = author
        self._publication_date=publication_date
        self._content = content
        self._id = next(self._ids)
        self._last_edited = None

    @property
    def last_edited (self):
        return self._last_edited 

    @last_edited .setter
    def last_edited (self, value: datetime.datetime):
        self._last_edited  = value

    @property
    def id(self):
        return self._id

    @id.setter
    def id(self, value):
        self._id = value

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = value
        
    @property
    def author(self):
        return self._author

    @author.setter
    def author(self, value):
        self._author = value

    @property
    def publication_date(self):
        return self._publication_date

    @publication_date.setter
    def publication_date(self, value):
        self._publication_date = value

    @property
    def content(self):
        return self._content

    @content.setter
    def content(self, value):
        self.last_edited = datetime.datetime.now()
        self._content = value

    def __repr__(self):
      return (f'<{self.__class__.__name__}'
              f' title={self.title!r}'
              f' author={self.author!r}'
              f' publication_date={self.publication_date.isoformat()!r}>')
  
    def __len__(self):
      return len(self.content)

    def short_introduction(self, n_characters:int):
      ret_list = []
      content = self.content
      content = content.split()
      total_len = 0
      for i in content:
        total_len += len(i)
        if n_characters >= total_len:
          ret_list.append(i)
        else:
          break
        total_len+=1
      return " ".join(ret_list)
      
    def most_common_words(self,n:int):
      result = {}
      if n == 0 :
        return result
      content = self.content
      word_list = re.split('\W', content)
      word_list = ' '.join(word_list).split()
      word_list = list(map(lambda x:x.lower(),word_list))

      cal_dict = {}
      for idx,val in enumerate(word_list):
        try:
          cal_dict[val]["count"] += 1
        except KeyError:
          cal_dict[val] = {"count":1,"idx":idx}
      
      # dict to list
      cal_dict = sorted(cal_dict.items(), key=lambda x: (x[1]["idx"]))
      # list
      cal_dict = sorted(cal_dict, key=lambda x: (x[1]["count"]), reverse=True)

 
      count = 0
      for i in cal_dict:
        count+=1 
        if count > n :
          break
        result[i[0]] = i[1]["count"]
          
      return result
      
    def __lt__(self, other):
      return self.publication_date < other.publication_date