def reunion(even, odd): oddN = [i for i in range(1, (odd * 2) + 1) if i % 2 != 0] evenN = [i for i in range(1, (even * 2) + 1) if i % 2 == 0] odds = [list(C(oddN, i)) for i in range(1, len(oddN) + 1)] odds = [j for i in odds for j in i] oddpics = [(s, ) + i for i in odds for s in evenN if all([s > v for v in i])] print(f"Odd number pictures: {oddpics}") evens = [list(C(evenN, i)) for i in range(1, len(evenN) + 1)] evens = [j for i in evens for j in i] evenpics = [(s, ) + i for i in evens for s in oddN if all([s > v for v in i])] print(f"Even number pictures: {evenpics}") return len(oddpics + evenpics)
def calVal(arr): pos, neg = posNegCount(arr) pos_ = [] neg_ = [] total = [] for i in range(1, len(pos) + 1): print("pos: ", list(C(pos, i))) pos_.append(list(C(pos, i))) for i in range(2, len(neg) + 1, 2): print("neg: ", list(C(neg, i))) neg_.append(list(C(neg, i))) for i in itertools.product(neg_, pos_): print(i) total.append(i) print(pos, neg) return total
def break_rings(rings): N = max([max(e) for e in rings]) for cnt in range(2, N): for breaked in C(range(1, N + 1), cnt): if all([(r[0] in breaked) or (r[1] in breaked) for r in map(list, rings)]): return cnt
def solution1(nums): answer = 0 threes = list(C(nums, 3)) for el in threes: if primeCheck(sum(el)): answer += 1 print(answer) return answer
def solution2(nums): answer = 0 candidates = list(C(nums, 3)) for c in candidates: if primeCheck(sum(c)): answer += 1 print(answer) return answer
def solution(arr, k, t): answer = 0 for n in range(k, len(arr) + 1): candis = list(C(arr, n)) for candi in candis: if sum(candi) <= t: print(candi) answer += 1 print(answer) return answer
def solution(nums): answer = 0 # 주어진 nums에 대해 3개의 숫자를 선택하는 경우를 모두 탐색 comb_nums = list(C(nums, 3)) for c in comb_nums: if isPrime(sum(c)): answer += 1 return answer
def gen3(N): def from_tuple(t, x): y = '0' if x == '1' else '1' p = 0 s = '1' for i in t: s += y * (i - p) + x p = i + 1 s += y * (N - 1 - len(s)) + '1' return s def from_tuples(t, x): for i in t: yield from_tuple(i, x) strs = [] for i in xrange(1, N - 1, 3): if i <= N / 2 - 1: strs = chain(strs, from_tuples(C(xrange(N - 2), i), '1')) else: strs = chain(strs, from_tuples(C(xrange(N - 2), N - 2 - i), '0')) return strs
def pe34(): f = [factorial(i) for i in range(10)] max_digit = 2 while len(str(max_digit * f[9])) >= max_digit: max_digit += 1 N = [] res = 0 for i in range(2, max_digit + 1): N = [''.join(n) for n in C('1234567890', i)] for n in N: p = str(sum(f[int(s)] for s in n)) if sorted(p) == sorted(n): res += int(p) return res
def getAssociativeRule(arr, inputArr, minconf): allAssociativeRules = [] for i in (range(1, len(arr))): c = [list(ele) for ele in list(C(arr, i))] for ele in c: rest = [i for i in arr if i not in ele] # print(ele) countEle = countElements(ele, inputArr) countArray = countElements(arr, inputArr) conf = countArray / countEle # print(ele,'->', rest, 'Proportion:\t', countArray, '/', countEle, '=',conf) if conf >= minconf: allAssociativeRules.append([ele, rest]) return allAssociativeRules
def pe30(pwr): if pwr < 2: return 0 f = [i**pwr for i in range(10)] max_digit = 2 while len(str(max_digit * f[9])) >= max_digit: max_digit += 1 res = 0 for i in range(2, max_digit + 1): N = [''.join(n) for n in C('1234567890', i)] for n in N: p = str(sum(f[int(s)] for s in n)) if sorted(p) == sorted(n): res += int(p) return res
def check_connection(network, first, second): groups = [set(s.split("-")) for s in network] loop = True while loop: loop = False for l, r in C(range(len(groups)), 2): if groups[l].intersection(groups[r]): lg, rg = groups[l], groups[r] groups.remove(lg) groups.remove(rg) groups.append(lg.union(rg)) loop = True break return any([{first, second}.issubset(g) for g in groups])
def solution(relation): # column의 개수 c <= 8, row의 개수 r <= 20 -> 완전탐색 r, c = len(relation), len(relation[0]) columnIndex = [i for i in range(c)] candidateKey = [] # 가능한 모든 키 조합에 대해 for i in range(1, c + 1): for keyComb in list(C(columnIndex, i)): uniqueness = True chk = [] # 릴레이션에서 해당 키의 튜플만 저장 for rel in relation: temp = [] for key in keyComb: temp.append(rel[key]) # 유일성 체크 if temp in chk: uniqueness = False break else: chk.append(temp) # 유일성 테스트를 통과한다면 if uniqueness: # 최소성 체크 currKey = ''.join(map(str, keyComb)) minimality = True # 이전에 결정된 후보키를 모두 포함하는 키가 있다면 최소성 만족 X for existingKey in candidateKey: count = len(existingKey) for ek in existingKey: for ck in currKey: if ek == ck: count -= 1 if count == 0: minimality = False break if minimality: candidateKey.append(currKey) return len(candidateKey)
def __init__(self, training_file): self.bigrams = Counter() self.unigrams = Counter() self.n_docs = 0 with open(training_file) as f: for line in f: self.n_docs += 1 label, *word_occurrences = line.strip().split() counts = sorted( map(lambda s: int(s.split(":")[0]), word_occurrences)) for w in counts: self.unigrams[w] += 1 for (w_i, w_j) in C(counts, 2): # If we've previously stored this in a different order, keep storing it that way ## BRW - leaving this here, but it shouldn't happen as we've sorted these if self.bigrams[(w_j, w_i)] != 0: self.bigrams[(w_j, w_i)] += 1 else: self.bigrams[(w_i, w_j)] += 1
def brute(n, k): global st, x ls = range(n) mxi = 0 area = 0 result = dict() for i in C(ls, k): bs = [] for j in i: bs.append(st[j]) bs.sort(reverse=True) area = pi * 2 * bs[0][1] * bs[0][0] for ix in xrange(1, len(bs)): area += pi * abs(bs[ix - 1][0]**2 - bs[ix][0]**2) area += 2 * pi * bs[ix][1] * bs[ix][0] area += pi * bs[-1][0]**2 mxi = max(mxi, area) result[mxi] = bs[:] #print result[mxi] return 'Case #%d: %0.8f' % (x + 1, area)
def solution(orders, course): result = [] for cour in course: arr = sum([list(map(lambda x: tuple(sorted(x)), C(string,cour))) for string in orders], []) cnt = 0 answer = [] for pair in set(arr): frequency = arr.count(pair) if cnt < frequency and frequency >= 2: answer = [pair] cnt = frequency elif cnt == frequency and frequency >= 2: answer.append(pair) result += [''.join(a) for a in answer] return sorted(result)
def solve(test): def arrange(cores): for n in range(len(cores), 0, -1): average = (test.U + sum(cores[:n])) / n if all(average >= p for p in cores[:n]): cores = [average] * n + cores[n:] break print(test.cores) print(test.U) print(cores) return cores cores = list(test.cores) cores[-test.K:] = arrange(cores[-test.K:]) if test.N == test.K: return reduce(mul, cores) else: combs = C(cores, test.K) return 1 - reduce(mul, (reduce(mul, (1 - s for s in cs)) for cs in combs))
def find_all_possible(known): possible = [False] * 360 for x in known: possible[x] = True stack = deque() for a1 in known.copy(): a2 = a1 for a in [(360 + a1 - a2) % 360, (360 + a2 - a1) % 360, (a1 + a2) % 360]: if not possible[a]: stack.append(a) known.add(a) possible[a] = True for a1, a2 in C(known, 2): for a in [(360 + a1 - a2) % 360, (360 + a2 - a1) % 360, (a1 + a2) % 360]: if not possible[a]: stack.append(a) known.add(a) possible[a] = True while stack: a1 = stack.pop() a2 = a1 for a in [(360 + a1 - a2) % 360, (360 + a2 - a1) % 360, (a1 + a2) % 360]: if not possible[a]: stack.append(a) known.add(a) possible[a] = True for a2 in known.copy(): for a in [(360 + a1 - a2) % 360, (360 + a2 - a1) % 360, (a1 + a2) % 360]: if not possible[a]: stack.append(a) known.add(a) possible[a] = True return possible
def getAssociativeRule(arr, inputArr, minconf): print(type(arr)) print(arr) arr = [int(each) for each in sorted((set(''.join(arr))))] print(string) allAssociativeRules = {} for i in (range(1, len(arr))): c = [list(ele) for ele in list(C(arr, i))] print(type(c)) print(c) for ele in c: rest = [i for i in arr if i not in ele] # print(ele) countEle = countElements(ele, inputArr) countArray = countElements(arr, inputArr) conf = countArray / countEle print('chec', ele, rest) if conf >= minconf: allAssociativeRules.setdefault( str(ele) + '->' + str(rest), conf) return allAssociativeRules
if TEST: player: Player = Player(hit_points=8) boss: Player = Player(hit_points=12, equipment=[Equipment(cost=0, damage=7, armor=2)]) else: player: Player = Player(hit_points=100) boss: Player = Player(hit_points=100, equipment=[Equipment(cost=0, damage=8, armor=2)]) print(boss.damage) min_cost: int = 9999 min_eq: List[Equipment] = [] for weapon in WEAPONS: for armor in ARMORS: for rings in [[]] + [[r] for r in RINGS] + list(C(RINGS, 2)): equipment = [weapon, armor] + list(rings) player_damage = max(1, sum(e.damage for e in equipment) - boss.armor) boss_damage = max(1, boss.damage - sum(e.armor for e in equipment)) if ceil(boss.hit_points / player_damage) > ceil( player.hit_points / boss_damage): continue cost = sum(e.cost for e in equipment) if cost < min_cost: min_cost = cost min_eq = equipment print(min_cost) print(min_eq)
from itertools import combinations as C with open('input') as f: lines = [ list(sorted(map(int, l.strip().split('\t')))) for l in f.read().strip().split('\n') ] print(sum(l[-1] - l[0] for l in lines)) print( sum((lambda t: t[1] // t[0] )(next(filter(lambda t: t[1] % t[0] == 0, C(sorted(l), 2)))) for l in lines))
def expand(self, x): expanded = np.fromiter(map(lambda x:x[0]*x[1], C(x, 2)), float) return np.concatenate([[1], x, expanded])
print 'Case #%d: %0.8f\n' % (n, res), #print res def outterm(n, res): print >> sys.stderr, 'Case #%d:' % (n), print >> sys.stderr, res for x in xrange(input()): n, k = get(int) st = [] for i in xrange(n): a, b = get(int) st.append((a, b)) ls = range(n) mxi = 0 for i in C(ls, k): bs = [] for j in i: bs.append(st[j]) bs.sort(reverse=True) area = pi * 2 * bs[0][1] * bs[0][0] for ix in xrange(1, len(bs)): area += pi * abs(bs[ix - 1][0]**2 - bs[ix][0]**2) area += 2 * pi * bs[ix][1] * bs[ix][0] area += pi * bs[-1][0]**2 mxi = max(mxi, area) outfile(x + 1, mxi) outterm(x + 1, mxi)
from itertools import combinations as C n = list(map(int, input().split())) numbers = list(map(int, input().split())) numbers.sort() comb = list(C(numbers, n[1])) comb.sort() for i in comb: answer = "" for j in i: answer += str(j) + " " print(answer)
from itertools import combinations as C import sys init=True for line in sys.stdin: num=sorted(list(map(int, line.split()))[1:]) if num==[]: break elif not init: print() init=False for c in C(num, 6): print(*c)
len(test_out))**0.5 print "Error Estimate Bowler wickets per innings = ", (errbowpi * 1.0 / len(test_out))**0.5 print "Error Estimate Batsmen not-outs = ", (errbanot * 1.0 / len(test_out))**0.5 print "Error Estimate Bowler 5-wicket halls = ", (errbofwi * 1.0 / len(test_out))**0.5 print "Error Estimate Batsmen highest score = ", (errbahig * 1.0 / len(test_out))**0.5 print "Error Estimate Bowler 10-wicket halls = ", (errbotwm * 1.0 / len(test_out))**0.5 f3.close() print "team prediction starts" print "**********************" allbats = list(C(random.sample(batsmen, 8), 6)) allbowl = list(C(random.sample(bowler, 7), 5)) print "**********************" print "batsmen" temp = [] temp2 = [] for i in allbats: arr = [float(dic_bat['Average_' + x]) for x in i] temp2.append(modelbaavg.predict(arr)[0]) i = 0 while (i < len(temp2)): if (temp2[i] >= sum(temp2) / len(temp2)): temp.append(allbats[i]) i += 1 allbats = temp for i in allbats:
numcases = int(temp.pop(0).strip('\n')) pt = 0 case = [] for i in range(numcases): intersections = 0 N = int(temp[pt].strip('\n')) pt += 1 wires = [] for ii in range(N): line = temp[pt].strip('\n').split(' ') wires.append([int(line[0]), int(line[1])]) pt += 1 #Now that all the data is read in... for k in C(wires, 2): #find difference and multiply #if answer is negative, there's an intersection, because #A1>A2 and B1<B2 or vice versa. If positive, then #one wire is completely higher than the other. #Using timeit.Timer, turns out multiplication is faster #than boolean > if (k[0][0] - k[1][0]) * (k[0][1] - k[1][1]) < 0: intersections += 1 case.append(intersections) with open(filename + r'\out.txt', 'w') as outputfile: outputfile.write('\n'.join([ 'Case #' + str(num + 1) + ': ' + str(ans) for num, ans in enumerate(case) ]))
def load_DataGenerators(self, dictionary_dir, wavs_dict, negative_wavs, speaker_list_current, flag, model_current, graph, speaker_list_val): while True: #print(flag) triplets = [] triplets_miniepoch = [] st = time.time() print("Current speaker list for " + str(flag) + " =", speaker_list_current) for speaker in speaker_list_current: print(speaker) start = time.time() dict_dir_current = dictionary_dir + '/' + flag + '/' dict_dir_current_speaker = dict_dir_current + str(speaker) print(dict_dir_current_speaker) num_chunks = int(len(os.listdir(dict_dir_current_speaker))) if flag == 'train': chunk = random.randint(0, num_chunks - 1) else: chunk = 0 #print("chunk",chunk) tmp_dictionary = get_dictionaries(dict_dir_current_speaker, chunk) #print(len(tmp_dictionary.keys())) anchor_positive_pairs = list(C(tmp_dictionary.keys(), 2)) negative_wav_ids = list(negative_wavs[speaker]) random.shuffle(negative_wav_ids) #print((anchor_positive_pairs)) tmp = negative_sampling(speaker, chunk, anchor_positive_pairs, tmp_dictionary, negative_wav_ids, wavs_dict, dictionary_dir, flag, graph, model_current, speaker_list_val) print("Done negative sampling for speaker ", speaker) #print(tmp) del tmp_dictionary triplets_miniepoch.append(tmp) #print(time.time() - start, "seconds") #print(triplets_miniepoch) #print("Found triplets for mini epoch") triplets = [t for p in triplets_miniepoch for t in p] random.shuffle(triplets) if flag == 'train': f = open("triplets_mep0.pickle", 'wb') pickle.dump(triplets, f) f.close() print("SAVED TRIPLETS") if flag == 'train': f = open( "/home/rperi/exp_DAE/SpeakerTurnLossHistory/triplets.txt", 'a') f.writelines(str(triplets) + "\n") f.close() num_triplets = len(triplets) print("Num Triplets = ", num_triplets) batch_size = int(self.batch_size) num_batches = int(num_triplets / batch_size) #print("num batches", num_batches) for b in range(num_batches): current_batch = list(triplets[b * batch_size:(b + 1) * batch_size]) l = K.get_value(model_current.optimizer.lr) print(l) anc, pos, neg, tar = self.__data_generation( dictionary_dir, flag, current_batch) yield [anc, pos, neg], tar del triplets, triplets_miniepoch
if learned[ord(w)] == False: canRead = False break if canRead: count += 1 return count n, k = map(int, input().split()) answer = 0 alphabet = set(chr(i) for i in range(97, 123)) - {'a', 'n', 't', 'i', 'c'} words = [sys.stdin.readline().rstrip()[4:-4] for _ in range(n)] if k >= 5: learned = [False] * (150) for x in {'a', 'n', 't', 'i', 'c'}: learned[ord(x)] = True # 남은 알파벳 중에서 k-5개를 선택해본다. for teach in list(C(alphabet, k - 5)): for t in teach: learned[ord(t)] = True count = countReadableWords(words, learned) if count > answer: answer = count # 배운 단어 초기화 for t in teach: learned[ord(t)] = False print(answer) else: print(0)
import sys input = sys.stdin.readline from itertools import combinations as C, permutations as P people = [x for x in range(int(input()))] S = [list(map(int, input().split())) for x in range(len(people))] team = list(C(people, len(people) // 2)) limit = len(team) gap = 9001 for i in range(limit // 2): sum1 = 0 sum2 = 0 startTeam = list(P(team[i], 2)) linkTeam = list(P(team[limit - i - 1], 2)) for j in range(len(startTeam)): sum1 += S[startTeam[j][0]][startTeam[j][1]] sum2 += S[linkTeam[j][0]][linkTeam[j][1]] if gap > abs(sum1 - sum2): gap = abs(sum1 - sum2) print(gap)