コード例 #1
0
ファイル: 01.py プロジェクト: jinn2u/algorithm
def solution(numbers):
    ans = []
    answer = list(cb(numbers, 2))
    for i in answer:
        if sum(i) not in ans:
            ans.append(sum(i))
    return sorted(ans)
コード例 #2
0
def fun_cnnreshape(datain):
    c = int(datain.shape[1] / 4)
    disl_num = int((1 + (1 + 4 * c)**(0.5)) / 2)
    print(disl_num)
    r_all = datain[:, 0:c]
    a_all = datain[:, c:c * 2]
    g_all = datain[:, c * 2:c * 3]
    t_all = datain[:, c * 3:c * 4]

    in_val = numpy.zeros((datain.shape[0], disl_num, disl_num, 4))

    ind = numpy.array(list(cb(list(range(disl_num)), 2)))
    ind1 = ind
    ind2 = ind[:, [1, 0]]
    ind = numpy.concatenate((ind1, ind2), axis=0)
    ind = numpy.unique(ind, axis=0)
    ind = numpy.delete(ind, numpy.where(ind[:, 0] == ind[:, 1]), axis=0)

    for q0 in range(datain.shape[0]):
        for q1 in range(c):
            in_val[q0, ind[q1, 0], ind[q1, 1], 0] = a_all[q0, q1]
            in_val[q0, ind[q1, 0], ind[q1, 1], 1] = r_all[q0, q1]
            in_val[q0, ind[q1, 0], ind[q1, 1], 2] = g_all[q0, q1]
            in_val[q0, ind[q1, 0], ind[q1, 1], 3] = t_all[q0, q1]

    return in_val
コード例 #3
0
 def findNumOfValidWords(self, words: List[str],
                         puzzles: List[str]) -> List[int]:
     cnt = collections.Counter(''.join(sorted(set(w))) for w in words)
     return [
         sum(cnt[''.join(sorted(s + (p[0], )))] for l in range(len(p))
             for s in cb(p[1:], l)) for p in puzzles
     ]
コード例 #4
0
ファイル: 15686.py プロジェクト: LastCow9000/Algorithms
def find_distance(home_list, ck_list, cnt):
    picked_ck = []
    ck_dis_list = []

    # 조합으로 cnt 개수만큼 뽑는 경우의 수 구하기
    for ck in cb(ck_list, cnt):
        picked_ck.append(list(ck))

    # 경우의 수마다 치킨거리 구하기
    for position in picked_ck:

        # N은 50이 최대이므로 50 * 50 = 2500이 최대거리이므로 최소거리를 찾기 위해 초기값 세팅
        ck_dis = {k: 3000 for k in range(len(home_list))}

        for x, y in position:
            for idx, (h_x, h_y) in enumerate(home_list):
                dis = abs(h_x - x) + abs(h_y - y)

                if ck_dis[idx] > dis:  # 최소값 갱신하면서 치킨 거리 구하기
                    ck_dis[idx] = dis

            city_dis = 0
            for k, v in ck_dis.items():
                city_dis += v

            ck_dis_list.append(city_dis)  # 경우의 수에 따른 도시 거리를 구해서 추가

    return ck_dis_list
コード例 #5
0
def combinations_calculator(matrix):
    """ Give a number (ie a name) to each row of matrix
        Search all the possible combinations of rows and save that in list of names (ie list of numbers)
        Create each different matrix only once in the resolution function to save space"""

    # Give a name to each row of the matrix
    names = []
    for i in range(len(matrix)):
        names.append(i)

    # Search all the possible combinations
    combinations = list(cb(names, len(matrix[0])))

    # If the matrix is square (ie n lines, n+1 columns with the solution column), combination = []
    if combinations == []:

        t = ()
        for i in range(len(matrix)):
            t += (i, )
        combinations.append(t)

        return combinations

    # Return a list of every combinations
    return combinations
コード例 #6
0
ファイル: pyex_newgk.py プロジェクト: ccszwg/pyexam
 def count_kmset_zycount(self, zydf):
     # count zy number for kmset
     zyfield=list(zydf.columns.values)
     zyfield.remove('zyclass')
     zy_xk_series = zydf[zyfield].sum()
     xk_comb_dict = {}
     self.__km_cb = cb(self.km_name_pinyin_first, 3)
     for xs in self.__km_cb:
         zynum = zy_xk_series['xk0']
         xss = ''.join(xs)
         for t in zy_xk_series.index:
             if '_' not in t:
                 continue
             xktype = t[0:t.find('_')]
             xksubs = t[t.find('_')+1:]
             if xktype in 'xk1,xk2,xk3':
                 # print(xksubs, xss)
                 if xksubs in xss:
                     # print(xss,t,zy_xk_series[t])
                     zynum += zy_xk_series[t]
             elif xktype in 'xk21, xk31':
                 if len(set(xs) & set(xksubs)) > 0:
                     # print(xs, t, zy_xk_series[t])
                     zynum += zy_xk_series[t]
             xk_comb_dict.update({xss: zynum})
         # print('km-{} zycount={}'.format(xs, zynum))
     return xk_comb_dict
コード例 #7
0
ファイル: pyex_newgk.py プロジェクト: ccszwg/pyexam
    def __init__(self):
        self.xkfile = d_path + 'xk/xk_type_zycount.csv'

        self.xk_type_name = ['xk0', 'xk1', 'xk2', 'xk3', 'xk21', 'xk31']
        self.xk_type_label = ['0', '1', '2', '3', '1/2', '1/3']
        self.xk_class_name = None

        self.km_name_pinyin_first = ['d', 'h', 'l', 's', 'w', 'z']
        self.km_name_chinese_string = ['地理', '化学', '历史', '生物', '物理', '政治']
        self.__km_cb = cb(self.km_name_pinyin_first, 3)
        self.km_comb_ccname_dict = {''.join(k): ''.join(
            [self.km_name_chinese_string[self.km_name_pinyin_first.index(s)] for s in k])
            for k in self.__km_cb}

        self.df_xkdata_junshi = None
        self.df_total_count = None
        self.df_class_type_count = None
        self.df_class_type_count_bk = None
        self.df_comb_st = None

        self.num_zy_total = None
        self.num_zy_total_bk = None
        self.num_kmcomb_count_dict = {}
        self.num_kmcomb_count_dict_bk = {}

        self.pre_do()
def mySolution(numbers):
    cnt = 0
    uniqueNumToCalc = list()
    for numOfDigits in range(1, len(numbers) + 1):
        combs = set([
            str((''.join(item)))
            for item in list(cb([c for c in numbers], numOfDigits))
        ])
        #         print('='*50)
        #         print('combs:')
        #         print(combs)
        for c in combs:
            #             perms = set([int(''.join(item)) for item in list(pm(c))])
            perms = set(list(pm(c)))
            #             print('-'*25)
            #             print('set perms')
            #             print(perms)
            for perm in perms:
                x = int(''.join(perm))
                uniqueNumToCalc.append(x)
    uniqueNumToCalc = set(uniqueNumToCalc)
    for x in uniqueNumToCalc:
        #         print('x:', x, end=' ')
        if isPrime(x):
            cnt += 1


#             print(f'>>> prime <<< cnt: {cnt}')
#         else:
#             print(f'...   no  ... cnt: {cnt}')
    print('*/\*' * 25)
    print('cnt:', cnt)
    return cnt
コード例 #9
0
def fun_cnnreshape(datain):
    col_size = int(datain.shape[1]/3)
    r_val    = datain[:,0:col_size]
    a_val    = datain[:,col_size:2*col_size]
    t_val    = datain[:,2*col_size:]
    #print(a_val.shape)
    #print(r_val.shape)
    #print(t_val.shape)
    ind   = numpy.array(list(cb(list(range(col_size)),2)))
    ind1  = ind
    ind2  = ind[:,[1,0]]
    ind = numpy.concatenate((ind1,ind2),axis=0)
    ind = numpy.unique(ind,axis=0)

    #print(ind.shape)

    azimuth0     = numpy.reshape(a_val[:,ind[:,0]],(datain.shape[0],col_size,col_size,1))
    azimuth1     = numpy.reshape(a_val[:,ind[:,1]],(datain.shape[0],col_size,col_size,1))
    azimuth_all  = numpy.concatenate((azimuth0,azimuth1),axis=3)

    radial0      = numpy.reshape(r_val[:,ind[:,0]],(datain.shape[0],col_size,col_size,1))
    radial1      = numpy.reshape(r_val[:,ind[:,1]],(datain.shape[0],col_size,col_size,1))
    radial_all   = numpy.concatenate((radial0,radial1),axis=3)

    rotation0    = numpy.reshape(t_val[:,ind[:,0]],(datain.shape[0],col_size,col_size,1))
    rotation1    = numpy.reshape(t_val[:,ind[:,1]],(datain.shape[0],col_size,col_size,1))
    rotation_all = numpy.concatenate((rotation0,rotation1),axis=3)  

    datain       = numpy.concatenate((radial_all,azimuth_all,rotation_all),axis=3)

    return datain
コード例 #10
0
def main():
    n = int(si())
    nn = n // 2
    synergy = []
    for _ in range(n):
        l = [int(e) for e in si().split()]
        synergy.append(l)

    members = [i + 1 for i in range(n)]
    cases = cb(members, nn)
    md = 10000
    for c in cases:
        cl = list(c)
        cs, ol = set(cl), []

        for member in members:
            if member not in cs:
                ol.append(member)

        t1, t2 = 0, 0
        for i in range(nn - 1):
            for j in range(i + 1, nn):
                t1 += synergy[cl[i] - 1][cl[j] - 1]
                t1 += synergy[cl[j] - 1][cl[i] - 1]
        for i in range(nn - 1):
            for j in range(i + 1, nn):
                t2 += synergy[ol[i] - 1][ol[j] - 1]
                t2 += synergy[ol[j] - 1][ol[i] - 1]
        md = min(md, abs(t1 - t2))
    print(md)
コード例 #11
0
def solution(orders, course):
    u_menus = set(''.join(orders))

    answer = []
    for n_menu in course:
        max_cnt = 2
        new_comb = []
        combs = cb(u_menus, n_menu)
        for comb in combs:
            cnt = 0
            for order in orders:
                found = False
                for menu in comb:
                    if me
                if len([menu for menu in comb if menu in order]) == len(comb):
                    cnt += 1
                    found = True
                if found:
                    if cnt > max_cnt:
                        max_cnt = cnt
                        new_comb = [comb]
                    elif cnt == max_cnt:
                        new_comb.append(comb)

        for comb in new_comb:
            answer.append(''.join(sorted(comb)))

    answer.sort()
    return answer
コード例 #12
0
def solution(first_line, second_line):
    n, m = map(int, first_line.split())
    gram = list(map(int, second_line.split()))

    x = cb(gram, 2)
    list_gram = [i + j for i, j in x]
    n_count = len(list(filter(lambda x: x <= n, list_gram)))
    return max(n_count)
コード例 #13
0
def equal_multiset(lst):
    half = sum(lst) // 2
    for x in range(1, len(lst)):
        for y in cb(lst, x):
            if half == sum(y):
                return True

    return False
コード例 #14
0
def closestNumbers(arr):
    combin = [x for x in cb(sorted(arr), 2)]
    res = []
    for x in combin:
        if x[1] - x[0] == min(y[1] - y[0] for y in combin):
            res.append(x[0])
            res.append(x[1])
    return res
コード例 #15
0
def alternate(s):
	rest_aplha = sorted([sorted(x) for x in cb(set(s),2)])
	res =[]
	for x in rest_aplha:
		temp = ''.join(alphabet for alphabet in s if alphabet in x)				
		if ((x[0]+x[1])*len(temp)) [:len(temp)]==temp or ((x[1]+x[0])*len(temp)) [:len(temp)]==temp:
			res.append(temp)
	return len(max(res, key=len)) if res else 0
def MultiplyAllSubcombs(Combinations: 'list', Size: 'int'):
    '''
    Multiplies all subcombinations in combimation
    '''
    SubCombinations = [[j for j in cb(Combinations, i)] for i in range(Size)]
    result = list()
    for i, sublist in enumerate(SubCombinations):
        result.append(sum([prod(subtuple) for subtuple in sublist]))
    return result
コード例 #17
0
def solution(arr, K):
    #여기에 코드를 작성해주세요.
    answer = 0
    lst = list(cb(arr, 3))

    for ls in lst:
        if not sum(ls) % K:
            answer += 1
    return answer
コード例 #18
0
def flower_cost(n, maps):
    min_cost = max_cost

    comb_list = list(cb(range(n * n), 3))

    for flowers in comb_list:
        min_cost = min(min_cost, solve(flowers))

    return min_cost
コード例 #19
0
ファイル: makeNum.py プロジェクト: jaeby99/Practice
def solution(nums):
    answer = 0
    for x in cb(nums, 3):
        num = sum(x)
        for d in range(2, num):
            if num % d == 0:
                break
        else:
            answer += 1
    return answer
コード例 #20
0
def solution(first_line, second_line):
    first_line = int(first_line)
    second_line = list(map(int, second_line.split()))
    answer = [0] * (sum(second_line) + 1)
    for i in range(1, first_line + 1):
        val = list(cb(second_line, i))
        val = [sum(j) - 1 for j in val]
        for j in val:
            answer[j] = 1
    return answer.index(0) + 1
コード例 #21
0
def solution(n, m, matrix):
    home, chicken = location(n, matrix)
    answer = []
    for chic in cb(chicken, m):
        min_val = 0
        for ho in home:
            min_val += min([distance(i, ho) for i in chic])
        answer.append(min_val)

    return min(answer)
コード例 #22
0
def solution(nums):
    answer = 0
    for i in cb(nums, 3):
        res = sum(i)
        for j in range(2, res):
            if res%j == 0:
                break;
        else:
            answer += 1
    return answer
コード例 #23
0
def solution(nums):
    ans = 0
    for c in cb(nums,3):
        cs = sum(c)
        for i in range(2,cs):
            if cs%i==0:
                break
        else:
            ans+=1
    return ans
コード例 #24
0
def cbSolution(nums):
    from itertools import combinations as cb
    answer = 0
    for a in cb(nums, 3):  # combinations 모듈을 통해 쉽게 가능한 모든 조합 생성 가능
        cand = sum(a)
        for j in range(2, cand):  # 1은 소수니까 제외하고, 2 ~ n까지 해당수를 나누면서 소수여부 판별
            if cand % j == 0:
                break  # 0이되면 소수가 아니므로 break로 넘어감
        else:  # 소수라면 answer 카운트 1증가
            answer += 1
    return answer
コード例 #25
0
def solution(nums):
    from itertools import combinations as cb
    answer = 0
    for a in cb(nums, 3):
        cand = sum(a)
        for j in range(2, cand):
            if cand % j == 0:
                break
        else:
            answer += 1
    return answer
コード例 #26
0
 def readBinaryWatch(self, num):
     t = [8, 4, 2, 1, 32, 16, 8, 4, 2, 1]
     ret = []
     for i in cb(range(10), num):
         h, m = 0, 0
         for j in i:
             if j < 4: h += t[j]
             else: m += t[j]
         if h >= 12 or m >= 60: continue
         ret.append(str(h) + ':' + str(m).zfill(2))
     return ret
コード例 #27
0
def solution(nums):
    answer = 0
    for a in cb(nums, 3):
        can = sum(a)
        for j in range(2, can):
            if can % j == 0:
                break
        else:
            answer += 1

    return answer
コード例 #28
0
def sol(nums):
    from itertools import combinations as cb
    answer = 0
    for x in cb(nums, 3):
        sumx = sum(x)
        for i in range(2, sum(x)):
            if sumx % i == 0:
                break
        else:
            answer += 1
    return answer
コード例 #29
0
def removNb(n):
    l = []
    possible_a_b = list(cb(range(1, n + 1), 2))

    for i, j in possible_a_b:
        if i * j == sum([num for num in range(n + 1)
                         if num != i and num != j]):
            l.append((i, j))
            l.append((j, i))

    return l
コード例 #30
0
ファイル: ap.py プロジェクト: ikjyot/AprioriPython
def calc_support(ip_list):
    count_lr = 0
    for i in trans_list:
        temp_list_lr = []
        for j in cb(i, len(ip_list)):
            temp_list_lr.append(list(j))
        for k in temp_list_lr:
            if set(ip_list) == set(k):
                count_lr += 1
            else:
                continue
    return count_lr
コード例 #31
0
ファイル: word2vec.py プロジェクト: cligs/toolbox
def eval(EvalFile, ModelFile): 
    # Load the list of pairs and build a list of grouped quadrupels from it.
    with open(EvalFile, "r") as InFile: 
        AllItems = pd.read_csv(InFile,
                            index_col=0,
                            header=0,
                            sep=",")
        #print(AllItems)
        Types = list(set(list(AllItems.index.values)))
        #print(Types)
        AllQuads = []
        for Type in Types:
            Pairs = []
            Items = AllItems.loc[Type,:]
            #print(Items)
            #print(len(Items))
            for i in range(0,len(Items)): 
                Pairs.append([Items.iloc[i,0], Items.iloc[i,1]])
            #print(Pairs)
            Quads = cb(Pairs, r=2)
            #print(Quads)
            AllQuads.append(Quads)
        ListAllQuads = []
        for Type in AllQuads:
            for Quad in Type:
                ListAllQuads.append([Quad[0][0], Quad[0][1], Quad[1][0], Quad[1][1]])
        #print(ListAllQuads)
    # Evaluate the model performance on the quadrupels                   
    Model = gensim.models.Word2Vec.load(ModelFile)
    Correct = 0
    Items = 0
    for Quad in ListAllQuads: 
        try: 
            Actual = Model.most_similar(positive=[Quad[1], Quad[2]], 
                                        negative=[Quad[0]], 
                                        topn=1)
        except: 
            print("Oh-ooh! (Probably a missing vocabulary item)")
        if Quad[3] == Actual[0][0]: 
            Correct +=1
            print("OK!", Quad[1]+"+"+Quad[2]+"-"+Quad[0]+"\t= "+Quad[3]+" : "+Actual[0][0])
        else: 
            print("ERREUR!", Quad[1]+"+"+Quad[2]+"-"+Quad[0]+"\t= "+Quad[3]+" : "+Actual[0][0])
        Items+=1
    print(str(Correct)+"/"+str(Items)+"="+str(Correct/Items))