TWIG::2020.07.19

Today lolol·2020년 7월 19일
0

TWIG

목록 보기
10/17

세상은 넓고 똑똑한 사람은 많구나..

leetCode라는 곳에서 코딩 문제를 풀고 있는데, 이진 연산문제였다.
나의 코드는 장황하게 이런 식으로 작성했다.

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        a = a[::-1]
        b = b[::-1]
        
        a_length = len(a)
        b_length = len(b)
        
        length = 0
        if a_length > b_length:
            length = a_length
        else:
            length = b_length
            
        addFlag = False
        result = []
        for i in range(0, length+1):
            try:
                _a = a[i]
            except:
                _a = '0'
            try:
                _b = b[i]
            except:
                _b = '0'
            
            if addFlag and _a == '1' and _b == '1':
                result.append('1')
                addFlag = True
            elif addFlag and (_a == '1' or _b == '1'):
                result.append('0')
                addFlag = True
            elif addFlag and _a != '1' and _b != '1':
                result.append('1')
                addFlag = False
                
            elif (not addFlag) and _a == '1' and _b == '1':
                result.append('0')
                addFlag = True
            elif (not addFlag) and (_a == '1' or _b == '1'):
                result.append('1')
                addFlag = False
            else:
                result.append('0')
                addFlag = False
            
        if result[len(result) - 1] == '0':
            del result[len(result) - 1]
        
        result_str = ''
        for string in result[::-1]:
            result_str += string
        
        return result_str

코드를 보면, 모든 케이스를 그냥 다 살펴보는 방식이라고 할 수 있다.



생각없이 코드를 짜면 이런 식으로 나온다는 것을 알 수 있게 하는 그래프...

그렇다면 상위권 코드 작성자의 코드를 보자.

- Kia... bin()

# referenced from leetCode, sample 8 ms submission in july-leetcoding-challenge Add Binary
# https://leetcode.com/submissions/detail/368741573/?from=/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3395/
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a,2)+int(b,2))[2:]

bin함수가 있다는 것도 처음 알았고... int의 매개변수를 2개 이상 넣을 수 있다는 것도 처음 알았다.

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

당연하게도.. 16진수 또한 지원이 된다.. 자세한 내용은 아래의 게시물에 설명이 잘되어 있다.

- int()

int에 지수를 설정할 수 있다는 것을 처음 알았다..

또한 변환한 수를 더할 수 있다니..
곱할 수도 있다니... python의 세계는 참으로 신비하다.

그렇다면... programmers는..?

programmers도 코딩테스트를 푼 문제에 한하여, 다른 사람의 답을 볼 수 있는 기능을 있다. 풀어놓은 레벨 2의 문제 중 스택/큐 기능개발이라는 문제를 보자.

프로그래머스의 코드는 뭔가 안될거 같으니... 올리진 않겠다..
그러나 해당 코드에서 사용된 zip()이라는 함수는 무엇일까?

x = [1, 2, 3]
y = [4, 5, 6]

>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]

>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True

//연산자에 대해서도 처음 알게 되었다.

대단한 사람들이 참 많다..

profile
working making doing makes us 🤖

0개의 댓글