def perms_list(nnk): a=nnk[0]; b=nnk[1]; c=nnk[2] p_list = list(perms((a,b,c))) p_list += list(perms((a,b,-c))) p_list += list(perms((a,-b,c))) p_list += list(perms((-a,b,c))) p_list = [ p for p in p_list ] return p_list
def perms_list(nnk): a = nnk[0] b = nnk[1] c = nnk[2] p_list = list(perms([a, b, c])) p_list += list(perms([a, b, -c])) p_list += list(perms([a, -b, c])) p_list += list(perms([-a, b, c])) p_list = [list(p) for p in p_list] return p_list
def solve(): """ """ permutations = sorted([''.join(p) for i, p in enumerate(perms(str(d) for d in range(10))) if i < 1000000]) return permutations[-1]
def get_blocks(grid): ''' expects a grid and yields each current_block as a set of tuples i,j''' block_nodes = set() def block_finder(node): '''expects a node that is part of the current_block and continues to add nodes to the current_block''' i, j = node[0], node[1] neighbours = ((i + n, j + m) for n, m in perms([-1, 0, 1], 2) if 0 <= i + n < 4 and 0 <= j + m < 4 and abs(n + m) == 1) for neigh in neighbours: if grid[node] == grid[neigh] and neigh not in current_block: current_block.add(neigh) block_finder(neigh) for j, i in product(range(4), range(4)): current_block = set() node = (i, j) if node not in block_nodes: neighbours = ((i + n, j + m) for n, m in perms([-1, 0, 1], 2) if 0 <= i + n < 4 and 0 <= j + m < 4 and abs(n + m) == 1) if any(grid[node] == grid[neigh] for neigh in neighbours): current_block.add(node) block_finder(node) # this will find the current_block block_nodes = block_nodes | current_block yield current_block
def create_pandigitals(start, end): total = 0 for s in perms(start): n = ''.join(s) poss = n + end if is_curious(poss): total += int(poss) return total
def solution(): ingredients = ["Sugar", "Sprinkles", "Candy", "Chocolate"] capacity = [3, -3, -1, 0] durability = [0, 3, 0, 0] flavor = [0, 0, 4, -2] texture = [-3, 0, 0, 2] calories = [2, 9, 1, 8] high_score = 0 high_score_spoons = () for spoons in list(perms(range(1, 101), len(ingredients))): if sum(spoons) == 100: score = 0 c = sum([a * b for a, b in zip(spoons, capacity)]) d = sum([a * b for a, b in zip(spoons, durability)]) f = sum([a * b for a, b in zip(spoons, flavor)]) t = sum([a * b for a, b in zip(spoons, texture)]) if c >= 0 and d >= 0 and f >= 0 and t >= 0: cals = sum([a * b for a, b in zip(spoons, calories)]) if cals == 500: score = c * d * f * t if score > high_score: high_score = score high_score_spoons = spoons return (high_score, high_score_spoons)
def edit_distance_one(word): for word_perm in perms(word, len(word)): for i in range(len(word_perm)): for letter in lowercase: new_word = ''.join(word_perm) new_word = new_word[:i] + letter + new_word[i + 1:] yield new_word
def gen_pandigs(): yield 1 n = '1' for k in xrange(2, 9): yield k n += str(k) for z in perms(n): yield int(''.join(z))
def sensing(eq_given): num_max = len(eq_given) result_1 = eq_given @ meas_p1 result_2 = eq_given @ meas_p2 pad = [(spot, spot) for spot in range(num_max)] indices = np.array(list(perms(range(num_max), 2)) + pad).T res_tot = result_1[indices[0]] + result_2[indices[1]] return res_tot
def make_some_features(numbers, clip): features = set() combinations = (combo for combo in combos(numbers, 6)) for i, comb in enumerate(combinations): if i % clip == 0: # Keeping size reasonable for perm in perms(comb): features.add(perm) return features
def main(): r = range(1, 10) ps = perms(r) res = set() for p in ps: s = nums(p) res = res.union(s) print(sum(res))
def observe(self): num = len(self.value_lines) res1 = self.value_lines @ self.meas_p1 res2 = self.value_lines @ self.meas_p2 pad = [(ii, ii) for ii in range(num)] ind = np.array(list(perms(range(num), 2)) + pad).T self.value_lines = res1[ind[0]] + res2[ind[1]] if self.prune_on: self.prune() return self.value_lines
def gen_ngons(n): lst = [] for perm in perms([i for i in range(1, n * 2 + 1)]): if perm[0] > n + 1: break ng = Ngon(n) ng.set_outer(list(perm[:n])) ng.set_inner(list(perm[n:])) lst.append(ng) return list(set(filter(lambda ng: ng.is_valid(), lst)))
def gen_numbers(digits): numbers = [] for m in range(1, len(digits) + 1): for c in perms(digits, m): s = ''.join(c) i = int(s) numbers.append(i) return numbers
def solve(n=9): s = "".join([str(x) for x in range(1, n + 1)]) res = set() for perm in perms(s): perm = "".join(perm) for b in range(1, n // 2): for c in range(b + 1, n): if int(perm[:b]) * int(perm[b:c]) == int(perm[c:]): res.add(int(perm[c:])) return sum(res)
def Oh_list(): Oh_list = list(perms([1, 2, 3])) Oh_list += list(perms([1, 2, -3])) Oh_list += list(perms([1, -2, 3])) Oh_list += list(perms([-1, 2, 3])) Oh_list += list(perms([1, -2, -3])) Oh_list += list(perms([-1, 2, -3])) Oh_list += list(perms([-1, -2, 3])) Oh_list += list(perms([-1, -2, -3])) Oh_list = [list(R) for R in Oh_list] return Oh_list
def block_finder(node): '''expects a node that is part of the current_block and continues to add nodes to the current_block''' i, j = node[0], node[1] neighbours = ((i + n, j + m) for n, m in perms([-1, 0, 1], 2) if 0 <= i + n < 4 and 0 <= j + m < 4 and abs(n + m) == 1) for neigh in neighbours: if grid[node] == grid[neigh] and neigh not in current_block: current_block.add(neigh) block_finder(neigh)
def recurse(remainingNodes): edges = G[remainingNodes[0]] # because these are cyclic permutations, we fix the first element for partialPerm in perms(edges[1:]): if len(remainingNodes) == 1: yield {remainingNodes[0] : edges[:1]+list(partialPerm)} else: # print {remainingNodes[0] : edges[:1]+list(partialPerm)} # print recurse(remainingNodes[1:] for followingPerms in recurse(remainingNodes[1:]): yield mergeDicts({remainingNodes[0] : edges[:1]+list(partialPerm)}, followingPerms)
def all_unique_no_perms(line): """ returns True if line contains all unique words, False if not """ if all_unique(line) == False: return False for word in line: p = [''.join(x) for x in perms(word)] for pp in p: if pp != word and pp in line: return False return True
def solve(n, bff): bff = [x - 1 for x in bff] for howMany in range(n, 0, -1): for perm in perms(range(n), howMany): valid = True perm = perm + (perm[0],) for i in range(howMany): if not bff[perm[i]] == perm[i+1] and not bff[perm[i]] == perm[i-1]: valid = False break if valid: return howMany
def next_smallest_pandigital(P): test_P = str(P)[:-2] + str(P)[7:][::-1] if int(test_P) < int(P): return test_P for d in range(3, 10): base = str(P)[:-d] chad = str(P)[9 - d:] chads = [''.join(p) for p in perms(chad)] chads = [perm for perm in chads if int(perm) < int(chad)] if len(chads) > 0: max_chad = str(max(map(int, chads))) return int(base + max_chad) else: continue return None
def crosswordFormation(words): from itertools import permutations as perms from collections import defaultdict as ddic ans = 0 for p in perms(words): M = ddic(int) a,b,c,d = p for i in range(2, min(len(a),len(b))): for p in range(len(a) - i): for q in range(len(b) - i): M[a[p],a[p+i],b[q],b[q+i]] += 1 for i in range(2, min(len(c),len(d))): for p in range(len(c) - i): for q in range(len(d) - i): ans += M[c[p],d[q],c[p+i],d[q+i]] return ans
def __perms(lcletters: str) -> List[str]: # There's no inherent ordering to query letters, and we support single words # so, we want both permutations of the letters for faster look-up on smaller # lists, but also single letter look-ups, for one-letter word corner cases single_letter_keys = [ch for ch in lcletters] # Must sync up with index storage mechanism! words less than chunk len # indexed by first letter, so this is safe to do for query. if len(lcletters) < ListIndex.CHUNK_LEN: return single_letter_keys # The larger the query length, the worse this performs, of course, perms lead # to very big numbers. chunked_keys = [''.join(p) for p in perms(lcletters, ListIndex.CHUNK_LEN)] return single_letter_keys + chunked_keys
def answer(times, time_limit): n = len(times) bunns = range(n - 2) if not bunns: return [] # Floyd-Warshall dist = times[:] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] # Infinite negative cycle? Yes if neg. in diag. if [r[i] for i, r in enumerate(dist) if r[i] < 0]: return bunns # Power set P = reduce(lambda z, x: z + [y + [x] for y in z], bunns, [[]]) # Check all permutations of all subsets res = [] for s in [list(p) for sub in P for p in perms(sub)]: # Begin at Start with 0 time current_spot = t = 0 # Visit spots with these bunnies for bunny_spot in [b + 1 for b in s]: t += dist[current_spot][bunny_spot] current_spot = bunny_spot # Go to Bulkhead from last bunny t += dist[current_spot][n - 1] if t <= time_limit and len(res) < len(s): res = sorted(s) # Quit checking permutations of all bunnies if len(res) == n - 2: return res return res
def solve(n, f): answer = False nums = n friends = {} for person in range(len(f)): friends[person+1] = f[person] print friends while not answer: print nums for perm in perms(range(1, n+1), nums): ## print perm success = True for i in range(nums): ## print i+1 if i == 0: if friends[perm[i]] == perm[1] or friends[perm[i]] == perm[-1]: continue else: ## print 'failure' success = False break elif i == nums - 1: if friends[perm[i]] == perm[-2] or friends[perm[i]] == perm[0]: continue else: ## print 'failure' success = False break else: if friends[perm[i]] == perm[i-1] or friends[perm[i]] == perm[i+1]: continue else: ## print 'failure' success = False break if success: print perm return nums nums -= 1 return
def palindrome(a): score = 0 initial_array = list() another_array = list() final_array = list() for char in a: initial_array.append(char) if len(initial_array) <= 10: perm_list = perms(initial_array) for permutation in list(perm_list): another_array.append(permutation) for permutation in another_array: count = 0 if permutation == permutation[::-1]: for element in final_array: if permutation == element: count += 1 if count == 0: score += 1 final_array.append(permutation) if score == 0: print("I didn't find any palindrome.") else: for element in final_array: print("I found a palindrome! It's", end=' ') for char in element: print(char, end='') print("") print(f"This word has {score} permuted palindromes.") else: print("Too many characters.")
def play_perms(): p = Position(ROWS,COLS) L = perms(['0','1','2','3','4','5','6','7','8']) dim = ROWS*COLS fact9 = fact(9) wins = [0]*dim print(wins) for prm in L: #print(prm) #showboard(p.brd, p.R, p.C) stone = BCH p.brd = '.'*dim for j in range(dim): p.brd = change_str(p.brd, int(prm[j]), stone) #showboard(p.brd, p.R, p.C) if has_win(p.brd, stone): wins[j] += 1 break stone = oppCH(stone) print(wins) for j in range(dim): print(j, wins[j], wins[j] / fact9)
def bigchief(alist): l = map(str, alist) return max("".join(x) for x in perms(l))
def plot_depths_hist(x_arr_left, x_arr_right, y_arr_left, y_arr_right, eis_arr, title_lab, out_fig_loc, n_cpus, fig_size, labs=None, self_comp=True): depth_arrs_list = [] hist_labs = [] out_fig_loc = str(out_fig_loc) hist_bins = np.concatenate((np.arange(5), [10000])) thresh_depth = hist_bins[-3] n_dims = x_arr_left.shape[1] arr_perms = list(perms([x_arr_left, x_arr_right, y_arr_left, y_arr_right], 2)) if labs is None: labs = ['x_left', 'x_right', 'y_left', 'y_right'] labs_perms = list(perms(labs, 2)) else: assert len(labs) == 4 labs_perms = list(perms(labs, 2)) if self_comp: for _arr in [x_arr_left, x_arr_right, y_arr_left, y_arr_right]: arr_perms.append((_arr, _arr)) for _labs in labs: labs_perms.append((_labs, _labs)) for arrs, _labs in zip(arr_perms, labs_perms): if arrs[0].shape[0] and arrs[1].shape[0]: _arr = depth_ftn_mp(arrs[1], arrs[0], eis_arr, n_cpus) _arr[_arr > thresh_depth] = thresh_depth depth_arrs_list.append(_arr) hist_labs.append('%s_in_%s' % _labs) _out_path, _out_ext = out_fig_loc.rsplit('.', 1) plt.figure(figsize=fig_size) rwidth = 0.98 items_per_fig = 4 for i, (mins, hist_lab) in enumerate(zip(depth_arrs_list, hist_labs), 1): plt.hist(mins, bins=hist_bins, alpha=0.3, density=True, rwidth=rwidth, label=hist_lab, align='mid') rwidth -= 0.17 if (not (i % items_per_fig)) or (i == len(hist_labs)): hist_title = '' hist_title += (('%s\n' '%d %d-dimensional unit vectors used\n' 'n_%s=%d, n_%s=%d, ' 'n_%s=%d, n_%s=%d') % (title_lab, eis_arr.shape[0], n_dims, labs[0], x_arr_left.shape[0], labs[1], x_arr_right.shape[0], labs[2], y_arr_left.shape[0], labs[3], y_arr_right.shape[0])) plt.title(hist_title) plt.xticks(hist_bins[:-2] + 0.5, (hist_bins[:-3].tolist() + ['>=%d' % thresh_depth])) plt.xlim(hist_bins[0], hist_bins[-2]) plt.ylim(0, 1) plt.legend() plt.grid() plt.savefig(_out_path + ('_%0.2d.%s' % (i, _out_ext)), bbox_inches='tight') rwidth = 0.98 plt.clf() plt.close() return
import string from time import clock from itertools import permutations as perms t = clock() data = eval(open("data/cipher1.txt").read()) chars = dict([(ord(c), c) for c in string.printable]) keys = set(perms(range(61, 123), 3)) sols = [] l = range(len(data)) for key in keys: text = [] flag = True for i in l: c = data[i] ^ key[i % 3] if c not in chars: flag = False break else: text.append(chars[c]) if flag: text = ''.join(text) if ' the ' in text: sols.append(key) if len(sols) == 1: print(sum([data[i] ^ sols[0][i % 3] for i in l])) print(clock() - t)
def is_perm(c, p): all_perms = [int(''.join(s)) for s in perms(str(p))] if c in all_perms: return True
Find the sum of all 0 to 9 pandigital numbers with this property. ''' import time from itertools import permutations as perms def sub_string_divide(n): divisors = [2, 3, 5, 7, 11, 13, 17] num_list = [x for x in n] for d in range(0, 7): if int(num_list[d + 1] + num_list[d + 2] + num_list[d + 3]) % divisors[d] != 0: return False return True #driver code if __name__ == '__main__': start_time = time.time() sum_total = 0 for x in perms('0123456789'): pand = ''.join(x) if sub_string_divide(pand): sum_total += int(pand) print(sum_total) print('Runtime: {}'.format(time.time() - start_time))
def factorial(n): rng = [i * 1.0 for i in range(1, n + 1)] res = 1.0 for i in rng: res *= i return res def n_permutations(n, k): return factorial(n) / factorial(n-k) p_sets_base = [[x for x in perms(i)] for i in sets] p_sets = [i for i in perms(sets)] max_len = len(sets) - 1 for idx, row in enumerate(p_sets[:5]): count = 0 tmp = list() inv_row = [i[::-1] for i in row] for i, _ in enumerate(row): for j, _ in enumerate(inv_row): if i != j: if i < max_len and j < max_len: print(row[i], row[i+1], inv_row[j], inv_row[j + 1])
if a % 100 == b / 100: return True else: return False tri = [x for x in prange(3,200) if x < 10000 and x > 999] rect = [x for x in prange(4,200) if x < 10000 and x > 999] pent = [x for x in prange(5,200) if x < 10000 and x > 999] hex = [x for x in prange(6,200) if x < 10000 and x > 999] hept = [x for x in prange(7,200) if x < 10000 and x > 999] oct = [x for x in prange(8,200) if x < 10000 and x > 999] figurates = [tri, rect, pent, hex, hept, oct] try: for p in perms(figurates): for n1 in p[0]: for n2 in p[1]: if isCyclic(n1,n2): for n3 in p[2]: if isCyclic(n2,n3): for n4 in p[3]: if isCyclic(n3,n4): for n5 in p[4]: if isCyclic(n4,n5): for n6 in p[5]: if isCyclic(n5,n6) and isCyclic(n6,n1): print [n1,n2,n3,n4,n5,n6],n1+n2+n3+n4+n5+n6 raise GetOutOfLoop() except GetOutOfLoop: pass
from time import clock from itertools import permutations as perms t = clock() primes = set([2, 3]) pandsets = [] for n in range(2, 8): digits = range(1, n + 1) if not sum(digits) % 3 == 0: pandsets.append(digits) primepands = set() for pandset in pandsets: for perm in perms(pandset): n = int(''.join(str(num) for num in perm)) flag = True for prime in primes: if n % prime == 0: flag = False break for div in range(max(primes), int(n ** 0.5) + 1, 2): if n % div == 0: primes.add(div) flag = False break if flag: primepands.add(n) print(max(primepands)) print(clock() - t)
from itertools import permutations as perms n = int(input('')) s = 'ААООУУЫЫ' s += ('Т' * n)[:-1] l = [] for s in perms(s, n): g = ''.join(list(s)) l.append(g) l = list(set(l)) def isValid(word): words = {'АА', 'ОО', 'УУ', 'АЫ', 'ЫА', 'ОУ', 'УА', 'А', 'О', 'У', 'Ы', ''} a = list(set(word.split('Т'))) if len(a) == 1 and a[0] == '': return False for i in a: if len(i) > 2: return False if i not in words: return False return True counter = 0 for b in l: if isValid(b): counter += 1 print(counter % 2021)
# for all odd numbers. for x in range(3, int(n**0.5) + 1, 2): if n % x == 0: return False return True def is_pandigital(n_str): if '0' in n_str: return False for i in n_str: if int(i) > len(n_str): return False n_len = len(n_str) n_set = set(n_str) if n_len == len(n_set): return True return False primes = [] # Generate all pandigital permutations, starting with 7 digit numbers and working down. for x in range(8, 5, -1): nums = perms(xrange(1, x)) for s in nums: n = ''.join([str(i) for i in s]) if is_pandigital(n) and is_prime(int(n)): primes.append(int(n)) primes.sort() print primes[len(primes) - 1]
def key_generator(): alphabet = "abcdefghijklmnopqrstuvwxyz" for perm in perms(alphabet, 3): yield [ binary(ord(c)) for c in perm]
from time import clock from math import log10 from itertools import permutations as perms def isSol(pand): for i in range(1, 5): n = pand div, n = int(n[:i]), n[i:] mul = 2 * div while n.find(str(mul)) == 0: mul += div n = n[int(log10(mul)) + 1:] if not n: return True return False t = clock() pands = perms(['9','8','7', '6', '5', '4', '3', '2', '1']) for pand in pands: pand = ''.join(pand) if isSol(pand): print pand, clock() - t break
from itertools import permutations as perms digits = [9, 8, 7, 6, 5, 4, 3, 2, 1] pands = perms(digits) def digitsToNum(nums): return ''.join(map(str, nums)) for i in range(1, 5): n = "192384576" div, n = int(n[:i]), n[i - 1:] check = str(2 * div) while n[i:].find(check) == 0: print div
netat = tuple(netat) if (all(b==c for b,c in etat if c!=-1)): done[etat] = 1 return 1 done[etat] = 0 res = compute(nb_places, nb_bases, netat) done[etat] = res return res if __name__=='__main__': nb_bases = 4 nb_places = 3 all_states = set(tuple(sorted((i%nb_bases, p) for i, p in zip(range(nb_places*nb_bases), perm))) for perm in perms(range(-1,nb_bases-1) + range(nb_bases)*(nb_places-1))) # compute the outcome of all states for e in all_states: compute(nb_places, nb_bases, e) print "Nb bases:",nb_bases,"; Nb colors:",nb_places,"; Nb states:", len(all_states) all_res = Counter(done[e] for e in all_states) # Prepare the filtering initial_states = all_states # filter out all states where someone is already home: we never take such states as initial states initial_states = filter(lambda x: all(b!=p for b,p in x), initial_states) res_nobody_home = Counter(done[e] for e in initial_states) # filter out all states where 2 guys of the same color are at the same base: we never take such states as initial states initial_states = filter(lambda e: filter(lambda x: x[1]==2 and x[0]!=x[1], Counter(e).items()), initial_states)
def lex_perms(n=1000000): return int(''.join([p for p in perms('0123456789')][n-1]))