나의 풀이

def solution(s):
    data = []
    tmp = []
    cur = ""

    for i in s:
        if i.isdigit():
            cur = cur + i

        if i == ',' and any(cur):
            tmp.append(cur)
            cur = ""

        elif i == '}':
            if any(cur):
                tmp.append(cur)
                cur = ""
            if any(tmp):
                data.append(tmp)
                tmp = []

    data.sort(key=lambda x:len(x))
    data = [set(i) for i in data]

    result = [data[0]]
    for i in range(1, len(data)):
        result.append(data[i] - data[i - 1])
    result = [int(list(i)[0]) for i in result]
    return result

 

다른 풀이

def solution(s):
    answer = []

    s1 = s.lstrip('{').rstrip('}').split('},{')

    new_s = []
    for i in s1:
        new_s.append(i.split(','))

    new_s.sort(key = len)

    for i in new_s:
        for j in range(len(i)):
            if int(i[j]) not in answer:
                answer.append(int(i[j]))

    return answer

 

strip으로 {, }을 처리 해줄 수도 있다.

나의 풀이

def solution(clothes):
    answer = 1
    data = {}
    for i, j in clothes:
        data[j] = data.get(j, 0) + 1

    for i in data:
        answer *= data[i] + 1

    return answer - 1

 

파이썬 dictionary의 .get 함수를 사용하였다.

 

data.get(x, y)

딕셔너리 data에서 x 값을 가져오되, 없다면 y를 반환(default value)

나의 코드

def check(data):
    tmp = []
    for i in data:
        if i in ['(', '{', '[']:
            tmp.append(i)

        else:
            if tmp:
                if i == ')' and tmp[-1] == '(':
                    tmp.pop()

                elif i == '}' and tmp[-1] == '{':
                    tmp.pop()

                elif i == ']' and tmp[-1] == '[':
                    tmp.pop()
            else:
                return False

    return False if any(tmp) else True

def solution(s):
    answer = 0
    for i in range(len(s)):
        if check(s[i + 1:] + s[:i + 1]):
            answer += 1
    return answer

나의 코드

def solution(cacheSize, cities):
    answer = 0
    data = []

    if cacheSize == 0:
        return len(cities) * 5

    for i in cities: 
        i = i.lower()
        if i not in data:
            if len(data) == cacheSize:
                data.pop(0)
            data.append(i)
            answer += 5

        else:
            data.pop(data.index(i))
            data.append(i)
            answer += 1

    return answer

 

다른 코드

def solution(cacheSize, cities):
    import collections
    cache = collections.deque(maxlen=cacheSize)
    time = 0
    for i in cities:
        s = i.lower()
        if s in cache:
            cache.remove(s)
            cache.append(s)
            time += 1
        else:
            cache.append(s)
            time += 5
    return time

deque의 maxlen 인자를 이용

+ Recent posts