Exemple #1
0
def BlackJack(m, a):
    temp = combi(a, 3)
    for i in temp:
        sum_i = sum(i)
        if sum_i <= m:
            b.append(sum(i))
    return max(b)
Exemple #2
0
def solution(orders, course):
    answer = []
    from itertools import combinations as combi
    dic = dict()

    for i in course:
        dic[i] = dict()

    for i in orders:
        for j in course:
            for k in combi([*i], j):
                k2 = ''.join(sorted(list(k)))
                dic[j][k2] = 0

    for i in orders:
        for j in course:
            for k in dic[j]:
                if set([*k]).issubset(set([*i])):
                    dic[j][k] += 1

    for i in course:
        if dic[i]:
            max_num = max(dic[i].values())
            if max_num < 2:
                pass
            else:
                answer.extend(
                    list(k for k, v in dic[i].items() if v == max_num))
    answer.sort()

    return answer
def solution(n, weak, dist):
    dst = copy.deepcopy(dist)
    dst.sort(reverse=True)

    # 투입되는 친구의 수
    for i in range(1, len(dst) + 1):
        # weak = [1, 5, 6, 10]
        for item in combi(range(len(weak)), i):
            # i = 2  -> (0,1), (0,2), (0,3), ....
            d = []
            for j in range(i):
                d.append((weak[item[(j + 1) % i] - 1] - weak[item[j]] + n) % n)
            d.sort(reverse=True)

            rst = True
            for j in range(i):
                if dst[j] < d[j]:
                    rst = False

            # weak 중 i개의 점을 선택하여 큰 dst부터 거리 체크하여
            # 모든 weak 다 확인할 경우
            if rst:
                return i

    return -1
Exemple #4
0
def super_matrix_full(array: object):

    nat = array.noa
    nb = nat - 1
    from itertools import product as combi
    state = np.asarray([i for i in combi(range(3), repeat=nb)])
    st = np.ones([nat, nat, 3 ** nb], dtype=int) * 2
    index = np.asarray(np.argsort(array.pos)[:, 1:nb + 1], dtype=np.int)
    for n1 in range(nat):
        k = 0
        for n2 in np.sort(index[n1, :]):
            for i in range(3 ** nb):
                st[n1, n2, i] = state[i, k]
            k += 1

    sigma = lil_matrix([3 ** nb * nat, 3 ** nb * nat], dtype=np.complex)
    sigmai = sigma_matrix(array)

    def foo(ni1, nj2, i, j):
        for ki1 in np.append(index[ni1, :], index[nj2, :]):
            if ki1 == ni1 or ki1 == nj2: continue;
            if st[ni1, ki1, i] != st[nj2, ki1, j]:
                return False
        return True

    for n1 in range(nat):
        for n2 in range(nat):  # choose initial excited atom
            for i in range(3 ** nb):  # select initial excited atom environment
                # choose final excited or np.sort(self.index[n1,:]): if massive photon

                for j in range(3 ** nb):  # select final excited environment
                    if foo(n1, n2, i, j):  # if transition is possible then make assigment
                        sigma[n1 * 3 ** nb + i, n2 * 3 ** nb + j] = \
                            sigmai[n1, n2, st[n1, n2, i], st[n2, n1, j]]
    return csr_matrix(sigma)
def solution(n, info):
    answer = [0] * 11
    max_score = 0
    real_ryan = {}
    for comb in combi(range(11), n):
        ryan = Counter(comb)
        apeach_score = 0
        ryan_score = 0

        for i in range(1, 11):
            if info[10 - i] < ryan[i]:
                ryan_score += i
            elif info[10 - i] > 0:
                apeach_score += i

        score = ryan_score - apeach_score
        if score > max_score:
            max_score = score
            real_ryan = ryan

    if max_score > 0:
        for r in real_ryan:
            answer[10 - r] = real_ryan[r]
        return answer
    else:
        return [-1]
Exemple #6
0
def solution(relation):
    len_row = len(relation) # 가로(행)의 갯수
    len_col = len(relation[0]) # 세로(열)의 갯수

    # combinations를 통해 속성(열)의 조합(중복 x) 계산
    com_list = []
    for i in range(1, len_col+1):
        com_list.extend(combi(range(len_col), i))

    # 행렬을 바꾼 리스트 생성
    change_col_row = [list(i) for i in zip(*relation)]

    unique = []
    for c in com_list:
        tmp = []
        for i in c:
            tmp.append(change_col_row[i])

        if len(  set( [ ''.join(k) for k in [list(j) for j in zip(*tmp)] ] ) ) == len_row:
            unique.append(c)
    
    duplicate = []
    for i in range(len(unique)):
        for j in range(i+1, len(unique)):
            if set(unique[i]) == set(unique[i]).intersection(set(unique[j])):
                duplicate.append(unique[j])

    answer = set(unique) - set(duplicate)

    return len(answer)
Exemple #7
0
    def _contruct_combinations(self, rank):
        deck_combos = []

        for deck in self._tdecks:
            rank_combinations = []
            for i in range(1, rank + 1):
                comb = combi(deck, i)
                comb = list(comb)
                rank_combinations.append(comb)
            deck_combos.append(rank_combinations)
        return deck_combos
def solution(N, M):
    field = [list(input()) for i in range(N)]
    vh = [0] * (N * M)
    direc = [[1, 0], [0, 1]]
    result = -float('inf')
    for i in range(N * M + 1):
        for indices in combi(range(N * M), i):
            for idx in indices:
                vh[idx] = 1
            result = max(result, calculate(field, vh, N, M, direc))
            for idx in indices:
                vh[idx] = 0
    print(result)
Exemple #9
0
def solve(N, K, pcs):
    pcs_side_area = [pc[0] * 2 * pc[1] * pi for pc in pcs]
    pcs_btm_area = [pc[0] * pc[0] * pi for pc in pcs]

    if K == 1:
        ans = max([s + b for (s, b) in zip(pcs_side_area, pcs_btm_area)])
    else:
        patterns = list(combi(list(range(0, N)), K))
        total_area_list = [
            calc_total_area(pcs_side_area, pcs_btm_area, p) for p in patterns
        ]
        ans = max(total_area_list)

    return str(round(ans, 9))
def solution(info, query):
    answer = []

    infodict = defaultdict(list)
    for i in info:
        temp = i.split(" ")
        keylist = temp[:-1]
        score = int(temp[-1])

        for j in range(5):
            for c in combi(keylist, j):
                key = ''.join(c)
                infodict[key].append(score)

    for key in infodict.keys():  # 같은 key값이면 점수를 오름차순 정렬
        infodict[key].sort()
    print(infodict.keys())

    for q in query:  # query 정보 분리
        temp = []
        q = q.split(" ")

        for el in q:
            if el != 'and' and el != '-':
                temp.append(el)

        key = ''.join(temp[:-1])
        score = int(temp[-1])

        count = 0  # 조건에 해당하는 info

        if key in infodict.keys():
            value = infodict[key]  # value는 배열
            start, end = 0, len(value)
            while start <= end and start < len(value):
                mid = (start+end)//2

                if value[mid] < score:
                    start = mid+1
                else:
                    end = mid-1
            count = len(value)-start
        answer.append(count)

    # print(temp)
    # print(answer)
    return answer
Exemple #11
0
def solution(relation):
    r= len(relation)
    c= len(relation[0])
    dic={}
    table= [[-1]*c for _ in range(r)]
    idx=0
    for i in range(r):
        for j in range(c):
            if relation[i][j] not in dic:
                dic[relation[i][j]]=idx
                table[i][j]=idx
                idx+=1
            else:
                table[i][j]=dic[relation[i][j]]
    for i in range(r):
        for j in range(c):
            table[i][j]= str(table[i][j])
                
    [print(*el) for el in table]
    answer = 0
    done= [0]*c
    for i in range(1,c+1):
        for ls in combi(list(range(c)),i):
            print(ls)
            s=0
            s=sum([done[el] for el in ls])
            if s:
                continue
            chk={}
            flag=False
            for j in range(r):
                chunk=''
                for idx in ls:
                    chunk+=table[j][idx]+' '
                print(chunk)
                if chunk not in chk:
                    chk[chunk]=True
                else:
                    flag=True
                    break
            if not flag:
                for idx in ls:
                    done[idx]=1
                answer+=1
            print('done',done)

    return answer
Exemple #12
0
def solution(info, query):
    answer = []
    combiDict = {}

    for i in info:
        tmpInfo = i.split(' ')
        val = int(tmpInfo[-1])
        tmpInfo = tmpInfo[:-1]

        for i in range(5):
            for c in combi(tmpInfo, i):
                if c not in combiDict:
                    combiDict[c] = []

                combiDict[c].append(val)

    for d in combiDict:
        combiDict[d].sort()

    for q in query:
        cnt = 0
        q = [c for c in q.split(' ') if c != 'and' and c != '-']
        val = int(q.pop())
        q = tuple(q)

        if q not in combiDict:
            answer.append(cnt)
            continue

        arr = combiDict[q]
        length = len(arr)
        st, en = 0, length - 1

        while st <= en:
            mid = (st + en) // 2

            if arr[mid] < val:
                st = mid + 1
            else:
                en = mid - 1
        idx = en + 1

        answer.append(length - idx)

    return answer
Exemple #13
0
def cableCalculator(need, cables, output=None):
    from itertools import combinations as combi
    from collections import defaultdict

    t = cables
    lens = len(t)
    t = [i for i in t if i <= need]
    i = 1
    if output is None:
        output = dict()
    while i < lens:
        pools = list(combi(t, i))
        for each in pools:
            output[sum(each)] = sorted(each, reverse=True)
        i += 1
    if need in output:
        return ','.join(map(str, list(output[need])))
    else:
        return 'No result'
def cableCalculator(need, cables, output=None):
    from itertools import combinations as combi
    from collections import defaultdict

    t = cables
    lens = len(t)
    t = [i for i in t if i <= need]
    i = 1
    if output is None:
        output = dict()
    while i < lens:
        pools = list(combi(t, i))
        for each in pools:
            output[sum(each)] = sorted(each, reverse=True)
        i += 1
    if need in output:
        return ','.join(map(str, list(output[need]) ) )
    else:
        return 'No result'
Exemple #15
0
def solution(info, query):
    answer = []
    info_dict = defaultdict(list)

    for i in info:
        i = i.split()
        info_key = i[:-1]
        info_value = int(i[-1])
        for j in range(5):
            for c in combi(info_key, j):
                temp_key = ''.join(c)
                info_dict[temp_key].append(info_value)

    for key in info_dict.keys():
        info_dict[key].sort()

    for q in query:
        q = q.split()
        q_value = int(q[-1])
        q = q[:-1]
        for i in range(3):
            q.remove('and')
        while '-' in q:
            q.remove('-')
        temp_q = ''.join(q)

        if temp_q in info_dict:
            score = info_dict[temp_q]
            n = 0
            if len(score) > 0:
                start, end = 0, len(score)
                while end > start:
                    flag = (start + end) // 2
                    if score[flag] >= q_value:
                        end = flag
                    else:
                        start = flag + 1
                answer.append(len(score) - start)
        else:
            answer.append(0)

    return answer
def solution(info, query):
    answer = []
    info_dict = defaultdict(list)
    for i in info:
        i = i.split()
        i_key = i[:-1]
        i_val = int(i[-1])
        for k in range(5):
            for c in combi(i_key, k):
                tmp_c = ''.join(c)
                info_dict[tmp_c].append(i_val)

    for key in info_dict.keys():
        info_dict[key].sort()

    for q in query:
        q = q.split(' ')
        q_score = int(q[-1])
        q = q[:-1]

        for r in range(3):
            q.remove('and')
        while '-' in q:
            q.remove('-')
        tmp_q = ''.join(q)

        if tmp_q in info_dict:
            scores = info_dict[tmp_q]
            if len(scores) > 0:
                start, end = 0, len(scores)
                while end > start:
                    mid = (start + end) // 2
                    if scores[mid] >= q_score:
                        end = mid
                    else:
                        start = mid + 1
                answer.append(len(scores) - start)
        else:
            answer.append(0)

    return answer
Exemple #17
0
def a():
    n, k = map(int, input().split())
    A = {int(a) for a in input().split()}

    if k > max(A):
        print('IMPOSSIBLE')
        return
    # combination of two nums in A
    # keep making the combination -
    # until it finds k or doesn't increase in number.
    from itertools import combinations as combi
    l = len(A)
    while True:
        A |= { abs(c[0] - c[1]) for c in combi(A, 2) }
        if k in A or 1 in A:
            print('POSSIBLE')
            return
        if len(A) == l:
            break
        l = len(A)
    print( 'POSSIBLE' if k in A else 'IMPOSSIBLE' )
Exemple #18
0
def solution(relation):
    col=range(len(relation[0]))
    row_len=len(relation)
    #모든 경우의수
    candi=[]
    for i in range(1,len(col)+1):
        candi.extend(combi(col,i))
    #유일성
    uniques=[]
    for i in candi:
        tmp=set([tuple(x[j] for j in i) for x in relation])
        if len(tmp)==row_len:
            uniques.append(set(i))
    #삭제 오류 방지
    answer=uniques[:]
    # 최소성 
    for index,value in enumerate(uniques):
        for j in uniques[index+1:]:
            if value==value&j and (j in answer):
                answer.remove(j)
    return len(answer)
Exemple #19
0
def solution(N, number):
    dp= {}
    for i in range(1,7):
        dp[int(str(N)*i)]=i
    dp[0]=0
    for _ in range(8):
        new={}
        L=list(dp.items())
        for el in combi(L,2):
            (k1, v1), (k2, v2)= el
            if v1+v2>8:
                continue
            #print(k1,v1,k2,v2)
            if k1+k2 in dp:
                new[k1+k2]=min(v1+v2, dp[k1+k2])
            else:
                new[k1+k2]=v1+v2
        for k, v in L:
            if k*N in dp:
                new[k*N]= min(v+1, dp[k*N])
            else:
                new[k*N]= v+1

            if k+N in dp:
                new[k+N]= min(v+1, dp[k+N])
            else:
                new[k+N]= v+1

            if not k%N:
                if k//N in dp:
                    new[k//N]= min(v+1, dp[k//N])
                else:
                    new[k//N]= v+1
        dp={}
        for k, v in new.items():
            dp[k]=v
    if number not in dp:
        return -1

    return dp[number]
def solution(relation):
    rows = len(relation)
    cols = len(relation[0])
    # print(f"rows: {rows} cols: {cols}")

    candidates = []  # 후보키가 될 수 있는 요소들
    for i in range(1, cols + 1):
        candidates.extend(combi(range(cols), i))
    # print(candidates)

    # 유일성 test
    unique = []
    for keys in candidates:
        keycheck = set()
        for row in range(rows):
            temp = ""
            for col in keys:
                temp += relation[row][col]
            keycheck.add(temp)
        if len(keycheck) == rows:
            unique.append(keys)

    for i in range(len(unique)):
        unique[i] = list(unique[i])
    # print(unique)
    answer = set()

    # 최소성 test
    for i in range(len(unique)):
        for j in range(i + 1, len(unique)):
            temp2 = []
            for el in unique[i]:
                if el in unique[j]:
                    temp2.append(el)
            if len(temp2) == len(unique[i]):
                answer.add(tuple(unique[j]))

    print(len(unique) - len(answer))
    return len(unique) - len(answer)
from copy import deepcopy
from itertools import combinations as combi
def hunt(h,c):
    for i in range(1,d+1):
        for dx in range(-i,i+1):
            x,y=h+dx,n-(i-abs(dx))
            if 0<=x<m and 0<=y<n and c[y][x]:return x,y
def sol(archers):
    c=deepcopy(b)
    ret=0
    for _ in range(n):
        e=set(hunt(h,c)for h in archers)-{None};ret+=len(e)
        for x,y in e:c[y][x]=0
        for y in range(n-1,0,-1):c[y]=c[y-1][:]
        c[0]=[0]*m
    return ret
n,m,d=map(int,input().split())
b=[[*map(int,input().split())]for _ in range(n)]
print(max(sol(i)for i in combi(range(m),3)))
Exemple #22
0
def calc_possible(data, current_index, pre_size):
    return list(
        map(lambda x: x[0] + x[1],
            combi(data[current_index - pre_size:current_index], 2)))
Exemple #23
0
def all_non_empty_subsets( set ) :
	subs = []
	for i in range( len( set ) ) :
		subs += [ list( s ) for s in combi( set, i+1 ) ]
	return subs
Exemple #24
0
import sys
from itertools import combinations_with_replacement as combi

N, M = map(int, input().split())
x = list(map(int, input().split()))
x.sort()
ans_lst = sorted(set(list(combi(x, M))))

for i in ans_lst:
    print(*i)
Exemple #25
0
def diff_population(area1, area2):
    global m
    if connected(area1) and connected(area2):
        s = 0
        for i in range(len(area1)):
            s += P[area1[i]]
        for i in range(len(area2)):
            s -= P[area2[i]]
        s = abs(s)
        if m > s:
            m = s
    return m


if __name__ == "__main__":
    N = int(input())
    P = [0] + list(map(int, input().split()))
    G = [[] for _ in range(N + 1)]
    for i in range(1, N + 1):
        u, *v = map(int, input().split())
        G[i].extend(v)

    for i in range(1, N // 2 + 1):
        for area1 in combi(range(1, N + 1), i):
            area2 = [i for i in range(1, N + 1) if i not in area1]
            diff_population(area1, area2)
    if m == sys.maxsize:
        print(-1)
    else:
        print(m)
Exemple #26
0
from itertools import combinations as combi
n, s = map(int, input().split())
L = [*map(int, input().split())]
ans = 0
for i in range(1, n + 1):
    for ls in combi(L, i):
        if sum(ls) == s:
            ans += 1
print(ans)
Exemple #27
0
from itertools import combinations as combi
import sys
read = sys.stdin.readline

N, limit = map(int, read().rstrip().split())
cards = list(map(int, read().rstrip().split()))

cards_sum = set(map(sum, list(combi(cards, 3))))

diff = float('inf')
res = 0
for s in cards_sum:
    tmp = limit - s
    if tmp >= 0 and tmp < diff:
        diff = tmp
        res = s

    if res == limit:
        break

print(res)
Exemple #28
0
# Problem [4012] : [모의 SW 역량테스트] 요리사

from itertools import combinations as combi
import sys
sys.stdin = open('input.txt')


if __name__ == '__main__':
    T = int(input())
    for tc in range(1, T+1):
        N = int(input())
        D = [list(map(int,input().split())) for _ in range(N)]
        m = float('inf')
        food = list(combi(range(N),N//2))

        for food1 in food:
            food2 = list()
            for n in range(N):
                if n not in food1:
                    food2.append(n)
            s1 = 0
            for i in range(N//2):
                for j in range(i+1,N//2):
                    s1 += D[food1[i]][food1[j]] + D[food1[j]][food1[i]]
            s2 =0
            for i in range(N//2):
                for j in range(i+1,N//2):
                    s2 += D[food2[i]][food2[j]] + D[food2[j]][food2[i]]
            m = min(m,abs(s2-s1))
        print('#{} {}'.format(tc, m))
Exemple #29
0
import sys
input = sys.stdin.readline
from itertools import combinations as combi

ti_list = []

for _ in range(9):
    x = int(input())
    ti_list.append(x)

ti_list = combi(ti_list, 7)

for el in ti_list:
    total = sum(el)
    if total == 100:
        break

for i in el:
    print(i)
Exemple #30
0
# 오 저 ceil 함수 안쓰는데 저도 쓰면 좋겠네요 ㅋㅋㅋ 감사여
import sys

input = sys.stdin.readline
from itertools import combinations as combi  # 전 이렇게 축약해요

N, M = map(int, input().split())

numberList = [*map(int, input().split())]

mylist = combi(numberList, 3)
sumList = []
for el in mylist:
    a = sum(el)
    sumList.append(a)

sumList = set(sumList)
sumList2 = list(sumList)
sumList2 = sorted(sumList2)

for i in range(len(sumList2)):
    if (sumList2[-1] < M):
        print(sumList2[-1])
        break
    if (int(sumList2[i]) > M):
        print(sumList2[i - 1])
        break

for i in range(N - 2):  # nCr 고르기 다중포문으로 고르는 법도 알아두시면 좋아요
    for j in range(i + 1, N - 1):
        for k in range(j + 1, N):
Exemple #31
0
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return iter_chain.from_iterable(combi(s, r) for r in range(len(s)+1))
Exemple #32
0
import random
from itertools import combinations as combi

L=[0]*9
for i in range(10):
    L[i]=random.randint(1,10)

for i in range(1,3):
    M=L[:]
    for tst in combi(L,i):
        for nm in tst:
            M[nm]=0
    mp= [for el in M]
    


import sys; input= lambda: sys.stdin.readline().rstrip()
mp= [[*map(int, input().split())] for _ in range(3)]
ans=0
def backtrack():
    flag=False
    for i in range(3):
        for j in range(3):
            if not mp[i][j]:
                flag=True
                chk=[False]*10
                for r in range(3):
                    chk[mp[r][j]]=True
                for c in range(3):
                    chk[mp[i][c]]=True
                for k in range(1,10):