def populate_ad_to_img_dicts(self): # Key: Ad filepath # Value: List of image filepaths self.ad_to_img_pairs = OrderedDict() self.ad_to_img = OrderedDict() # Looping over ad filenames for date in os.listdir(self.root): for hour in os.listdir(join(self.root, date)): for ad_filepath in os.listdir(join(self.root, date, hour)): imgs = self.imgs_from_ad( join(self.root, date, hour, ad_filepath)) # Check if valid ad if imgs: # Add to dict list of images self.ad_to_img[ad_filepath] = [ join(self.root, date, hour, ad_filepath, x) for x in imgs ] # Add to dict list of image pairs self.ad_to_img_pairs[ad_filepath] = list( map( lambda x: (join(self.root, date, hour, ad_filepath, x[0]), join(self.root, date, hour, ad_filepath, x[1])), list(combs(imgs, 2))))
def solve_grid(self): self.solutions = [] # Generate coords of free spaces in the grid, then brute force combinations of those # - N choose R where N is the set of free coordinates, and R = self.add free_coords = [] for i in range(len(self.grid)): # For each row for j in range(len(self.grid)): # For each cell in the row if self.grid[i][j] == 0: # There is no watcher in the cell free_coords.append( [i, j]) # This cell can potentially have a watcher in it num_solutions_found = 0 for added_coords in combs( free_coords, self.add): # All combinations of possible watchers # Create the board to be tested to_be_tested = self.make_grid(self.gridsize, list(added_coords) + self.coords) if self.grid_is_valid(to_be_tested): # Check validity of board self.solutions.append(to_be_tested) num_solutions_found += 1 return self.solutions
def solution(num_buns, num_required): buns = [[] for i in range(num_buns)] if num_required == 0: return buns start = 0 for c in combs(buns, num_buns - num_required + 1): for item in c: item.append(start) start += 1 return buns
def find_counterfeit(coins): good, found = set(), set() for i, j in combs(range(len(coins)), 2): if not balanced(coins[i], coins[j]): found.add(i) found.add(j) else: good.add(i) good.add(j) result = [x for x in found.difference(good)] return result[0] if result else None
def get_aspects(jdate, l_bodies=bodies): """ Return a structured array of aspects and orb Return None if there's no aspect """ bodies_id = l_bodies['id'] return array([ get_aspect(jdate, *comb) for comb in combs(bodies_id, 2) if get_aspect(jdate, *comb) is not None ], dtype=[('body1', 'i4'), ('body2', 'i4'), ('i_asp', 'i4'), ('orb', 'f4')])
def solve_r(rules, a, L): positions = range(L) ri = 0 for cp in combs(positions, rules[ri][1]): consistent = True for p in range(L): if p in cp: if a[p][rules[ri][0][p]] == 'N': consistent = False break else: if a[p][rules[ri][0][p]] == 'E': consistent = False break if not consistent: break if not consistent: continue saved_a = copy.deepcopy(a) for p in range(L): if p in cp: a[p][rules[ri][0][p]] = 'E' for d in range(10): if d != rules[ri][0][p]: a[p][d] = 'N' else: a[p][rules[ri][0][p]] = 'N' for ri2 in range(len(rules)): if ri != ri2: count_wrong, count_correct = 0, 0 for p in range(L): if a[p][rules[ri2][0][p]] == 'E': count_correct += 1 elif a[p][rules[ri2][0][p]] == 'N': count_wrong += 1 condition1 = count_correct > rules[ri2][1] condition2 = count_wrong > L - rules[ri2][1] if condition1 or condition2: consistent = False break if not consistent: a = saved_a continue saved_rule = rules.pop(ri) if len(rules): ans = solve_r(rules, a, L) if ans[1]: return ans else: answer = [] for p in range(L): for d in range(10): if a[p][d] == 'E' or a[p][d] == '?': answer.append(str(d)) break return [''.join(answer), True] rules.insert(ri, saved_rule) a = saved_a return [str(0), False]
def solve(upper_limit: int = 28123) -> int: prime_lst = lib.primes.prime_list(upper_limit) abundants = [] can_sum = set() res = 0 for num in range(1, upper_limit + 1): if is_abundant(num, prime_lst): abundants.append(num) can_sum.add(num*2) for comb in combs(abundants, 2): can_sum.add(sum(comb)) for num in range(1, upper_limit + 1): if num not in can_sum: res += num return res
def get_ns_similarity(self): if not self.ns_names: self.get_n_ns() if not self.ips: self.ips = self.__get_rr('A', ttl=True) if len(self.ns_names) > 2: similarities = list() all_combs = combs(self.ns_names, 2) for comb in all_combs: similarities.append(similarity(*comb)) return sum(similarities) / len(similarities) elif len(self.ips) == 0 or len(self.ns_names) == 0: return 0.0 else: return 1.0
def sol(ps: int = 5): global P, PS, BIG_P #print(P) two_cands = [] for c in tqdm(combs(P, 2)): if in_primes(*c): two_cands.append(set(c)) old_arr = two_cands[:] print(old_arr) for i in range(3, ps + 1): if i == 5: print(old_arr) print(i) arr = go_over(old_arr) old_arr = arr[:] min_s = float("inf") for t in arr: min_s = min(min_s, sum(t)) return min_s
def sol(z: int) -> str: global P, PS #cache = dict() for i in tqdm(range(len(P))): digits = len(P[i]) for j in range(1, digits): perms = combs(range(digits), j) for p in perms: fam = 0 consider = False sol = [] for n in range(0, 10): s = replace(P[i], p, str(n)) contains = (r := str(int(s))) in PS if P[i] == r: consider = True continue if contains: sol.append(r) fam += 1 if consider and fam + 1 == z: print((P[i]), p, fam)
def combine(self, n: int, k: int) -> List[List[int]]: # def dfs(s, e): # if s < e: # result.append([s, e]) # return # else: # for i in range(1, n+1): # for j in range(i, n): # dfs(i, j+1) # result = [] # if n - k > 1: # dfs(0, 0) # elif n - k == 1: # result.append([n]) # result.append([k]) # elif n - k == 0: # result.append([n]) # return result return list(combs(range(1, n + 1), k))
def solution(relation): n_row = len(relation) n_col = len(relation[0]) candidates = [] for i in range(1, n_col + 1): # extend는 iterable의 각 항목을 넣는다. candidates.extend(combs(range(n_col), i)) final = [] for keys in candidates: tmp = [tuple([item[key] for key in keys]) for item in relation] if len(set(tmp)) == n_row: final.append(keys) answer = set(final) for i in range(len(final)): for j in range(i + 1, len(final)): # intersection을 이용해서 최소성을 만족하는지 확인 if len(final[i]) == len(set(final[i]).intersection(set(final[j]))): # discard는 제거할 것이 없어도 실행 가능. remove와 차이점 answer.discard(final[j]) return len(answer)
def get_confusion_matrix(src, corr, alignments, confusion_dict_pos, confusion_dict_paths): assert len(src) == len(corr) == len(alignments), "len en: " + str(len(src)) + " len of corr: " + \ str(len(corr)) + " len all: " + str(len(alignments)) def strip_direction(x): return x.split("_")[0] for i in range(len(src)): src_n, src_g = conll2graph(src[i]) corr_n, corr_g = conll2graph(corr[i]) alignment = alignments[i] # Simplify the alignment to a set of one-to-one pairs one_to_one = [] for k, v in alignment.items(): if k == "X": # Do not analyse stuff added on the Ko side for now continue head = k tail = str(highest_or_none(v, corr_g)) one_to_one.append((head, tail)) # POS confusion dict for pair in one_to_one: head, tail = pair # Skip technical additional nodes if "." in head: continue try: src_pos = src_n[head]["pos"] except KeyError: print(i, src[i]) continue if tail == "None": corr_pos = "None" else: corr_pos = corr_n[tail]["pos"] corr_pos = corr_n[tail]["pos"] if src_pos not in confusion_dict_pos: confusion_dict_pos[src_pos] = Counter() confusion_dict_pos[src_pos][corr_pos] += 1 # Path confusion dict for pair in combs(one_to_one, 2): (src_head, corr_head), (src_tail, corr_tail) = pair # Skip technical additional nodes if "." in head: continue src_path_arr = get_path(src_head, src_tail, src_g) if len(src_path_arr) > 1: continue src_path = strip_direction(src_path_arr[0]) if corr_head == corr_tail: corr_path = "Nodes collapsed" elif corr_head == "None" and corr_tail == "None": corr_path = "Both endpoints unaligned" elif corr_head == "None" or corr_tail == "None": corr_path = "One endpoint unaligned" else: corr_path_arr = get_path(corr_head, corr_tail, corr_g) corr_path = "->".join(list(map(strip_direction, corr_path_arr))) if src_path not in confusion_dict_paths: confusion_dict_paths[src_path] = Counter() confusion_dict_paths[src_path][corr_path] += 1
if l[j][i] == 0: continue for k in range(j + 1, N): if l[k][i] == 0 or l[k][j] == 0: continue ans += 1 print(f'#{tc} {ans}') print(l) # 왜애애애애애애애애애앤지 모르겠지만 이게 더 빨라서 통과가 된다. # 반복회수는 이게 더 만을텐데 배열의 인덱싱이 더 오래 걸려서 그런갑다.. # 테케는 1000개 N의 최대는 50개 # 각 인덱스가 최대 50개 인데 이게 좀 더 걸리나보다 # 찾아보니까 그냥 bool 배열을 만들어서 인덱싱 한사람도 있고 dfs쓴사람도 있다. from itertools import combinations as combs T = int(input()) for tc in range(1, T + 1): N, M = map(int, input().split()) l = [[] for _ in range(N)] for _ in range(M): tmp = sorted(list(map(int, input().split()))) l[tmp[0] - 1].append(tmp[1] - 1) ans = 0 for comb in combs(range(N), 3): if comb[1] in l[comb[0]] and comb[2] in l[comb[0]] and comb[2] in l[ comb[1]]: ans += 1 print(f'#{tc} {ans}')
def in_primes(*args) -> bool: string = lambda num1, num2: int(str(num1) + str(num2)) in PS and int( str(num2) + str(num1)) in PS return all(string(*c) for c in combs(args, 2))
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. """ from itertools import combinations_with_replacement as combs def is_palin(n): return str(n) == str(n)[::-1] products = (x*y for x,y in combs(range(100,1000),2)) print( max (x for x in products if is_palin(x) ) )
"valentine's", "summer", "wedding", "gala", "beautician", "hunter", ] team_damage = "16,000" parses = ["180", "120", "60"] coab_combos = ["_"] + [ "".join(coabs) for x in range(1, len(coab_sort_key) + 1) for coabs in combs(coab_sort_key, x) ] def copy_parses(): return {"180": {}, "120": {}, "60": {}}.copy() def coab_sort(coabs): if "none" == coabs.lower(): return "_" else: return "".join( sorted(coabs, key=lambda c_list: [coab_sort_key.index(c) for c in c_list]))
from itertools import combinations as combs from functools import reduce in_file = open('input_1.txt', 'r') # in_file = open('test_1.txt', 'r') numList = map(lambda x: int(x[:-1]), in_file.readlines()) target = 2020 numsList = combs(numList, 3) for nums in numsList: if sum(nums) == target: print(reduce(lambda x, y: x * y, nums, 1))
from itertools import combinations_with_replacement as combs s, k = input().split() print(*[''.join(p) for p in combs(sorted(s), int(k))], sep='\n')
thetapred = graddes[0] pred = surpred(xlin1int, thetapred) scoreint = predicttrain(pred) dif = scoreint-scorelin print (i,j), " ", scoreint, " ", round(dif*m) if dif > 0: posints.append((i,j)) print posints # interactionterms() # Note this takes about 3 min print "Time elapsed:", time() - start intlist = list(combs(range(2, 13), 2)) alpha = 0.2 niter = 20000 lam = 0 # This was a first implementation of what later became titanlogregCV() for (i, j) in intlist: tempds = logreg_prepdata(dba, [(i, j)])[0] tempds = Datasets(tempds) trainds = tempds.train() y = trainds[0::, 0] x = trainds[0::, 1::] graddes = gradientdescent(x, y, alpha, niter, lam, logreg=True)
from itertools import combinations_with_replacement as combs check = [1] * 1001 check[0], check[1] = 0, 0 prime = [] for n in range(2, 1000): if check[n]: prime.append(n) for i in range(n, 1000, n): check[i] = 0 dict_Vino = {} for comb in combs(prime, 3): if sum(comb) in dict_Vino: dict_Vino[sum(comb)] += 1 else: dict_Vino[sum(comb)] = 1 T = int(input()) for tc in range(1, T + 1): print(f'#{tc} {dict_Vino[int(input())]}')
from itertools import combinations as combs T = int(input()) for tc in range(1, T + 1): numbers = list(map(int, input().split())) sum_ = [] for comb in combs(numbers, 3): sum_.append(sum(comb)) sum_ = list(set(sum_)) sum_.sort(reverse=True) print(f'#{tc} {sum_[4]}')
def trust_eval(graph, totedges): trusted = 0 not_trusted = 0 for rev, rwe, trust in graph.edges(data=True): #set to true to guarantee 3-tuple return value if trust['weight'] == 1: trusted += 1 if trust['weight'] == -1: not_trusted += 1 print("Amount Trust Edges: ", trusted) print("Amount Distrust Edges: ", not_trusted) p_pos = round(trusted/totedges, 4) p_neg = round(1 - (trusted/totedges), 4) print("P(positive edge) = p: ", p_pos) print("P(negative edge) = 1 - p: ", p_neg) #expected and actual distributions triangles = nx.triangles(graph) t_count = sum(triangles.values())/3 print("Amount of Triangles: ", t_count) #expected distribution print("\n-Expected Distribution-") print("Type\t|\tPercent\t|\tNumber") TTT_percent = round((p_pos ** 3) * 100,1) TTT_num = round((t_count * TTT_percent)/100,1) print("TTT\t|\t" + str(TTT_percent) + "\t|\t" + str(TTT_num)) TTD_percent = round((p_pos ** 2 * p_neg * 3) * 100,1) TTD_num = round((t_count * TTD_percent)/100,1) print("TTD\t|\t" + str(TTD_percent) + "\t|\t" + str(TTD_num)) TDD_percent= round((p_pos * (p_neg ** 2) * 3) * 100,1) TDD_num= round((t_count * TDD_percent)/100,1) print("TDD\t|\t" + str(TDD_percent) + "\t|\t" + str(TDD_num)) DDD_percent= round((p_neg ** 3) * 100,1) DDD_num= round((t_count * DDD_percent)/100,1) print("DDD\t|\t" + str(DDD_percent) + "\t|\t" + str(DDD_num)) print("Total\t|\t" + str(100) + "\t|\t" + str(t_count)) #actual distribution print('\nTriads:') weight = nx.get_edge_attributes(graph, 'weight') Triads = [edge for edge in nx.enumerate_all_cliques(graph)if len(edge) == 3] triad_list = list(map(lambda edge: list(map(lambda edge: (edge, weight[edge]), combs(edge, 2))), Triads)) TTT_count = 0 TTD_count = 0 TDD_count = 0 DDD_count = 0 for triad in triad_list: e1_weight = triad[0][1] e2_weight = triad[1][1] e3_weight = triad[2][1] #identify type based on weight if(e1_weight == 1 and e2_weight == 1 and e3_weight == 1): triad_type = "TTT" TTT_count += 1 if(e1_weight == 1 and e2_weight == 1 and e3_weight == -1) or (e1_weight == -1 and e2_weight == 1 and e3_weight == 1) or (e1_weight == 1 and e2_weight == -1 and e3_weight == 1): triad_type = "TTD" TTD_count += 1 if(e1_weight == -1 and e2_weight == -1 and e3_weight == 1) or (e1_weight == 1 and e2_weight == -1 and e3_weight == -1) or (e1_weight == -1 and e2_weight == 1 and e3_weight == -1): triad_type = "TDD" TDD_count += 1 if(e1_weight == -1 and e2_weight == -1 and e3_weight == -1): triad_type = "DDD" DDD_count += 1 print(triad_type + "\t|\t" + str(triad[0]) + "\t|\t" + str(triad[1]) + "\t|\t" + str(triad[2])) TTT_percent = round((TTT_count *100)/t_count, 1) TTD_percent = round((TTD_count *100)/t_count, 1) TDD_percent = round((TDD_count *100)/t_count, 1) DDD_percent = round((DDD_count *100)/t_count, 1) print("\nActual Distribution:") print("Type\t|\tpercent\t|\tnumber") print("TTT\t|\t" + str(TTT_percent) + "\t|\t" + str(TTT_count)) print("TTD\t|\t" + str(TTD_percent) + "\t|\t" + str(TTD_count)) print("TDD\t|\t" + str(TDD_percent) + "\t|\t" + str(TDD_count)) print("DDD\t|\t" + str(DDD_percent) + "\t|\t" + str(DDD_count)) print("Total\t|\t" + str(100) + "\t|\t" + str(t_count))
#!/usr/bin/python from itertools import combinations as combs from fractions import Fraction maxi = 15 tot = 0 for i in range(maxi/2+1,maxi+1): #calculate probability of having exactly i right for j in combs(range(2, maxi+2), i): res = 1 for k in range(2,maxi+2): if k in j: res *= Fraction(1,k) else: res *= Fraction(k-1,k) tot += res print tot #gives 9219406943/20922789888000 #so 2269
from itertools import combinations as combs import math T = int(input()) for _ in range(T): s = [] answer = 0 nums = list(map(int, input().split(' '))) nums.pop(0) s.extend(combs(nums, 2)) for pair in s: answer += math.gcd(pair[0], pair[1]) print(answer)
from itertools import combinations as combs from functools import reduce from operator import mul def prod(numbers): return reduce(mul, numbers, 1) def first(iterable): return next(iter(iterable)) with open('input/day_01.txt') as f: report = [int(n) for n in f] part1 = first(prod(nums) for nums in combs(report, 2) if sum(nums) == 2020) part2 = first(prod(nums) for nums in combs(report, 3) if sum(nums) == 2020) print('Part 1:', part1) print('Part 2:', part2)
Sample: from itertools import combinations_with_replacement print list(combinations_with_replacement('12345',2)) [('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5')] A = [1,1,3,3,3] print list(combinations(A,2)) [(1, 1), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (3, 3), (3, 3), (3, 3)] Task: You are given a string S Your task is to print all possible size K replacement combinations of the string in lexicographic sorted order. Input: Output: """ from itertools import combinations_with_replacement as combs if __name__ == '__main__': s, k = input().split() print(*[''.join(p) for p in combs(sorted(s), int(k))], sep='\n') """ Test input: """
from itertools import combinations as combs def is_mono(n): n = str(n) for i in range(1, len(n)): if n[i] < n[i - 1]: return False return True T = int(input()) for tc in range(1, T + 1): N = int(input()) A = list(map(int, input().split())) ans = 0 for comb in combs(A, 2): num = comb[0] * comb[1] if is_mono(num): if ans < num: ans = num if ans == 0: ans = -1 print(f'#{tc} {ans}')
def get_confusion_matrices(corpus, cursor, collapse_subcategories=False): # Load data en = [] ko = [] alignments = [] for en_, ko_, alignment_str in cursor.execute( f'SELECT `en`, `ru`, `alignment` FROM `{corpus}` WHERE `verified` = 1' ): en.append(en_) ko.append(ko_) alignments.append(json.loads(alignment_str)) pos_pairs = [] path_pairs = [] for i in range(len(en)): en_n, en_g = conll2graph(en[i]) ko_n, ko_g = conll2graph(ko[i]) alignment = alignments[i] edges = [] # Select edges participating in one-to-one and many-to-one relationships # and fill the POS confusion matrix for k, v in alignment.items(): # Add none-to-smth to the POS matrix if k == 'X': for idx in v: if '.' in idx: continue new_node = ko_n[idx] pos_pairs.append(( 'None', new_node['pos'] )) continue # Filter out one-to-many elif len(v) > 1: continue head = k tail = v[0] edges.append((head, tail)) en_pos = en_n[head]['pos'] if tail == 'X': ko_pos = 'None' else: ko_pos = ko_n[tail]['pos'] pos_pairs.append((en_pos, ko_pos)) for pair in combs(edges, 2): (en_head, ko_head), (en_tail, ko_tail) = pair en_path_arr = get_path(en_head, en_tail, en_g) # Don't care for long source-side paths for now if len(en_path_arr) > 1: continue en_path = strip_direction(en_path_arr[0]) if collapse_subcategories: en_path = strip_subcategory(en_path) if ko_head == ko_tail: ko_path = 'Nodes collapsed' # Skip unaligned elif ko_head == 'X' or ko_tail == 'X': continue else: ko_path_arr = get_path(ko_head, ko_tail, ko_g) ko_path_arr = list(map(strip_direction, ko_path_arr)) if collapse_subcategories: ko_path = '+'.join( list(map(strip_subcategory, ko_path_arr)) ) else: ko_path = '+'.join(ko_path_arr) path_pairs.append((en_path, ko_path)) target_lang_name = corpus.split('-')[1] pos_dict = defaultdict(list) for head_pos, tail_pos in pos_pairs: pos_dict['en'].append(head_pos) pos_dict[target_lang_name].append(tail_pos) pos_df = pd.DataFrame(pos_dict) path_dict = defaultdict(list) for head_path, tail_path in path_pairs: path_dict['en'].append(head_path) path_dict[target_lang_name].append(tail_path) path_df = pd.DataFrame(path_dict) return ( pd.crosstab(pos_df['en'], pos_df[target_lang_name]), pd.crosstab(path_df['en'], path_df[target_lang_name]) )
def complete_graph(n): vertices = list(range(1, n + 1)) edges = [(a, b, 1) for a, b in combs(vertices, 2)] return Graph(vertices, edges)