ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [30 Days of ML] Day 7
    Program/[Kaggle] 30 Days of ML 2021. 8. 12. 01:34
    반응형

    Excercise


    Imports

    Python에서는 고품질의 사용자 정의 라이브러리를 사용할 수 있음

    이러한 라이브러리의 일부는 "표준 라이브러리"에 있음

    먼저 표준 라이브러리 중 math 를 임포트해보자

    import math
    
    print("It's a math! It has type {}".format(type(math)))
    It's a math! It has type <class 'module'>

    math는 모듈임

    모듈은 다른 사람이 정의한 변수의 모음임

    우리는 내장 함수 dir()를 이용해서 math의 모든 names를 확인할 수 있음

    print(dir(math))
    ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

    Other import syntax

    as 를 사용해 줄여서 가져올 수 있음

    import pandas as pd # 이런 경우

    math.pi 가 아닌 그냥 pi로 접근하려면 아래처럼 하면 됨

    from math import *
    from math import pi # 다른 모듈의 function or 변수와 겹칠 수 있으니 이렇게 사용하자
    print(pi)
    3.141592653589793

    Submodules

    서브 모듈은 math.pi에서 pi와 같은 function 혹은 value와 같은 변수임


    Three tools for understanding strange objects

    1: type() (what is this thing?)

    2: dir() (what can I do with it?)

    3: help() (tell me more)


    Operator overloading

    리스트+정수와 같은 [3, 4, 1, 2, 2, 1] + 10 의 경우 성립하지 않음

    그러나 numpy 배열+정수와 같은 array([4, 1, 4, 4, 2, 5, 1, 2, 3, 1]) + 10의 경우 성립함

    아래와 같은 비교도 가능함

    rolls <= 3
    array([False, False,  True,  True, False,  True, False,  True,  True,
            True])

    When does 1 + 1 not equal 2?

    Python 라이브러리인 tensorflow는 operator overloading을 광범위하게 사용함

    import tensorflow as tf
    # Create two constants, each with value 1
    a = tf.constant(1)
    b = tf.constant(1)
    # Add them together to get...
    a + b
    <tf.Tensor: shape=(), dtype=int32, numpy=2>

    a+b는 2가 아니며 Operation의 출력 중 하나에 대한 symbolic handle임

    이는 해당 operation의 출력값을 가지지는 않지만 대신 TensorFlow.tf.Session에서 해당 값을 계산하는 수단을 제공함

    라이브러리가 operator overloading을 뚜렷(명확)하지 않은 방식으로 종종 사용한다는 사실을 알고 있어야 함


    Curious how it all works?

    print(dir(list))
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

    Python 프로그래머는 operator가 그 유형에 대해 어떻게 작용하는지 정의하고 싶을 때, __It__ , __setattr__, or __contains__와 같이 2개의 밑줄(__)로 시작하고 끝나는 특수한 이름을 가지는 메서드를 구현하여 정의함. 일반적으로 이러한 이름은 Python에 특별한 의미를 가짐

    예를 들어, x in [1, 2, 3][1, 2, 3].__contains__(x)와 동일함


    Tutorials


    1.

    def prettify_graph(graph):
        """Modify the given graph according to Jimmy's requests: add a title, make the y-axis
        start at 0, label the y-axis. (And, if you're feeling ambitious, format the tick marks
        as dollar amounts using the "$" symbol.)
        """
        graph.set_title("Results of 500 slot machine pulls") # 그래프 제목 설정
        graph.set_ylim(0) # y scale 범위 설정
        graph.set_ylabel('Balance') # y축 라벨 설정
    
        yticks=graph.get_yticks() # y 축 tick 얻기
        new_yticks = ['$ {}'.format(i) for i in yticks] # y 축 tick에 $ 붙이기
        graph.set_yticklabels(new_yticks) # 변환한 y 축 tick으로 설정

     

    3.

    내 코드

    def blackjack_hand_greater_than(hand_1, hand_2):
        """
        Return True if hand_1 beats hand_2, and False otherwise.
    
        In order for hand_1 to beat hand_2 the following must be true:
        - The total of hand_1 must not exceed 21
        - The total of hand_1 must exceed the total of hand_2 OR hand_2's total must exceed 21
    
        Hands are represented as a list of cards. Each card is represented by a string.
    
        When adding up a hand's total, cards with numbers count for that many points. Face
        cards ('J', 'Q', and 'K') are worth 10 points. 'A' can count for 1 or 11.
    
        When determining a hand's total, you should try to count aces in the way that 
        maximizes the hand's total without going over 21. e.g. the total of ['A', 'A', '9'] is 21,
        the total of ['A', 'A', '9', '3'] is 14.
    
        Examples:
        >>> blackjack_hand_greater_than(['K'], ['3', '4'])
        True
        >>> blackjack_hand_greater_than(['K'], ['10'])
        False
        >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3'])
        False
        """
        total_list = [hand_1, hand_2] # 각 핸드의 점수를 편리하게 계산하기 위해 리스트에 넣어줌
        temp = 0
        total_dict={} # 핸드는 문자형이므로 숫자로 변형해서 저장하기 위한 딕셔너리(흠.. 리스트로 했어도 괜찮을거같은데)
    
        # 각 핸드에 접근
        for i in range(len(total_list)):
            total_dict[i]=[] # 문자형을 숫자로 변형하여 저장할 빈 리스트 생성
            for j in total_list[i]:
                # J, Q, K의 경우 10
                if j in ['J', 'Q', 'K']:
                    temp=10
                    total_dict[i].append(temp)
                # A의 경우 일단 1
                elif j == 'A':
                    temp = 1
                    total_dict[i].append(temp)
                # 나머지는 모두 정수형으로 저장
                else:
                    total_dict[i].append(int(j))
    
        answer=[] # 입력 받은 리스트의 합계를 계산해 저장할 리스트 선언
        for k, v in total_dict.items():
            # 1의 개수를 세줌
            count=v.count(1)
            # 핸드의 합계를 계산
            sum_=sum(v)
    
            # 초반에 A를 일단 1로 두었는데
            # 핸드의 합계에 따라 21보다 작으면 10을 더하여 A의 값을 변환해줌
            while(count>=1):
                if sum_+10>21:
                    break
                else:
                    sum_+=10
                count-=1
            answer.append(sum_)
    
    #     In order for hand_1 to beat hand_2 the following must be true:
    #     - The total of hand_1 must not exceed 21
    #     - The total of hand_1 must exceed the total of hand_2 OR hand_2's total must exceed 21
        # 위의 조건에 맞게 비교하여 값을 반환하면 끝
        if answer[0]>21:
            return False
        else:
            if (answer[0]>answer[1] or answer[1]>21):
                return True
            else:
                return False

    답 코드

    def hand_total(hand):
        """Helper function to calculate the total points of a blackjack hand.
        """
        total = 0
        # Count the number of aces and deal with how to apply them at the end.
        aces = 0
        for card in hand:
            if card in ['J', 'Q', 'K']:
                total += 10
            elif card == 'A':
                aces += 1
            else:
                # Convert number cards (e.g. '7') to ints
                total += int(card)
        # At this point, total is the sum of this hand's cards *not counting aces*.
    
        # Add aces, counting them as 1 for now. This is the smallest total we can make from this hand
        total += aces
        # "Upgrade" aces from 1 to 11 as long as it helps us get closer to 21
        # without busting
        while total + 10 <= 21 and aces > 0:
            # Upgrade an ace from 1 to 11
            total += 10
            aces -= 1
        return total
    
    def blackjack_hand_greater_than(hand_1, hand_2):
        total_1 = hand_total(hand_1)
        total_2 = hand_total(hand_2)
        return total_1 <= 21 and (total_1 > total_2 or total_2 > 21)

    답 코드가 좀 더 깔끔한 것 같음

    반응형

    'Program > [Kaggle] 30 Days of ML' 카테고리의 다른 글

    [30 Days of ML] Day 9 - part 1  (0) 2021.08.15
    [30 Days of ML] Day 8  (0) 2021.08.12
    [30 Days of ML] Day 6  (0) 2021.08.11
    [30 Days of ML] Day 5 - part 2  (0) 2021.08.09
    [30 Days of ML] Day 5 - part 1  (0) 2021.08.08

    댓글

Designed by Tistory.