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




    Python checkio Chapter .3





    Fizz Buzz



    본문


    3의 배수를 입력받으면 "Fizz", 5의 배수를 입력 받으면 "Buzz", 공배수를 입력 받으면 "Fizz Buzz" 를 출력하는 게임을 제작해 본다.


    규칙

    1. 3 또는 5의 배수가 아니면 입력받은 숫자를 문자열 형태로 반환한다.


    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
    #Your optional code here
    #You can import some modules or create additional functions
    def checkio(number):
        #Your code here
        #It's main function. Don't remove this function
        #It's using for auto-testing and must return a result for check.
        if number % == and number % == 0:
            result = "Fizz Buzz"
        elif number % == 0:
            result = "Fizz"
        elif number % == 0:
            result = "Buzz"
        else:
            result = str(number)
        #replace this for solution
        return result
     
    #Some hints:
    #Convert a number in the string with str(n)
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        assert checkio(15== "Fizz Buzz""15 is divisible by 3 and 5"
        assert checkio(6== "Fizz""6 is divisible by 3"
        assert checkio(5== "Buzz""5 is divisible by 5"
        assert checkio(7== "7""7 is not divisible by 3 or 5"
     
    cs


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




    The Most Numbers



    본문


    숫자 배열중 최대 및 최소 요소 사이의 차이점을 찾아 반환한다. 빈 인수 목록에 대해서는 0을 반환한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    def checkio(*args):
        if not args:
            result = 0
        else:
            args1 = max(args)
            args2 = min(args)
            result = args1 - args2
     
        return result
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        def almost_equal(checked, correct, significant_digits):
            precision = 0.** significant_digits
            return correct - precision < checked < correct + precision
     
        assert almost_equal(checkio(123), 23), "3-1=2"
        assert almost_equal(checkio(5-5), 103), "5-(-5)=10"
        assert almost_equal(checkio(10.2-2.201.10.5), 12.43), "10.2-(-2.2)=12.4"
        assert almost_equal(checkio(), 03), "Empty"
    cs


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




    Even the last



    본문


    입력받는 정수 목록의 2의 배수 자리의 정수의 합을 구하여 마지막 요소를 곱하여 그 값을 정수로 반환하는 코드를 작성해보자.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    def checkio(array):
        """
            sums even-indexes elements and multiply at the last
        """
        result = 0
        if not array:
            result = 0
        else:
            for i in range(len(array)):
                if i % == 0:
                    result += array[i]
            result *= array[len(array)-1]
            
        return result
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        assert checkio([012345]) == 30"(0+2+4)*5=30"
        assert checkio([135]) == 30"(1+5)*5=30"
        assert checkio([6]) == 36"(6)*6=36"
        assert checkio([]) == 0"An empty array = 0"
     
    cs


    다음은 다른유저의 좀더 Python 스러운 코드이다.




    Secret Message



    본문


    입력받는 문자열 중 대문자를 수집하여 반환한다. 대문자가 없을 경우 빈 문자열을 반환하면 된다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    def find_message(text):
        """Find a secret message"""
        result = ""
        if text.islower() == True:
            result = ""
        else:
            for i in range(len(text)):
                if text[i].isupper() == True:
                    result += text[i]
                    
        return result
     
    if __name__ == '__main__':
        #These "asserts" using only for self-checking and not necessary for auto-testing
        assert find_message("How are you? Eh, ok. Low or Lower? Ohhh."== "HELLO""hello"
        assert find_message("hello world!"== """Nothing"
        assert find_message("HELLO WORLD!!!"== "HELLOWORLD""Capitals"
    cs


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




    Three words



    본문


    단어와 숫자 공백으로 구분된 문자열을 입력받아 숫자가 아닌 문자가 3회 이상 반복 되는지 판단하여 boolean 타입으로 반환한다.


    규칙

    1. 입력받는 문자열은 3단어 이상을 포함하고 있어야 한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    def checkio(words):
        i = 0
        for word in words.split():
            if word.isalpha():
                i += 1
            else:
                i = 0
            if i == 3:
                return True
        return False
     
     
    def test_function():
        assert checkio("Hello World hello") is True, "Hello"
        assert checkio("He is 123 man") is False, "123 man"
        assert checkio("1 2 3 4") is False, "Digits"
        assert checkio("bla bla bla bla") is True, "Bla Bla"
        assert checkio("Hi") is False, "Hi"
    cs


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




    index Power



    본문


    숫자 배열과 배열의 인덱스를 입력으로 받는다. 배열의 해당 인덱스자리의 정수를 인덱스 만큼 제곱한 값을 반환한다.


    규칙

    1. 인덱스 번호가 비어있는 배열을 가를킬 경우 -1 을 반환한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    def index_power(array, n):
        """
            Find Nth power of the element with index N.
        """
        if n < len(array):
            val = array[n]
            result = val**n
        else:
            result = -1
     
        return result
     
    if __name__ == '__main__':
        #These "asserts" using only for self-checking and not necessary for auto-testing
        assert index_power([1234], 2== 9"Square"
        assert index_power([1310100], 3== 1000000"Cube"
        assert index_power([01], 0== 1"Zero power"
        assert index_power([12], 3== -1"IndexError"
     
    cs


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




    Right to Left



    본문


    left 라는 단어가 들어있을 경우 right 로 변경하고 입력받은 튜플 타입을 문자열 타입으로 편집하여 반환하면 된다.


    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
    def left_join(phrases):
        """
            Join strings and replace "right" to "left"
        """
        result = ""
        i = 1
        for word in phrases:
            if "right" in word:
                result += word.replace("right""left")
     
            else:
                result += word
     
            if i != len(phrases):
                result += ","
            i += 1
     
        return result
     
    if __name__ == '__main__':
        #These "asserts" using only for self-checking and not necessary for auto-testing
        assert left_join(("left""right""left""stop")) == "left,left,left,stop""All to left"
        assert left_join(("bright aright""ok")) == "bleft aleft,ok""Bright Left"
        assert left_join(("brightness wright",)) == "bleftness wleft""One phrase"
        assert left_join(("enough""jokes")) == "enough,jokes""Nothing to replace"
     
    cs


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




    Digits Multiplication 



    본문


    양의 정수를 입력받아 '0' 을 제외한 모든 숫자의 곱셈 결과를 반환한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    def checkio(number):
        result = 1
        numStr = str(number)
        for num in numStr:
            if num != "0":
                result *= int(num)
     
        return result
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        assert checkio(123405== 120
        assert checkio(999== 729
        assert checkio(1000== 1
        assert checkio(1111== 1
     
    cs


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




    Number Basse



    본문


    입력으로 문자열과 진수표현을 입력받아 해당하는 진수로 문자열을 변환하여 10진수로 반환하는 프로그램을 작성한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    def checkio(str_number, radix):
        try:
            result = int(str_number, radix)
        except:
            result = -1
        return result
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        assert checkio("AF"16== 175"Hex"
        assert checkio("101"2== 5"Bin"
        assert checkio("101"5== 26"5 base"
        assert checkio("Z"36== 35"Z base"
        assert checkio("AB"10== -1"B > A > 10"
     
    cs


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




    Absolute sorting



    본문


    튜플 타입으로 숫자 배열을 입력받아 절대값으로 배열을 정렬하여 리스트 타입으로 반환하는 프로그램을 작성한다.


    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
    def checkio(numbers_array):
        list = []
        for number in numbers_array:
            list.append(abs(number))
     
        list.sort()
     
        for number in numbers_array:
            for i in range(len(numbers_array)):
                if list[i] == abs(number):
                    list[i] = number
     
        return list
     
    #These "asserts" using only for self-checking and not necessary for auto-testing
    if __name__ == '__main__':
        def check_it(array):
            if not isinstance(array, (list, tuple)):
                raise TypeError("The result should be a list or tuple.")
            return list(array)
     
        assert check_it(checkio((-20-51015))) == [-51015-20], "Example"  # or (-5, 10, 15, -20)
        assert check_it(checkio((1230))) == [0123], "Positive numbers"
        assert check_it(checkio((-1-2-30))) == [0-1-2-3], "Negative numbers"
     
    cs


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



    728x90
    반응형

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

    코딩도장 풀이1(feat.python)  (0) 2017.08.08
    Python checkio 문제풀이4  (0) 2017.08.07
    Python checkio 풀이2  (0) 2017.07.27
    Python checkio 풀이1  (0) 2017.07.26
    Python Fizz-Buzz 문제풀이  (0) 2017.07.26
상단으로