def BTK(choice,idx): global myMin if choice == N//2: A = [] B = [] for u in range(N): if visited[u]: A.append(u) else: B.append(u) r1 = 0 r2 = 0 for a,b in c(A,2): r1+=data[a][b]+data[b][a] for a,b in c(B,2): r2+=data[a][b]+data[b][a] temp = abs(r1-r2) if temp < myMin: myMin = temp return for i in range(idx,N): visited[i] = 1 BTK(choice+1,i+1) visited[i] = 0
def isSpecial(A): for i in range(1, len(A) + 1): for j in c(A, i): setB = set(j) temp = A - setB for k in range(1, len(temp) + 1): for l in c(temp, k): setC = set(l) if len(setB) > len(setC): if sum(setB) <= sum(setC): return False if sum(setB) == sum(setC): return False return True
def solution(phone_book): sortedPB=sorted(phone_book) for a, b in c(sortedPB, 2): if a==b[:len(a)]: return False return True
def func(): from itertools import combinations_with_replacement as c TARGET = 17 #prime numbers >=17 numbers = set(range(TARGET, 1, -1)) _primes = [] while numbers: _p = numbers.pop() _primes.append(_p) numbers.difference_update(set(range(_p * 2, TARGET + 1, _p))) #sums true_sums, done, index = [], False, 0 while not done: main_list = [list(item) for item in c(_primes, index)] for a_sub_list in main_list: if sum(a_sub_list) == TARGET: true_sums.append(a_sub_list) else: pass index += 1 if index > len(_primes) + 1: done = True assert len(true_sums) == TARGET for true_s in true_sums: temp = '' for i in true_s: temp = temp + str(i) + '+' print("{} = {}".format(temp[:len(temp) - 1], TARGET)) print("\nCount: {}\nAgreed".format(len(true_sums)))
def solution(phoneBook): answer = True sortedPB = sorted(phoneBook, key=len) for (a, b) in c(sortedPB, 2): if a == b[:len(a)]: answer = False return answer
def U(A, k): ans = set() for i in c(A, k): total = sum(i) if total in ans: ans.remove(total) else: ans.add(total) return ans
def solution(road, n): N = len(road) road2 = [*road] candidate = [] for i in range(N): if road2[i] == '0': candidate.append(i) if len(candidate) <= n: return len(road) ans = 0 for i in c(candidate, n): road3 = road2[:] for j in i: road3[j] = '1' res = 0 maxres = 0 for k in road3: if k == '1': res += 1 else: maxres = max(res, maxres) res = 0 ans = max(ans, maxres) return ans
def rand(s): cs = [] sample = [] for x in c(n, 3): cs.append(x) sample = random.sample(cs, s) return sample
def main(passwd, length, console_output, live_output): cmd('cls' if osname == 'nt' else 'clear') if console_output == True: if live_output == True: MaxNum = 10 ** length t1 = time() for i in c(start=1): x = r(0, MaxNum) print(i, "Tries ", length, "Nums lenght", " ", "Current pin:", x) if x == passwd: t2 = time() print("Pin is guessed:", x) t = t2 - t1 print(t, "Seconds, with output") print(i, "Tries") break elif live_output == False: MaxNum = 10 ** length t1 = time() for i in c(start=1): x = r(0, MaxNum) if x == passwd: t2 = time() print("Pin is guessed:", x) t = t2 - t1 print(t, "Seconds") print(i, "Tries") break elif console_output == False: if live_output == True: MaxNum = 10 ** length t1 = time() for i in c(start=1): x = r(0, MaxNum) if x == passwd: t2 = time() t = t2 - t1 break elif live_output == False: print("What do you expect? gui is of but live feed on? really?") i = "nonsence" t = "nonsence" return i,t
def largestReversi(): #largestR = [x*y for x,y in list(c(list(range(10,100)),2)) if str(x*y)==''.join(reversed(str(x*y)))][-1] x =max(filter(lambda y: str(y[2]) == ''.join(reversed(str(y[2]))), map(lambda x:(x[0] , x[1], x[0]*x[1]), list(c(list(range(100,1000)),2)))) ,key=lambda item:item[2]) return (x[0],'x',x[1],'=',x[2])
def divs( n ): "given a whole number n, divs() will return a list of all positive divisors of n which are less than n." d = {1:0} pfs = pf(n,[]) for l in range(1,len(pfs)+1): for k in c(pfs,l): # divisors can be found by multiplying ALL combinations of the prime factors d[reduce( mul, k )]=0 d.pop(n) # the number n itself should not be in the list return d.keys()
def solve(): res = -1 for num_length in range(1,upper_bound+1): combos = c(range(10),num_length) for combo in combos: total = sum([x**5 for x in combo]) if sorted([x for x in str(total)]) == sorted(map(str,combo)): res+=total return res
def largestTriangleArea(points): """ :type points: List[List[int]] :rtype: float """ area = 0 for x, y, z in c(points, 3): area = max(area, ShoelaceFormula(x, y, z)) return area
def __init__(self, rounds, matches, verified): self.valid_cnt = 0 self.valid = [] self.rounds = rounds self.matches = matches self.verified = verified # All True for classic mode self.combos = list(c(range(1, 16), 3)) # Embeds self.sol_panel = discord.Embed()
def solution(phoneBook): answer = True # for i in range(len(phoneBook)): # phoneBook[i] = str(phoneBook[i]) sortedPB = sorted(phoneBook) #, key= len) for (a,b) in c( sortedPB,2): a = str(a) b = str(b) if a == b[:len(a)]: answer = False return answer
def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] for i in set(c(sorted(nums), 3)): # print(i, sum(i)) if sum(i)==0: res.append(list(i)) return res
def dice(): combinations = list(c([1, 2, 3, 4, 5, 6], 2)) combinations.append((1, 1)) combinations.append((6, 6)) for sum in range(2, 13): out = [] for combination in combinations: if combination[0] + combination[1] == sum: out.append(combination) out.append(tuple(list(combination)[::-1])) print(f"{sum}: \t{out}")
def goldbach(n): if n < 3: raise NotGoldbach("Numeri inferiori a 2 non sono numeri di Goldbach") if n % 2 != 0: raise NotGoldbach("{} non è un numero pari".format(n)) prime = [x for x in range(2, n) if trial_division(x)] return [ str(n) + " = " + str(x[0]) + " + " + str(x[1]) for x in c(prime, 2) if x[0] + x[1] == n ]
def find_prob(n,m): combos = n*'a' + m*'b' possibles = list(c(combos,m+n)) print(possibles) total = prob = 0 for i in possibles: prob += always_leading(i) total += 1 return prob/total
def gen_candidates(table): keys=list(table.keys()) tup_cnt=len(list(keys[0])) table = {} tup = [] for v in c(keys,2): a=set(v[0]) b=set(v[1]) if((len(a&b)==(tup_cnt-1)) and (tuple(a|b) not in tup)): tup.append(tuple(a|b)) print tup[-1] cnt=get_support(tup[-1]) if(cnt>=support): table[tup[-1]]=cnt return table
def solve(): #Define variables start = time.time() ans = '' #Solve the problem nums = max(c(range(1, 10), 4), key=length) for i in nums: ans += str(i) #Print the results print 'The string that represents the concatenation of the 4 single ' print 'digit numbers where a < b < c < d, for which the longest set of ' print 'consecutive positive integers, 1 to n, can be obtained, is ' + ans + '.' print 'This took ' + str(time.time() - start) + ' seconds too calculate.'
def semiprime(n): l = [] f = 0 if n > 2 and n % 2 == 0: l.append(2) for i in range(3, n + 1): if prime(i) == 0 and (n % i == 0): l.append(i) ln = list(c(l, 2)) for i in ln: if (i[0] * i[1] == n): print(i[0], i[1]) f = 1 break if (f == 0): return 0
def repeat_inside(line: str): """ first the longest repeating substring """ from itertools import combinations as c result = '' length = len(line) repeat_items_alternative = [ line[start:end] for start, end in c(range(length), 2) if end - start <= length / 2 ] for repeat_item in repeat_items_alternative: for repeat_times in range(2, length // len(repeat_item) + 1): if repeat_item * repeat_times in line and len( repeat_item * repeat_times) > len(result): result = repeat_item * repeat_times return result
def get_all_equations(n, values): with open('all_equations.txt', 'w', encoding='utf8') as file: result = [] for i in range(2 ** n): b_num = bin(i ^ 2 ** n)[:2:-1] row = [int(values[i]), b_num[::-1]] for j in range(1, n + 1): for coefficient in c(enumerate(b_num, 1), j): low = ''.join([str(coefficient[i][0]) for i in reversed(range(len(coefficient)))]) up = ''.join([str(coefficient[i][1]) for i in reversed(range(len(coefficient)))]) row.append('K_{}^{}'.format(low, up)) result.append(row) file.write(' ?'.join(row[n + 1:1:-1]) + ' ?' + ' ?'.join(row[n + 2::]) + ' = f({})'.format(row[1]) + ' = {}'.format(row[0]) + '\n') return result
def solution(answer_sheet, sheets): ans = 0 for i in c(sheets, 2): cnt = 0 con = 0 concnt = 0 for j in range(len(answer_sheet)): k = 0 if i[0][j] == i[1][j] and i[0][j] != answer_sheet[j]: cnt += 1 k = 1 if k == 1: con += 1 concnt = max(con, concnt) else: con = 0 res = cnt + concnt**2 ans = max(ans, res) return ans
def snowmen(s): a = {i:s.count(i) for i in set(s)} s = sorted(s) p = sum(s) n = len(s)/3 ss = a from itertools import combinations as c for i in xrange(n,0,-1): #print 3*i v = set() if p < sum(s[:len(s)-3*i]): break for k in c(s,3*i): t = {g:h for g,h in a.items()} #k = tuple(sorted(k)) #print k if k not in v: b = 1 v.add(k) for j in list(set(k)): if k.count(j) > i: b = 0 break t[j] -= k.count(j) if t[j] < 0: b = 0 break if b == 1: temp = sum(g*h for g,h in t.items()) #print temp if temp < p: p = temp ss = t if p == 0: return 0 if p == 0: return 0 c = 0 for i,j in ss.items(): c += j*i**3 from math import pi return c*4/3.*pi
def CombinationMethods(nums, elements_number): """ This function allows you to easily get all the methods of combination. Parameters ---------- nums: list They are all the elements that need to be combined. elements_number: int It is the number of elements to be taken out. Returns ------- tuple This tuple have two elements, the first is all the combination methods (list), the second is the Combination object (Combination(len(nums, elements_number))). """ res = list(c(nums, elements_number)) return res, Combination(len(nums), elements_number)
def solution(): l = getPrimesBelowN(1000000) for n in range(len(l)): if l[n]: digits = len(str(n)) for length in range(1, digits): combs = c(range(digits), length) for comb in combs: replacement_prime = [] d_replacement = '123456789' if 0 not in comb: d_replacement = '0123456789' for d in d_replacement: p = list(str(n)) for pos in comb: p[pos] = d if l[int(''.join(p))] and int( ''.join(p)) not in replacement_prime: replacement_prime.append(int(''.join(p))) if len(replacement_prime) >= 8: print sorted(replacement_prime)
def diz_solution(data): from itertools import combinations as c from cmath import pi, acos, sqrt space = list(map(list, data)) def distance(u, v): return abs(complex(*u[:2]) - complex(*v[:2])) + 1e-9 def intersection(d, r1, r2): a = r1 ** 2 * acos((d ** 2 + r1 ** 2 - r2 ** 2) / (2 * r1 * d)) + \ r2 ** 2 * acos((d ** 2 + r2 ** 2 - r1 ** 2) / (2 * r2 * d)) - \ sqrt((r1 + r2 - d) * (r1 + d - r2) * (r2 + d - r1) * (d + r1 + r2)) / 2 return a.real while 1: for d, a, b in sorted((distance(u, v), u, v) for u, v in c(space, 2)): (rs, s), (rb, b) = sorted((n[2], n) for n in (a, b)) if rb ** 2 / 1.2 >= rs ** 2 <= intersection(d, rs, rb) / pi / .55: b[2] = abs(rs + 1j * rb) space.remove(s) break else: return space
# -*- coding: utf-8 -*- """ Created on Thu Dec 3 14:23:00 2020 @author: Tumtum """ from itertools import combinations as c d = list(map(int, open("input.txt", "r").readlines())) for x, y in c(d, 2): if x + y == 2020: print(x) print(y) # print(z) solve = x * y print(solve) # print([x*y*z for x,y,z in c(d,3)if x+y+z==2020][0],[x*y*z for x,y,z in c(d,3)if x+y+z==2020][0]) # print([x*(2020-x) for x in d[::2] if 2020-x in d])
from itertools import combinations as c n=int(input()) s=[[*map(int,input().split())]for _ in range(n)] m=[sum(i)+sum(j)for i,j in zip(s,zip(*s))] a=sum(m)//2;p=[] for l in c(m,n//2):p.append(abs(a-sum(l))) print(min(p))
from __future__ import division from itertools import combinations as c #user input to list L N = int(raw_input()) L = map(str, raw_input().split()) K = int(raw_input()) L2 = c(L, K) L3 = list(L2) count_a = 0 for i in range(0,len(L3)): if L3[i].count('a') > 0: count_a +=1 print count_a/len(L3)
import sys sys.stdin = open('../input.txt', 'r') from itertools import combinations as c while 1: s = [*input().split()] if s.pop(0) == '0': break for i in c(s, 6): print(*i) print()
from itertools import combinations as c from itertools import permutations as p #PALINDROME GENERATOR n = [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9] pals = [] for i in range(1,4): #print (i) #print (*c(n,i)) pals += [x[:-1]+x[::-1] for x in c(n,i) if x[0] != 0] pals += [x+x[::-1] for x in c(n,i) if x[0] != 0] a = 0 pals = [] for i in map(str,range(1,1000)): pals.append(i[:-1]+i[::-1]) pals.append(i+i[::-1]) mydict = {} for pal in pals: x = str(bin(int(''.join([str(x) for x in pal]))))[2:] if x == x[::-1] and x not in mydict: mydict[x] = 1 #print (pal) #print (x) a += int(pal) print (a) a = 0 for i in range(1,1000000): stri = str(i) x = bin(i)[2:] if stri == stri[::-1] and x == x[::-1]: #print (i)
found_minimum = False; minimum = 100000000 if S in dictionary_words: output.write("Case #%i: %s\n"%(t, "0" )) continue while not found_minimum: for number_of_altercations in range(1,len(S)): print number_of_altercations while not found_minimum: for number_of_swaps in range(number_of_altercations+1): print number_of_swaps number_of_spaces = number_of_altercations - number_of_swaps space_location_sets = c(range(1,len(S)),number_of_spaces); while not found_minimum: for space_locations in space_location_sets: s1=S for space_location in space_locations: str(list(s1).insert(space_location, ' ')) swap_location_sets = c(range(len(s1)),number_of_swaps); s2=s1 strings_to_apply_to = [s2] for swap_locations in swap_location_sets: result = [] for swap_location in swap_locations: for string_to_apply_to in strings_to_apply_to: result+=changeLetterAtIndex(swap_location,string_to_apply_to) strings_to_apply_to = result passesTest=True
The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """ """ Prova de um cara lá no fórum do PE sobre apenas ser necessário considerar números de 6 dígitos ou menos. Proof that one need only consider numbers 6 digits or less: If N has n digits, then 10^{n-1} <= N. If N is the sum of the 5th powers of its digits, N <= n*9^5. Thus, 10^{n-1} <= n*9^5. We now show by induction that if n>=7, then 10^{n-6} > n. 1) Basis step (n=7): 10^{7-6} = 10 > 7. 2) Induction step: suppose 10^{n-6} > n for some n>=7. Show this true for n+1 too. Well, 10^{(n+1)-6} = 10*10^{n-6} > 10n > 2n > n+1 QED. It follows that if n>=7, then 10^{n-1} = 10^{n-6}*10^5 > n * 10^5 > n*9^5. Hence the only way we can have 10^{n-1} <= n*9^5 is for n<=6. """ #Aqui foi pura sorte. #Inicialmente tentei pensar num limite para testes, seria o tamanho*9**5, mas não consegui deduzir o maior tamanho possível #Desse jeito, fiz alguns testes e descobri que a ocorrência de números que poderiam ser escritos como a soma de potência(5) #Era no tamanho intervalo de [4, 7) from itertools import combinations_with_replacement as c; from string import digits as d n = lambda num, digits: sorted(str(num)) == sorted(digits) p = lambda comb: sum([int(n) ** 5 for n in comb]) print(sum(set(reduce(list.__add__, ([p(cb) for cb in c(d, x) if n(p(cb), cb)] for x in range(7))))))
potatoes='69 162 108 196 170 123 84 89 158 135' from itertools import combinations as c res={} # res = { str(a):sum(a) for a in c(map(int,potatoes.split()),2) } for a in c(map(int,potatoes.split()),2): res[str(a)]=sum(a) for a in c(map(int,potatoes.split()),3): res[str(a)]=sum(a) for a in c(map(int,potatoes.split()),4): res[str(a)]=sum(a) for a in c(map(int,potatoes.split()),5): res[str(a)]=sum(a) for a in sorted([(res[k],k) for k in res]): print (a)
from urllib import request as req import json,csv,pickle from itertools import combinations as c from time import sleep with open('locations.csv','r') as f: locations={i.split('#')[0]:(float(i.split('#')[1]),float(i.split('#')[2].replace('\n',''))) for i in list(f)[1:]} apikey='AIzaSyC7AbjTN7Pu0r9w9Wksz6ZIjdG6FUjfFL0' # apikey='AIzaSyB9XMc1GR3rCn2zkfa6xJ0j8AsLdz0BW8U' # theodore l = [] for i in c(locations,2): j = {} while 'routes' not in j or len(j['routes'])==0: print(i[0],i[1]) j = json.loads(req.urlopen('https://maps.googleapis.com/maps/api/directions/json?origin={},{}&destination={},{}&key={}'.format(locations[i[0]][0],locations[i[0]][1],locations[i[1]][0],locations[i[1]][1],apikey)).read().decode('utf-8')) sleep(0.1) distance = str(sum(i['distance']['value'] for i in j['routes'][0]['legs'][0]['steps'])) time = str(sum(i['duration']['value'] for i in j['routes'][0]['legs'][0]['steps'])) l.append([i[0],i[1],distance,time]) with open('pickle/directions.py','wb') as f: pickle.dump(l,f) with open('paths.csv','w') as csvfile: w = csv.writer(csvfile) w.writerow(['from','to','distance','time']) for i in l: w.writerow(i)
def dig_pow(n, p): from itertools import count as c s = sum([pow(int(i), m) for i, m in zip(str(n), c(p))]) / float(n) return s if s.is_integer() else -1
#!/bin/env python3 import base64 import hashlib from itertools import cycle as c T=lambda s:map(''.join, zip(*[iter(s)]*2)) #split in pairs of 2 encode= lambda k,s:''.join(hex(ord(S)+ord(K)%256)[2:]for K,S in zip(c(k),s)) #decode=lambda k,C:''.join(chr(int(C,16)-ord(K)%256)for K,C in zip(c(k),T(C))) #not used def gen_key(hashable): if not hashable: raise NotImplementedError return hashlib.sha224(hashable.encode('utf8')).hexdigest() def code_mangler(code_cleartext, key, verbose=False): pre_code = "#hey you got this far :) that's something! But the fun only just started\n" # This used to be part of the precode. It's inlined now for added evilness. #y=__import__('itertools').cycle #T=lambda s:map(''.join, zip(*[iter(s)]*2)) #d=lambda k,C:''.join(chr(int(C,16)-ord(K)%256)for K,C in zip(y(k),T(C))) code_ct = '''DF = True #used to check if you were able to decrypt properly #bloody kudos mate. #PM me the passphrase "The manatee prosciuttos at noon" if you got it ;) #I sorta wanna tip my virtual hat to you. '''+code_cleartext cypher = encode(key,code_ct) code = 'c,remove,DF = "' +cypher+'", __import__,False' post_code = ''' try:c,input=exec(''.join(chr(int(C,16)-ord(K)%256)for K,C in zip(remove('itertools').cycle(remove('hashlib').sha224('<REPLACE ME WITH CODE>'.encode('utf8')).hexdigest()),map(''.join, zip(*[iter(c)]*2))))),lambda s: run() and False
from itertools import combinations as c print [n for n in c(open('shortdata.txt'),2)]
print table while True: table=gen_candidates(table) if(len(table)==1 or len(table)==0): print "Pruned list\n" print table break else: print "Pruned list\n" print table tup=set(list(table.keys())[0]) sup=table[list(table.keys())[0]] ls = [] for i in range(1,len(tup)): ls+=c(tup,i) print("+--------------------+---------------+------------------+") print("| Association rule | Support | Confidence |") print("+--------------------+---------------+------------------+") for i in ls: i=set(i) j=set(tup-i) sup_i=get_support(i) conf=float(sup)/float(sup_i) print("{}->{}\t\t{}\t\t{}/{}={}\t".format(i,j,sup,sup,sup_i,conf))