Dev Ops/Algorithm Python checkio 문제풀이4
  • 728x90
    반응형




    Python checkio Chapter .4




    Median



    본문


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    def checkio(data):
        data.sort()
        if len(data) % == 1:
            result =  data[len(data)//2]
        else:
            result = (data[len(data)//2+ data[len(data)//2-1])/2
     
        #replace this for solution
        return result
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        assert checkio([12345]) == 3"Sorted list"
        assert checkio([31253]) == 3"Not sorted list"
        assert checkio([130022001]) == 2"It's not an average"
        assert checkio([3620991015]) == 12.5"Even length"
        print("Start the long test")
        assert checkio(list(range(1000000))) == 499999.5"Long."
        print("The local tests are done.")
    cs


    다음은 다른 유저의 코드이다.



    Days Between



    본문


    튜플로 저장된 년, 월, 일 로 구성된 정수를 날짜로 변환하여 두 날짜의 차이 일수를 계산하여 반환한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    from datetime import date, timedelta
     
    def days_diff(date1, date2):
        """
            Find absolute diff in days between dates
        """
        f = date(*date1)
        s = date(*date2)
     
        result = abs((f-s).days)
     
        return result
     
    if __name__ == '__main__':
        #These "asserts" using only for self-checking and not necessary for auto-testing
        assert days_diff((1982419), (1982422)) == 3
        assert days_diff((201411), (2014827)) == 238
        assert days_diff((2014827), (201411)) == 238
     
    cs


    다음은 다른 유저의 코드이다.



    Cipher map



    본문


    다음 그림과 같이 4 x 4 암호 지도를 90도 시계 방향으로 회전하면서 단어를 조합한다.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    def recall_password(cipher_grille, ciphered_password):
        cipher_grille_list = list(cipher_grille)
        cipher_str = ''
        list_temp = []
        result = ""
     
        for rotate in range(4):
            for column in range(len(cipher_grille_list)):
                for row in range(len(cipher_grille_list[0])):
                    if cipher_grille_list[column][row] == 'X':
                        result += ciphered_password[column][row]
     
            for i in range(len(cipher_grille_list[0])):
                for j in range(len(cipher_grille_list)-1-1-1):
                    cipher_str += cipher_grille_list[j][i]
                list_temp.append(cipher_str)
                cipher_str = ''
            cipher_grille_list = list_temp
            list_temp = []
     
        return result
     
    if __name__ == '__main__':
        #These "asserts" using only for self-checking and not necessary for auto-testing
        assert recall_password(
            ('X...',
             '..X.',
             'X..X',
             '....'),
            ('itdf',
             'gdce',
             'aton',
             'qrdi')) == 'icantforgetiddqd''First example'
     
        assert recall_password(
            ('....',
             'X..X',
             '.X..',
             '...X'),
            ('xhwc',
             'rsqx',
             'xqzz',
             'fyzr')) == 'rxqrwsfzxqxzhczy''Second example'
     
     
     
    cs


    다음은 다른유저의 코드이다.




    Striped Words



    본문


    모음 또는 자음이 번갈아 반복되는 단어의 수 를 카운트하여 반환한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    VOWELS = "AEIOUY"
    CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
    SEPARATORS = ".,?"
     
    def checkio(text):
        result = 0
     
        # Splitting text
        for separator in SEPARATORS:
            text = text.replace(separator, " ")
        words = text.split()
     
        # Checking each word
        for word in words:
            if len(word) < 2: continue
            i = 0
            while i < len(word) - 1:
                if VOWELS.count(word[i].upper()) == and CONSONANTS.count(word[i].upper()) == or \
                                VOWELS.count(word[i].upper()) == VOWELS.count(word[i + 1].upper()) or \
                                CONSONANTS.count(word[i].upper()) == CONSONANTS.count(word[i + 1].upper()):
                    i = len(word)
                i += 1
                if i == len(word) - 1:
                    result += 1
     
        return result
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        assert checkio("My name is ..."== 3"All words are striped"
        assert checkio("Hello world"== 0"No one"
        assert checkio("A quantity of striped words."== 1"Only of"
        assert checkio("Dog,cat,mouse,bird.Human."== 3"Dog, cat and human"
     
    cs


    다음은 다른 유저의 코드이다.




    Friends



    본문


    위와 같이 클래스 내부의 함수들을 제작한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    from itertools import chain
     
    class Friends:
        def __init__(self, connections):
            self.connections = list(connections)
            #raise NotImplementedError
     
        def add(self, connection):
            if connection in self.connections:
                return False
            else:
                self.connections.append(connection)
                return True
            #raise NotImplementedError
     
        def remove(self, connection):
            if connection in self.connections:
                self.connections.remove(connection)
                return True
            else:
                return  False
            #raise NotImplementedError
     
        def names(self):
            return set(chain(*self.connections))
            #raise NotImplementedError
     
        def connected(self, name):
            return {n for n in self.names() if {n, name} in self.connections}
            #raise NotImplementedError
     
     
     
    if __name__ == '__main__':
        #These "asserts" using only for self-checking and not necessary for auto-testing
        letter_friends = Friends(({"a""b"}, {"b""c"}, {"c""a"}, {"a""c"}))
        digit_friends = Friends([{"1""2"}, {"3""1"}])
        assert letter_friends.add({"c""d"}) is True, "Add"
        assert letter_friends.add({"c""d"}) is False, "Add again"
        assert letter_friends.remove({"c""d"}) is True, "Remove"
        assert digit_friends.remove({"c""d"}) is False, "Remove non exists"
        assert letter_friends.names() == {"a""b""c"}, "Names"
        assert letter_friends.connected("d"== set(), "Non connected name"
        assert letter_friends.connected("a"== {"b""c"}, "Connected name"
     
    cs


    다음은 다른유저의 코드이다.













    728x90
    반응형

    'Dev Ops > Algorithm' 카테고리의 다른 글

    Python 코딩도장 풀이2  (0) 2017.08.09
    코딩도장 풀이1(feat.python)  (0) 2017.08.08
    Python checkio 문제풀이 3  (0) 2017.07.28
    Python checkio 풀이2  (0) 2017.07.27
    Python checkio 풀이1  (0) 2017.07.26
상단으로