def original_solution(): """runtime on mbp is 51ms""" # generate all possible 16 digit strings that have 6-10 as external nodes, and start with 6 # so, that's 6 + {all permutations of 7-10} on the outside, and all permutations of 1-5 on the inside # filter down to the ones that are magic, choose the max. best = 0 for outside in permutations([7,8,9,10]): for inside in permutations([1,2,3,4,5]): l = (6,) + outside + inside if is_magic(l): i = int(''.join(map(str, structure(l)))) print "magic: %d" % i if best < i: best = i return best
def test_point_pattern(self): """ This test checks that the code can compute an observed mean nearest neighbor distance and then use Monte Carlo simulation to generate some number of permutations. A permutation is the mean nearest neighbor distance computed using a random realization of the point process. """ random.seed() # Reset the random number generator using system time # I do not know where you have moved avarege_nearest_neighbor_distance, so update the point_pattern module observed_avg = analytics.average_nearest_neighbor_distance(self.points) self.assertAlmostEqual(0.027, observed_avg, 3) # Again, update the point_pattern module name for where you have placed the point_pattern module # Also update the create_random function name for whatever you named the function to generate # random points rand_points = utils.generate_random_points(100) self.assertEqual(100, len(rand_points)) # As above, update the module and function name. permutations = utils.permutations(99) self.assertEqual(len(permutations), 99) self.assertNotEqual(permutations[0], permutations[1]) # As above, update the module and function name. lower, upper = utils.crit_tations(permutations) self.assertTrue(lower > 0.03) self.assertTrue(upper < 0.07) self.assertTrue(observed_avg < lower or observed_avg > upper) # As above, update the module and function name. significant = utils.check_yer_sig(lower, upper, observed_avg) self.assertTrue(significant)
def original_solution(): """runtime is 323ms on mbp""" poly = [tri, square, penta, hexa, hepta, octa] polys = map(get, poly) answers = set() for p in utils.permutations(polys): candidates = [] # Do the first and last one (special because of wraparound, no tuples) for p_last in p[-1]: candidates.extend([(p_i, p_last) for p_i in p[0] if match(p_last, p_i)]) # Do the middle ones (not special) for i in range(1, 4): candidates = update_candidates(candidates, p[i]) # Do the second-to-last one (special because have to check both ends) final = [] for c in candidates: final.extend([insert(c, p_i) for p_i in p[4] if match(c[-2], p_i) and match(p_i, c[-1])]) # Did we get anything? if len(final): print final, sum(final[0]) return sum(final[0]) return -1
def genKey(key, keyGenType, itr): if keyGenType == 'manual': cipherWord = input("Enter an incorrect word from the plain text: ").upper() plainWord = input("Enter the correct word: ").upper() if len(cipherWord) != len(plainWord): print("Length of words must match! Key failed to update.") return key elif not (cipherWord.isalpha() and plainWord.isalpha()): print("Numbers can not be entered! Key failed to update.") else: cipherWordArray = [] cipherWordArray[:0] = cipherWord plainWordArray = [] plainWordArray[:0] = plainWord inverseKey = dict(zip(key.values(), key.keys())) for i in range(0, len(cipherWordArray)): if cipherWordArray[i] != plainWordArray[i]: key[inverseKey[cipherWordArray[i]]] = plainWordArray[i] key[inverseKey[plainWordArray[i]]] = cipherWordArray[i] print("Key updated! Try substitution cipher again.") elif keyGenType == 'auto': global PERMS if PERMS is None or itr == 0: PERMS = utils.permutations(key.values(), n=20, unique=True) key = dict(zip(key.keys(), PERMS[itr])) return key
def original_solution(): """runtime on mbp is 51ms""" # generate all possible 16 digit strings that have 6-10 as external nodes, and start with 6 # so, that's 6 + {all permutations of 7-10} on the outside, and all permutations of 1-5 on the inside # filter down to the ones that are magic, choose the max. best = 0 for outside in permutations([7, 8, 9, 10]): for inside in permutations([1, 2, 3, 4, 5]): l = (6, ) + outside + inside if is_magic(l): i = int(''.join(map(str, structure(l)))) print "magic: %d" % i if best < i: best = i return best
def original_solution(): """runtime is 323ms on mbp""" poly = [tri, square, penta, hexa, hepta, octa] polys = map(get, poly) answers = set() for p in utils.permutations(polys): candidates = [] # Do the first and last one (special because of wraparound, no tuples) for p_last in p[-1]: candidates.extend([(p_i, p_last) for p_i in p[0] if match(p_last, p_i)]) # Do the middle ones (not special) for i in range(1, 4): candidates = update_candidates(candidates, p[i]) # Do the second-to-last one (special because have to check both ends) final = [] for c in candidates: final.extend([ insert(c, p_i) for p_i in p[4] if match(c[-2], p_i) and match(p_i, c[-1]) ]) # Did we get anything? if len(final): print final, sum(final[0]) return sum(final[0]) return -1
def gather(A, part): if len(part) == N: return m = index(part) pi = expand(part) for i in xrange(N): for j in xrange(i + 1, N): for k in xrange(j + 1, N): for ii, jj, kk in permutations([i, j, k]): pic = list(pi) pic[i], pic[j], pic[k] = pic[ii], pic[jj], pic[kk] A[m, index(contract(pic))] += 1. / nways_to_choose_swap
def pandigital_products(): pan_prods = [] for _perm in utils.permutations(1, 9): perm = ''.join([str(p) for p in _perm]) for i in range(1, 4): x = int(perm[:i]) for j in range(i + 1, 7): y = int(perm[i:j]) z = int(perm[j:]) if x * y == z and z not in pan_prods: print('{} * {} = {}'.format(x, y, z)) pan_prods.append(z) return sum(pan_prods)
def original_solution(): """ original_solution took 584.394 ms 584.394 ms (write is_int inline instead of as a function call) 741.234 ms (build a table of funcs instead of eval inline) 13419.094 ms (intuition: solution won't have a 0 in it (useless!)) 20296.724 ms (intuition: solution needs to have 1 in it) 50730.742 ms (save list of all operator combos instead of dynamic generation) 51467.405 ms (format instead of 3 string replaces) 53080.543 ms (essential set of combos) 91008.076 ms (initial) The answer (original) is: 1258 """ # all possible combinations of operators olist = [p for p in product(['+', '-', '*', '/'], repeat=3)] # all possible parenthesizations combos = [ '(a %c (b %c c)) %c d', '((a %c b) %c c) %c d', 'a %c (b %c (c %c d))', 'a %c ((b %c c) %c d)', '(a %c b) %c (c %c d)' ] # all possible functions funcs = [ eval('lambda a,b,c,d : %s' % (c % o)) for c in combos for o in olist ] m, answer = 0, '' for numbers in combinations(xrange(1, 10), 4): if not 1 in numbers: continue # intuition about requirements for solution outcomes = set() for a, b, c, d in permutations(numbers): for f in funcs: try: n = f(a, b, c, d) if 0 < n and int(n) == n: outcomes.add(n) except ZeroDivisionError: pass lcr = largest_continuous_range( sorted(outcomes)) #lcr = largest_continuous_range_new(outcomes) if m < lcr: m, answer = lcr, ''.join(map(str, numbers)) print 'new max: %d from %s' % (m, answer) return answer
def main(): """Solves this problem Permutes a list of string digits. Returns the indexed the millionth value. Quite positive this could be dynamically calculated, but the number of permutations is only 10! (factorial) which is ~3.6 million, so not that bad Returns: Integer: Solution to this problem """ digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] perms = permutations(digits) return perms[1000000 - 1]
def list_equivalent_trees(self): """ Returns a list of all strings (subject to our assumptions) equivalent to a given tree INPUT: self -- any rooted tree OUTPUT: treelist -- a list of all the 'legal' tree strings that produce the same tree. The list of equivalent trees is obtained by taking all permutations of the (non-leaf) subtrees. This routine is used to test equality of trees. """ nleaves,subtrees=self._parse_subtrees() if len(subtrees)==0: return [self] for i in range(len(subtrees)): subtrees[i]=str(subtrees[i]) treelist = [RootedTree('{'+_powerString('T',nleaves,powchar='^')+ ''.join(sts)+'}') for sts in permutations(subtrees)] return treelist
def all_equivalent_trees(self): """ Returns a list of all strings (subject to our assumptions) equivalent to a given tree INPUT: self -- any rooted tree OUTPUT: treelist -- a list of all the 'legal' tree strings that produce the same tree. The list of equivalent trees is obtained by taking all permutations of the (non-leaf) subtrees. This routine is used to test equality of trees. """ nleaves,subtrees=self.parse_subtrees() if len(subtrees)==0: return [self] for i in range(len(subtrees)): subtrees[i]=str(subtrees[i]) treelist = [RootedTree('{'+powerString('T',nleaves,powchar='^')+ ''.join(sts)+'}') for sts in permutations(subtrees)] return treelist
def original_solution(): """ original_solution took 584.394 ms 584.394 ms (write is_int inline instead of as a function call) 741.234 ms (build a table of funcs instead of eval inline) 13419.094 ms (intuition: solution won't have a 0 in it (useless!)) 20296.724 ms (intuition: solution needs to have 1 in it) 50730.742 ms (save list of all operator combos instead of dynamic generation) 51467.405 ms (format instead of 3 string replaces) 53080.543 ms (essential set of combos) 91008.076 ms (initial) The answer (original) is: 1258 """ # all possible combinations of operators olist = [p for p in product(['+', '-', '*', '/'], repeat=3)] # all possible parenthesizations combos = ['(a %c (b %c c)) %c d', '((a %c b) %c c) %c d', 'a %c (b %c (c %c d))', 'a %c ((b %c c) %c d)', '(a %c b) %c (c %c d)'] # all possible functions funcs = [eval('lambda a,b,c,d : %s' % (c % o)) for c in combos for o in olist] m, answer = 0, '' for numbers in combinations(xrange(1, 10), 4): if not 1 in numbers: continue # intuition about requirements for solution outcomes = set() for a,b,c,d in permutations(numbers): for f in funcs: try: n = f(a,b,c,d) if 0 < n and int(n) == n: outcomes.add(n) except ZeroDivisionError: pass lcr = largest_continuous_range(sorted(outcomes)) #lcr = largest_continuous_range_new(outcomes) if m < lcr: m, answer = lcr, ''.join(map(str, numbers)) print 'new max: %d from %s' % (m, answer) return answer
def test_check_significant(self): observed_avg = utils.average_nearest_neighbor_distance(self.points) lower, upper = analytics.compute_critical(utils.permutations(99)) significant = analytics.check_significant(lower, upper, observed_avg) self.assertTrue(significant)
def generate_realizations(self, k): return utils.permutations(k)
def create_k_patterns(self, k): return utils.permutations(k)
def multi_divedable_pandigitals(): start_permutation = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for p in utils.permutations(start_permutation): if multi_div_test(p): yield utils.to_int(p) print p
from utils import permutations print("".join(map(str, list(permutations(list(range(10))))[999999])))
from utils import permutations lexiographic_permutations = sorted(permutations(list(range(10)))) print(lexiographic_permutations[1000000 - 1])
def test_compute_critical(self): observed_avg = utils.average_nearest_neighbor_distance(self.points) lower, upper = analytics.compute_critical(utils.permutations(99)) self.assertTrue(lower > 0.03) self.assertTrue(upper < 0.07) self.assertTrue(observed_avg < lower or observed_avg > upper)
def train(self, train_data, valid_data, configs, save=True, path='saved_models/default', verbose=False): best_architectures = utils.permutations( num_new_items=self.search_size[0]) for i in range(1, self.num_layers): if len(best_architectures ) * self.search_size[i] > configs.agent.num_models: break else: best_architectures = utils.permutations( num_new_items=self.search_size[i], inputs=best_architectures) start_num_layers = len(best_architectures[0]) for num_layers in range(start_num_layers, self.num_layers + 1): # Prepare samples if verbose: print('Sampling {}-layer samples.'.format(num_layers)) samples_path = os.path.join(path, '{}-layer-samples'.format(num_layers)) if os.path.isdir(samples_path): samples, accs = self._load_samples(samples_path) else: samples = best_architectures accs = [] for sample in samples: layers = [self.search_space[ID] for ID in sample] model = self.build_model(layers, self.architecture[:num_layers], self.task_info) accuracy = model.train( train_data=train_data, valid_data=valid_data, num_epochs=configs.model.num_epochs, learning_rate=configs.model.learning_rate, save_history=False, verbose=False) accs.append(accuracy) if save: self._save_samples(samples, accs, samples_path) # Train accuracy predictor if verbose: print('Training predictor for {}-layer models.'.format( num_layers)) self.predictor.update( samples=samples, accuracies=accs, num_epochs=configs.predictor.num_epochs, learning_rate=configs.predictor.learning_rate) # Mutate next layer if num_layers + 1 < self.num_layers: if verbose: print('Mutating {}-layer samples.'.format(num_layers)) best_architectures = utils.permutations( num_new_items=self.search_size[num_layers], inputs=best_architectures) accs = self.predictor.predict( best_architectures).detach().cpu().numpy() accs_order = accs.argsort()[::-1] best_architectures = np.array(best_architectures) best_architectures = best_architectures[ accs_order][:configs.agent.num_candidate_models] accs = accs[accs_order][:configs.agent.num_candidate_models] model_sizes = [] for architecture in best_architectures: layers = [self.search_space[ID] for ID in architecture] model_sizes.append( utils.estimate_model_size( layers=layers, num_tasks=self.task_info.num_tasks, architecture=self.architecture[:num_layers + 1], num_channels=self.task_info.num_channels)) objectives = [(acc, -model_size) for (acc, model_size) in zip(accs, model_sizes)] _, idx = utils.pareto_front(objectives, num=configs.agent.num_models) best_architectures = best_architectures[idx].tolist() if save: if verbose: print('Training final models.') architectures = [] accs = [] model_sizes = [] for architecture in best_architectures: layers = [self.search_space[ID] for ID in architecture] model = self.build_model(layers, self.architecture, self.task_info) accuracy = model.train( train_data=train_data, valid_data=valid_data, num_epochs=configs.model.num_epochs, learning_rate=configs.model.learning_rate, save_history=False, verbose=False) architectures.append(layers) accs.append(accuracy) model_sizes.append(model.size) self.save(architectures, accs, model_sizes, os.path.join(path, 'final'))
def test_permutations(self): permutations = utils.permutations(99) self.assertEqual(len(permutations), 99) self.assertNotEqual(permutations[0], permutations[1])