プログラマーlv.1


HASH:Key Value対
counter
  • collectionsライブラリ
  • list=> counter: key/value:dictionary
  • 完走していない選手
  • 他のリストと比較
  • import collections 
    
    def solution(participant, completion):
        # answer = ''
        answer = collections.Counter(participant) - collections.Counter(completion) 
        return list(answer.keys())[0] 
    電話番号リスト
  • 自分と比較
  • def solution(phoneBook):
        phoneBook = sorted(phoneBook) # 정렬 필요
    
        for p1, p2 in zip(phoneBook, phoneBook[1:]):
            if p2.startswith(p1):
                return False
        return True
    に見せかける
  • 異なるリスト内のすべての組合せ
  • def solution(clothes):
        from collections import Counter
        from functools import reduce
        cnt = Counter([kind for name, kind in clothes])
        answer = reduce(lambda x, y: x*(y+1), cnt.values(), 1) - 1
        return answer

  • (headgear +1) * (eyewear +1) -1
    すべての服を着ない/着ない場合を除く

  • reduce(lambda x, y : x * (y+1), count.value(), 1) -1
  • 3rd parameter: 1
    2 ndパラメータ:服装の数=>y
    Counter({'headgear': 2, 'eyewear': 1}) =
    1( (1 x (2+1) ) x (1+1) ) -1
    =5
    reduceの使用例
  • answer = reduce(lambda x, y : x + y, [2,4,6,8,10])
    ((((2 + 4) + 6) + 8) + 10)
  • ツールバーの
    K番目の数
  • 2リスト情報からvalueを抽出してリストに入れる
  • def solution(array, commands):
        return list(map(lambda x:sorted(array[x[0]-1:x[1]])[x[2]-1], commands))
  • map,lambdaはコマンドに適用され、i=x[0]、j=x[1]、k=x[2]
  • def solution(array, commands):
        return [sorted(array[i-1:j])[k-1] for i,j,k in commands]
    map:ドアはいらない
    set(map(lambda x: x ** 2, range(5)))
    >>{0, 1, 4, 9, 16}
    大数
  • 前列降順
  • x*3で整数を比較
  • def solution(num): 
        num = list(map(str, num)) 
        num.sort(key = lambda x : x*3, reverse = True)  # 자릿수 맞추기
        return str(int(''.join(num))) # input이 0,0,0 => 0으로 변환 
  • 「333」、「303030」、「343434」、「555」、「999」(str:数字を順番に比較)
    sorted : '303'030 -> '333' -> '343'434 -> '555' -> '999'
    reverse=True
    ['9', '5', '34', '3', '30']
  • H-index
  • x=yの最近接値.
  • [3, 0, 6, 1, 5]
    sorted : [6,5,3,1,0]
    (1, 6) -> 1
    (2, 5) -> 2
    (3, 3) -> 3
    (4, 1) -> 1
    (5, 0) -> 0
    [1, 2, 3, 1, 0]
  • def solution(citations):
        citations.sort(reverse=True)
        answer = max(map(min, enumerate(citations, start=1))) # (index, value) 
        return answer 
    
    
    def solution(citations):
        citations.sort()
        article_count = len(citations)
    
        for i in range(article_count):
            if citations[i] >= article_count-i:
                return article_count-i
        return 0
    フルナビゲーション
    模擬試験
    def solution(answers):
      p = [[1,2,3,4,5],
          [2,1,2,3,2,4,2,5],
          [3,3,1,1,2,2,4,4,5,5]]
      s = [0] * 3
    
      for idx, a in enumerate(answers):
        for idx2, pattern in enumerate(p):
          if a==pattern[idx%len(pattern)]:
            s[idx2] += 1 
     
      return [i+1 for i in range(len(s)) if s[i] == max(s)]
  • cycle library
  • next
  • from itertools import cycle
    
    def solution(answer):
      giveups = [
        cycle([1,2,3,4,5]),
        cycle([2,1,2,3,2,4,2,5]),
        cycle([3,3,1,1,2,2,4,4,5,5])
      ]
      scores=[0,0,0]
      
      for num in answer:
        for i in range(3):
          if next(giveups[i])==num:
            scores[i] += 1
    
      return [i+1 for i in range(len(scores)) if scores[i]==max(scores)]
    小数点を探します:エラトスのふるい
    from itertools import permutations
    
    def solution(numbers):
        answer = []                                   
        nums = [n for n in numbers]                   # numbers를 하나씩 자른 것
        per = []                                      
        for i in range(1, len(numbers)+1):            # numbers의 각 숫자들을 순열로 모든 경우 만들기
            per += list(permutations(nums, i))        # i개씩 순열조합
        new_nums = [int(("").join(p)) for p in per]   # 각 순열조합을 하나의 int형 숫자로 변환
    
        for n in new_nums:                            # 모든 int형 숫자에 대해 소수인지 판별
            if n < 2:                                 # 2보다 작은 1,0의 경우 소수 아님
                continue
            check = True            
            for i in range(2,int(n**0.5) + 1):        # n의 제곱근 보다 작은 숫자까지만 나눗셈
                if n % i == 0:                        # 하나라도 나눠떨어진다면 소수 아님!
                    check = False
                    break
            if check:
                answer.append(n)                      # 소수일경우 answer 배열에 추가
    
        return len(set(answer))                       # set을 통해 중복 제거 후 반환
    from itertools import permutations
    
    def prime_list(n):
        prime = [True] * (n + 1)
        prime[0] = prime[1] = False 
        
        for i in range(2, int(n ** 0.5) + 1):
            if prime[i]:
                for j in range(i*i, len(prime), i):
                    prime[j] = False
        return prime
        
    def solution(numbers):
        numbers = list(numbers)
        number_set = set()
        
        for i in range(len(numbers)):
            number_set |= set(map(int, map(''.join, permutations(numbers, i+1))))
        
        prime = prime_list(max(number_set))
        
        answer = 0
        for number in number_set:
            if prime[number]:
                answer += 1
        return answer
    **set速度が遅い
    def solution(n):
        num = set(range(2, n+1))
        
        for i in range(2, n+1):
            if i in num:
                num -= set(range(2*i, n+1, i))
        return len(num)
    じゅうたん
    def solution(brown, yellow):    
        total = brown + yellow
        for i in range(3, int(total**0.5) + 1):
            if not total % i and (i-2) * ((total//i)-2) == yellow:
                return [total//i, i]
    def solution(brown, red):
        for i in range(1, int(red**(1/2))+1):
            if red % i == 0:
                if 2*(i + red//i) == brown-4:
                    return [red//i+2, i+2]
    深度/幅優先ナビゲーション(DFS/BFS)
    ターゲット番号
    def solution(numbers, target):
        n = len(numbers)
        answer = 0
        def dfs(idx, result):
            if idx == n:
                if result == target:
                    nonlocal answer
                    answer += 1
                return
            else:
                dfs(idx+1, result+numbers[idx])
                dfs(idx+1, result-numbers[idx])
        dfs(0,0)
        return answer
  • 完全ナビゲーション
  • from itertools import product
    def solution(numbers, target):
        l = [(x, -x) for x in numbers]
        s = list(map(sum, product(*l)))
        return s.count(target)
    from collections import deque
    
    def solution(numbers, target):
        answer = 0
        queue = deque() #queue 생성
        
        length = len(numbers)
        queue.append([-numbers[0], 0])
        queue.append([+numbers[0], 0])
        
        while queue :
            num, i = queue.popleft()
            if i+1 == length :
                if num == target : answer += 1
            else :
                queue.append([num - numbers[i + 1], i + 1])
                queue.append([num + numbers[i + 1], i + 1])
        
        return answer
    def solution(numbers, target):
        super = [0]
        for i in numbers:
            sub=[]
            for j in super:
                sub.append(j+i)
                sub.append(j-i)
            super=sub
        return super.count(target)
    from itertools import product
    def solution(numbers, target):
        l = [(x, -x) for x in numbers]
        s = list(map(sum, product(*l)))
        return s.count(target)
    スタックキュー
    株価
    def solution(prices):
        length = len(prices)
        answer = [ i for i in range (length - 1, -1, -1)]
        
        stack = [0]
        for i in range (1, length, 1):
            while stack and prices[stack[-1]] > prices[i]:
                j = stack.pop()
                answer[j] = i - j
            stack.append(i)
        return answer
    ブリッジトラック
    from collections import deque
    
    def solution(bridge_length, weight, truck_weights):
        answer = 0
    
        bridge = deque(0 for _ in range(bridge_length))
        total_weight = 0
        truck_weights.reverse()
    
        while truck_weights:
            total_weight -= bridge.popleft()
    
            if total_weight + truck_weights[-1] > weight:
                bridge.append(0)
            else:
                truck = truck_weights.pop()
                bridge.append(truck)
                total_weight += truck
    
            answer += 1
    
        answer += bridge_length
    
        return answer
    プリンタ
    def solution(priorities, location):
        answer = 0
        from collections import deque
    
        d = deque([(v,i) for i,v in enumerate(priorities)])
    
        while len(d):
            item = d.popleft()
            if d and max(d)[0] > item[0]:
                d.append(item)
            else:
                answer += 1
                if item[1] == location:
                    break
        return answer
    def solution(priorities, location):
        queue =  [(i,p) for i,p in enumerate(priorities)]
        answer = 0
        while True:
            cur = queue.pop(0)
            if any(cur[1] < q[1] for q in queue):
                queue.append(cur)
            else:
                answer += 1
                if cur[0] == location:
                    return answer
    機能開発
    def solution(progresses, speeds):
        Q=[]
        for p, s in zip(progresses, speeds):
            if len(Q)==0 or Q[-1][0]<-((p-100)//s):
                Q.append([-((p-100)//s),1])
            else:
                Q[-1][1]+=1
        return [q[1] for q in Q]
    from math import ceil
    
    def solution(progresses, speeds):
        daysLeft = list(map(lambda x: (ceil((100 - progresses[x]) / speeds[x])), range(len(progresses))))
        count = 1
        retList = []
    
        for i in range(len(daysLeft)):
            try:
                if daysLeft[i] < daysLeft[i + 1]:
                    retList.append(count)
                    count = 1
                else:
                    daysLeft[i + 1] = daysLeft[i]
                    count += 1
            except IndexError:
                retList.append(count)
    
        return retList
    
    お尻
    もっと辛い
    import heapq
       
    def solution(scoville, k):
        heap = []
        for num in scoville:
             heapq.heappush(heap, num)
        mix_cnt = 0
        while heap[0] < k:
            try:
                heapq.heappush(heap, heapq.heappop(heap) + (heapq.heappop(heap) * 2))
            except IndexError:
                return -1
            mix_cnt += 1
        return mix_cnt
    import heapq as hq
    
    def solution(scoville, K):
    
        hq.heapify(scoville)
        answer = 0
        while True:
            first = hq.heappop(scoville)
            if first >= K:
                break
            if len(scoville) == 0:
                return -1
            second = hq.heappop(scoville)
            hq.heappush(scoville, first + second*2)
            answer += 1  
    
        return answer
    from heapq import heapify, heappush, heappop
    def solution(scoville, K):
        heapify(scoville)
        for i in range(1000000):
            try:
                heappush(scoville, heappop(scoville)+(heappop(scoville)*2))
                if scoville[0] >= K: return i+1
            except:
                return -1