def edit_ad(url): room = Room.query.filter_by(urlname=url).first() if not room and room.user == g.user: abort(404) if room.dead or get_days_ago(room.created_at) > OLD_DAYS.days: abort(404) occupied = Occupied.query.filter_by(space=room.occupieds).order_by("created_at").first() if occupied and get_days_ago(occupied.created_at) > OCCUPIED_DAYS.days: abort(404) if room.is_available: form = AvailableAdForm() else: form = WantedAdForm() form.starting.flags.is_date = True if request.method == "GET": form.process(obj=room) if room.is_available: form.room_pref.data = factorize(room.room_pref) else: form.room_type.data = factorize(room.room_type) form.email.data = g.user.email elif form.validate_on_submit(): if room.is_available: form.room_pref.data = product(form.room_pref.data) else: form.room_type.data = product(form.room_type.data) form.populate_obj(room) db.session.commit() return redirect(url_for("view_ad", url=room.urlname)) return render_template("autoform.html", form=form, title="Edit advertisement", submit="Save")
def post_ad(state="available"): is_available = state == "available" if is_available: form = AvailableAdForm() else: form = WantedAdForm() form.starting.flags.is_date = True if request.method == "GET": form.email.data = g.user.email if form.validate_on_submit(): room = Room(user=g.user, is_available=is_available) if room.is_available: form.room_pref.data = product(form.room_pref.data) else: form.room_type.data = product(form.room_type.data) form.populate_obj(room) room.urlname = str(uuid4())[:8] db.session.add(room) db.session.commit() # Search for matching rooms rooms_distance = Room.search_rooms(room) # Send emails to interested users for r, distance in rooms_distance: if room.is_available: # ad poster is looking for a person send_email_found_room(r.user, room, distance) else: # ad poster is looking for a room. send_email_found_person(r.user, room, distance) flash("Your ad has been posted!", category="info") return render_template("found.html", room=room, rooms_distance=rooms_distance) return render_template("autoform.html", form=form, title="Post a new advertisement", submit="Post ad")
def baseline_KL(real_data, fake_data): """ Calculate the Kullback-Leibler divergence from the null hypothesis (sample nouns and verbs according to frequency) to two sets of data :param real_data: first set of tuples :param fake_data: second set of tuples :return: (real KLs, fake KLs), each for (SVO, SV, VO) subsets """ real_prob = separate_prob(real_data) fake_prob = separate_prob(fake_data) noun_prob = pred_freq * noun_mask / pred_freq[nouns].sum() verb_prob = pred_freq * verb_mask / pred_freq[verbs].sum() both_prob = noun_prob + verb_prob real_match = [{tup: product(both_prob[p] for p in tup) for tup in c} for c in real_prob] fake_match = [{tup: product(both_prob[p] for p in tup) for tup in c} for c in fake_prob] real_KL = [KL(real_prob[i], real_match[i]) for i in range(3)] fake_KL = [KL(fake_prob[i], fake_match[i]) for i in range(3)] return real_KL, fake_KL
def step_0(u): u['M'] = u['g1']**u['m'][0] * product( [Z**m for Z, m in zip(u['Z'], u['m'][1:])]) u['r'] = G.random(ZR, len(u['m'])) u['T'] = u['g1']**u['r'][0] * product( [Z**r for Z, r in zip(u['Z'], u['r'][1:])]) return {'M': u['M'], 'T': u['T']}
def cell_likelihood(reads,ps): points = sorted(concat(reads)) G = len(ps) if not 0 in points: points.append(0) if not G in points: points.append(G) read_complements = [(stop)] return product([product(1-p for p in ps[start:stop]) for (start,stop) in reads])
def __init__(self, shape, physical_size, values=None): from utils import product #super(PhysicalGrid, self).__init__(shape=shape) if len(shape) != len(physical_size): raise GridError() self.shape = shape self.size = map(float, physical_size) self.volume = product(physical_size) self.increments = map(lambda x, y: x / y, self.size, shape) self.values = values self.no_elements = product(shape)
def productGen( matrix ): n = 20 for i in xrange( n ): for j in xrange( n ): V, Vb = j <= 16, j >= 3 H, Hb = i <= 16, i >= 3 if V: yield product( matrix[ i ][ j + k ] for k in xrange( 4 ) ) if H: yield product( matrix[ i + k ][ j ] for k in xrange( 4 ) ) if H and V: yield product( matrix[ i + k ][ j + k ] for k in xrange( 4 ) ) if Hb and V: yield product( matrix[ i - k ][ j + k ] for k in xrange( 4 ) )
def _weight_variable(shape, name): # If shape is [5, 5, 20, 32], then each of the 32 output planes # has 5 * 5 * 20 inputs. number_inputs_added = utils.product(shape[:-1]) stddev = 1 / math.sqrt(number_inputs_added) # http://neuralnetworksanddeeplearning.com/chap3.html#weight_initialization return tf.Variable(tf.truncated_normal(shape, stddev=stddev), name=name)
def get_quantities_score(self, quantities: Tuple[int, ...]) -> int: """ >>> IngredientSet.from_ingredients_text( ... "Butterscotch: capacity -1, durability -2, flavor 6, " ... "texture 3, calories 8\\n" ... "Cinnamon: capacity 2, durability 3, flavor -2, texture -1, " ... "calories 3\\n" ... ).get_quantities_score((44, 56)) 62842880 >>> IngredientSet.from_ingredients_text( ... "Butterscotch: capacity -1, durability -2, flavor 6, " ... "texture 3, calories 8\\n" ... "Cinnamon: capacity 2, durability 3, flavor -2, texture -1, " ... "calories 3\\n" ... ).get_quantities_score((10, 90)) 0 """ if len(quantities) != len(self.ingredients): raise Exception( f"Expected {len(self.ingredients)} quantities, but got " f"{len(quantities)}") return product( max( 0, sum( getattr(ingredient, _property) * quantity for quantity, ingredient in zip(quantities, self.ingredients))) for _property in self.SCORE_PROPERTIES)
def solve2(buses, depart): """Find the smallest timestamp, such that all the <buses> follow their bus ID, which is indexically paired with <depart>. Here I used the Chinese Remainder Theorem, someone well acquainted to anyone who does competitive or discrete mathematics. """ # Desired residue class for each bus. mods = [(b - d) % b for b, d in zip(buses, depart)] # Cross multiplication of the elements in the sequence. cross_mul = [product(buses) // b for b in buses] return sum( [c * pow(c, -1, b) * m for b, c, m in zip(buses, cross_mul, mods)]) % product(buses)
def horizontal_adjacent_numbers(k: int = 4) -> int: prod = 1 for i in range(20): for j in range(20 - k + 1): adjacent_numbers = matrix[i][j:j+k] prod = max(prod, product(adjacent_numbers)) return prod
def vertical_adjacent_numbers(k: int = 4) -> int: prod = 1 for i in range(20 - k + 1): for j in range(20): adjacent_numbers = [matrix[i+idx][j] for idx in range(k)] prod = max(prod, product(adjacent_numbers)) return prod
def chinese_remainder(remainders): total = 0 prod = utils.product(remainders.keys()) for bus, remainder in remainders.items(): p = prod // bus total += remainder * mul_inv(p, bus) * p return total % prod
def solve_linear_congruence_system( divisors_and_remainders: Iterable[Tuple[int, int]]) -> int: """ >>> solve_linear_congruence_system([(3, 2), (5, 3), (7, 2)]) 23 """ divisors = [ divisor for divisor, _ in divisors_and_remainders ] non_co_prime_divisors = utils.get_non_co_primes(divisors) if non_co_prime_divisors: raise Exception( f"Some divisors are not co-prime: {non_co_prime_divisors}") divisors_product = utils.product(divisors) coefficients_pairs = ( get_bezout_coefficients(divisor, divisors_product // divisor) for divisor in divisors ) a_solution = sum( remainder * coefficient * divisors_product // divisor for (divisor, remainder), (_, coefficient) in zip(divisors_and_remainders, coefficients_pairs) ) return a_solution % divisors_product
def anti_diagonal_adjacent_numbers(k: int = 4) -> int: prod = 1 for i in range(20 - k + 1): for j in range(19, k - 2, -1): adjacent_numbers = [matrix[i+idx][j-idx] for idx in range(k)] prod = max(prod, product(adjacent_numbers)) return prod
def part2() -> int: total = 0 for ds in DATA: total += 2 * (ds[0] + ds[1]) total += utils.product(ds) return total
def diagonal_left_right_max(A, length): M = len(A) N = len(A[0]) prods = [[0 for j in range(N-length)] for i in range(M-length)] for i in range(M-length): for j in range(N-length): prods[i][j] = product(A[i+x][j+x] for x in range(length)) return max(max(row) for row in prods)
def horizontal_max(A, length): M = len(A) N = len(A[0]) prods = [[0 for j in range(N-length)] for i in range(M)] for i in range(M): for j in range(N-length): prods[i][j] = product(A[i][j:j+length]) return max(max(row) for row in prods)
def step_7(v): """ Verifier - Verify """ lhs = v['td'] prod = product([pair(v['X'], B)**s for B, s in zip(v['Bt'], v['s'])]) rhs = pair(v['g'], v['Ct'])**v['c'] * pair(v['X'], v['At'][0])**v['sa'] * prod accept = lhs == rhs return {"Accept": accept}
def compare_KL(model, real_data, fake_data, samples=(100, 100, 100), **kwargs): """ Approximately calculate the Kullback-Leibler divergence from the model to two sets of data :param model: the sem-func model :param real_data: first set of tuples :param fake_data: second set of tuples :param samples: number of samples to draw, for: SVO, SV, VO graphs :return: (real KLs, fake KLs), each for (SVO, SV, VO) subsets """ # Get sample probabilities from the data real_prob = separate_prob(real_data) fake_prob = separate_prob(fake_data) # Initialise counts for generated samples real_match = [{tup: 0 for tup in c} for c in real_prob] fake_match = [{tup: 0 for tup in c} for c in fake_prob] # Sample from the model sampler = [ model.sample_background_svo, model.sample_background_sv, model.sample_background_vo ] for i in range(3): # Sample entities for each graph configuration for ents in sampler[i](samples=samples[i], **kwargs): # For the sampled entities, find the distribution over predicates pred_dist = [model.pred_dist(e) for e in ents] # Add the probability that this sample would generate the observed predicates for preds in real_match[i]: real_match[i][preds] += product(pred_dist[j][p] for j, p in enumerate(preds)) for preds in fake_match[i]: fake_match[i][preds] += product(pred_dist[j][p] for j, p in enumerate(preds)) # Average the probabilities for preds in real_match[i]: real_match[i][preds] /= samples[i] for preds in fake_match[i]: fake_match[i][preds] /= samples[i] real_KL = [KL(real_prob[i], real_match[i]) for i in range(3)] fake_KL = [KL(fake_prob[i], fake_match[i]) for i in range(3)] return real_KL, fake_KL
def get_lcm(l): factor_lists = [get_prime_factors(e) for e in l] factors = get_factor_set(factor_lists) d = defaultdict(int) for factor in factors: for fl in factor_lists: if fl.count(factor) > d[factor]: d[factor] = fl.count(factor) return product([k**v for k,v in d.items()])
def few_liberties_feature(position): feature = position.get_liberties() onehot_features = np.zeros(feature.shape + (3, ), dtype=np.uint8) onehot_index_offsets = np.arange(0, utils.product(onehot_features.shape), 3) + feature.ravel() nonzero_elements = ((feature != 0) & (feature <= 3)).ravel() nonzero_index_offsets = onehot_index_offsets[nonzero_elements] - 1 onehot_features.ravel()[nonzero_index_offsets] = 1 return onehot_features
def agg_gen_challange(sk, F, Mid): """ Aggregated challange generation """ Lfs = [agg_poly(sk, fid, Mid) for fid in F] r = G.random() xc = G.random() # xc != m foreach m in f Lf, *_ = Lfs Kf = product(g**(r * Lf(xc)) for Lf in Lfs) H = (g**r, xc, g**(r * Lf[0])) return (Kf, H)
def propensity(self, stoich_vector, rate_constant): choices = [choose(x_j, -v_j) for x_j, v_j in zip(self.state, stoich_vector) if v_j < 0] # print choices propensity = rate_constant * product(choices) # print "state:",self.state,"stoich:",stoich_vector,"rate const:",rate_constant,"prop:",propensity if propensity < 0: print "propensity less than zero:", stoich_vector, rate_constant raise Exception return propensity
def iterate_neighbors(): for k in itertools.product(range(-max_order, max_order + 1), repeat=len(gens)): if all(kk == 0 for kk in k): continue g = utils.product((gens[i]**k[i] for i in xrange(1, len(gens))), gens[0]**k[0]) for pt in basepoints: acted = pt.act_with(g) yield pt.act_with(g)
def chinese_remainder(a, n): N = product(n) output = 0 for ni, ai in zip(n, a): _, s = extended_euclide(ni, N // ni) output += ai * s * N // ni # print(ai, s, N//ni) return output % N
def step_4(u): u["r'"], u["r''"], u['ra'], *u['r'] = G.random(ZR, len(u['m']) + 3) u['At'] = [A**u["r'"] for A in u['A']] u['Bt'] = [B**u["r'"] for B in u['B']] u['Ct'] = u['C']**(u["r'"] * u["r''"]) prod = product([pair(u['X'], Bt)**r for Bt, r in zip(u['Bt'], u['r'])]) u['td'] = pair(u['X'], u['At'][0])**u['ra'] * prod return {'At': u['At'], 'Bt': u['Bt'], 'Ct': u['Ct'], 'td': u['td']}
def step_7(v): """ Verifier - Verify """ lhs = v['td']**v['ω'] prod = product([pair(S, B) for S, B in zip(v['S'], v['Bt'])]) rhs = pair(v['g']**(v['ω'] * v['c']), v['Ct']) * pair( v['Xd'], v['At'][0])**v['sa'] * prod accept = lhs == rhs return {"Accept": accept}
def do( N ): ways = ( choose( 25, N ) * product( xrange( 75, 100 - N ) ) * fact( 75 ) ) all = fact( 100 ) ret = ways * 10 ** 50 / all import sys print >>sys.stderr, (ret, N) return ret
def part2() -> int: tests = [ (1, 1), (3, 1), (5, 1), (7, 1), (1, 2), ] return utils.product(check_slope(DATA, dx, dy) for (dx, dy) in tests)
def coprime_congruence_classes(self, primes): modulus = utils.product(primes) coprime_congruence_classes = set([num for num in range(1, modulus)]) for prime in primes: prime_multiple = prime while prime_multiple < modulus: coprime_congruence_classes.discard(prime_multiple) prime_multiple += prime coprime_congruence_classes = list(coprime_congruence_classes) coprime_congruence_classes.sort() return coprime_congruence_classes, modulus
def make_onehot(feature, planes): onehot_features = np.zeros(feature.shape + (planes,), dtype=np.uint8) capped = np.minimum(feature, planes) onehot_index_offsets = np.arange(0, product(onehot_features.shape), planes) + capped.ravel() # A 0 is encoded as [0,0,0,0], not [1,0,0,0], so we'll # filter out any offsets that are a multiple of $planes # A 1 is encoded as [1,0,0,0], not [0,1,0,0], so subtract 1 from offsets nonzero_elements = (capped != 0).ravel() nonzero_index_offsets = onehot_index_offsets[nonzero_elements] - 1 onehot_features.ravel()[nonzero_index_offsets] = 1 return onehot_features
def main(): N = 12000 mps, results = [maxint for i in xrange(N - 1)], set() for x in xrange(4, 2 * N + 1): for factors in factorizations(x): k = len(factors) + product(factors) - sum(factors) if k > 1 and k <= N: mps[k - 2] = min(mps[k - 2], x) for number in mps: results.add(number) print sum(results)
def markov_blanket_sample(X, e, bn): """Retornar uma amostra de P (X | mb) onde mb denota que a Variáveis no cobertor de Markov de X tomam seus valores do evento E (que deve atribuir um valor a cada). A manta de Markov de X é X pais, filhos e pais das crianças.""" Xnode = bn.variable_node(X) Q = ProbDist(X) for xi in bn.variable_values(X): ei = extend(e, X, xi) Q[xi] = Xnode.p(xi, e) * product( Yj.p(ei[Yj.variable], ei) for Yj in Xnode.children) return probability(Q.normalize()[True])
def __init__(self, enc_out_features): super(MNISTDenseClassifier2, self).__init__() if is_iterable(enc_out_features): enc_out_features = product(enc_out_features) self.classifier = nn.Sequential( nn.Linear(enc_out_features, 1000), nn.ReLU(), nn.Linear(1000, 10), nn.LogSoftmax(dim=1), )
def factorizations(x): factorization, listes = factors(x), [[x]] for n_factors in range(1, len(factorization)): for combination in combinations(factorization, n_factors): p = product(combination) for facto in factorizations(x / p): liste = [p] liste.extend(facto) liste = sorted(liste) if liste not in listes: listes.append(liste) return listes
def make_onehot(feature, planes): onehot_features = np.zeros(feature.shape + (planes,), dtype=np.uint8) capped = np.minimum(feature, planes) onehot_index_offsets = np.arange(0, product( onehot_features.shape), planes) + capped.ravel() # A 0 is encoded as [0,0,0,0], not [1,0,0,0], so we'll # filter out any offsets that are a multiple of $planes # A 1 is encoded as [1,0,0,0], not [0,1,0,0], so subtract 1 from offsets nonzero_elements = (capped != 0).ravel() nonzero_index_offsets = onehot_index_offsets[nonzero_elements] - 1 onehot_features.ravel()[nonzero_index_offsets] = 1 return onehot_features
def compare_KL(model, real_data, fake_data, samples=(100,100,100), **kwargs): """ Approximately calculate the Kullback-Leibler divergence from the model to two sets of data :param model: the sem-func model :param real_data: first set of tuples :param fake_data: second set of tuples :param samples: number of samples to draw, for: SVO, SV, VO graphs :return: (real KLs, fake KLs), each for (SVO, SV, VO) subsets """ # Get sample probabilities from the data real_prob = separate_prob(real_data) fake_prob = separate_prob(fake_data) # Initialise counts for generated samples real_match = [{tup: 0 for tup in c} for c in real_prob] fake_match = [{tup: 0 for tup in c} for c in fake_prob] # Sample from the model sampler = [model.sample_background_svo, model.sample_background_sv, model.sample_background_vo] for i in range(3): # Sample entities for each graph configuration for ents in sampler[i](samples=samples[i], **kwargs): # For the sampled entities, find the distribution over predicates pred_dist = [model.pred_dist(e) for e in ents] # Add the probability that this sample would generate the observed predicates for preds in real_match[i]: real_match[i][preds] += product(pred_dist[j][p] for j,p in enumerate(preds)) for preds in fake_match[i]: fake_match[i][preds] += product(pred_dist[j][p] for j,p in enumerate(preds)) # Average the probabilities for preds in real_match[i]: real_match[i][preds] /= samples[i] for preds in fake_match[i]: fake_match[i][preds] /= samples[i] real_KL = [KL(real_prob[i], real_match[i]) for i in range(3)] fake_KL = [KL(fake_prob[i], fake_match[i]) for i in range(3)] return real_KL, fake_KL
def markov_blanket_sample(X, e, bn): """Return a sample from P(X | mb) where mb denotes that the variables in the Markov blanket of X take their values from event e (which must assign a value to each). The Markov blanket of X is X's parents, children, and children's parents.""" Xnode = bn.variable_node(X) Q = ProbDist(X) for xi in bn.variable_values(X): ei = extend(e, X, xi) # [Equation 14.12] Q[xi] = Xnode.p(xi, e) * product(Yj.p(ei[Yj.variable], ei) for Yj in Xnode.children) # (assuming a Boolean variable here) return probability(Q.normalize()[True])
def index(request): values_strings = request.GET.getlist('values') try: values_ints = map(int, values_strings) except ValueError as e: err_result = {'details': str(e) } err_result.update(ERROR_MSG_INVALID_INPUT) json_output = json.dumps(err_result) return HttpResponse(json_output, status=400) vsum = sum(values_ints) vproduct = product(values_ints) json_output = json.dumps({'sum': vsum, 'product': vproduct}) return HttpResponse(json_output)
def problem_008(series: int = 13, n: str = n) -> int: """ Straightforward solution using slicing window and product function. - O(n * series) time-complexity - O(1) space-complexity """ prod = 0 for i in range(len(n) - series + 1): adjacent_digits = n[i:i + series] prod = max(prod, product([int(digit) for digit in adjacent_digits ])) # compare current and new products return prod
def alpha81(df): """ Alpha#81 ((rank(Log(product(rank((rank(correlation(vwap, sum(adv10, 49.6054), 8.47743))^4)), 14.9655))) < rank(correlation(rank(vwap), rank(volume), 5.07914))) * -1) """ temp = u.rank( np.log( u.product( u.rank( u.rank(u.corr(df.vwap, u.ts_sum(u.adv(df, 10), 50), 8))**4), 15))) return ((temp < u.rank(u.corr(u.rank(df.vwap), u.rank(df.volume), 5))) * -1)
def markov_blanket_sample(X, e, bn): """Return a sample from P(X | mb) where mb denotes that the variables in the Markov blanket of X take their values from event e (which must assign a value to each). The Markov blanket of X is X's parents, children, and children's parents.""" Xnode = bn.variable_node(X) Q = ProbDist(X) for xi in bn.variable_values(X): ei = extend(e, X, xi) # [Equation 14.12:] Q[xi] = Xnode.p(xi, e) * product(Yj.p(ei[Yj.variable], ei) for Yj in Xnode.children) # (assuming a Boolean variable here) return probability(Q.normalize()[True])
def step_3(i): lhs = i['T'] rhs = i['M']**i['c'] * i['g1']**i['s'][0] * product( [Z**s for Z, s in zip(i['Z'], i['s'][1:])]) if lhs != rhs: raise ValueError("Step3 fuckup on check") a0 = G.random(ZR) i['A'] = [i['g1']**a0] i['A'] += [i['A'][0]**z for z in i['z']] i['B'] = [A**i['y'] for A in i['A']] i['C'] = i['A'][0]**i['x'] * i['M']**(a0 * i['x'] * i['y']) return {'A': i['A'], 'B': i['B'], 'C': i['C']}
def alpha29(df): """ Alpha#29 (min(product(rank(rank(scale(log(sum(ts_min(rank(rank((-1 * rank(delta((close - 1), 5))))), 2), 1))))), 1), 5) + ts_rank(delay((-1 * returns), 6), 5)) """ temp1 = u.scale( np.log( u.ts_sum( u.ts_min( u.rank(u.rank((-1 * u.rank(u.delta((df.close - 1), 5))))), 2), 1))) temp2 = u.product(u.rank(u.rank(temp1)), 1) temp3 = u.ts_rank(u.delay((-1 * df.returns), 6), 5) return (np.where(temp1 < temp2, temp1, temp2) + temp3)
def bayes(self, party, party_tweets, sample_freq_list): prob_of_party = len(party_tweets) / len(self.tweets) feature_probs = [] # iterate over every word (boolean flag) for i in xrange(0, len(sample_freq_list)): # P(A|B) = P(B|A) * P(A) / P(B) # P(match|party) = P(party|match) * P(match) / P(party) # = P(match) # because we're only looking at the party's tweets matching_fn = lambda test_tweet: test_tweet.freq_list[i] == sample_freq_list[i] matching_tweets = filter(matching_fn, party_tweets) probability = len(matching_tweets) / len(party_tweets) feature_probs.append(probability) combined = prob_of_party * utils.product(feature_probs) return combined
def statistical_mutual_information(ngram, text): """ Return the probability of all the terms of the ngram to appear together. Do we may consider the stop_words ? """ candidates = [(k, v) for k, v in enumerate(ngram) if normalize_token(v) not in stop_words \ and not v.isdigit() and len(v) > 1] alone_count = {} if len(candidates) == 0: return 0.1 for candidate in candidates: next = candidates.index(candidate) < len(candidates) - 1 \ and candidates[candidates.index(candidate) + 1] \ or None previous = candidates.index(candidate) > 0 \ and candidates[candidates.index(candidate) - 1] \ or None alone_count[candidate] = 0 indexes = [ idx for idx, value in enumerate(text) if value == candidate[1] ] for idx in indexes: if next is not None: positions_diff = next[0] - candidate[0] if idx >= len(text) - (positions_diff + 1) \ or not text[idx+positions_diff] == next[1]: #we are close end of text, next can't be found alone_count[candidate] += 1 if previous is not None: positions_diff = candidate[0] - previous[0] if idx < positions_diff \ or not text[idx-positions_diff] == previous[1]: #we are close beggin of text, preivous can't be found alone_count[candidate] += 1 res = [v for k,v in alone_count.items()] # print [v for v in alone_count.items()] if 0 in res: return 1 else: return product([1.0 * len(ngram) / (len(ngram) + v) for v in res])
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 qCombination_square(n, k): # TODO: if n >= k >= 0: return utils.product(fun=lambda x: QAnalogue.qNumber(2 * x), start=0, end=n) / \ utils.product(fun=lambda x: QAnalogue.qNumber(2 * x), start=0, end=k) / \ utils.product(fun=lambda x: QAnalogue.qNumber(2 * x), start=0, end=n - k) return 0
import itertools from utils import fast_prime_stream, fast_prime_posneg_stream, product def triple_stream(): # This will not generate all triples. # Need to multiply these by a constant to generate all. for a in itertools.count(2): for b in range(2, a): # Euclid's formula yield (a**2 - b**2, 2*a*b, a**2 + b**2) def triple_children(t): for e in itertools.count(1): yield map(lambda n: n * e, t) if __name__ == "__main__": for t in triple_stream(): for c in triple_children(t): s = sum(c) if s == 1000: print c print product(c) if s > 1000: break
def falling_fac(n,k): return product([n-j for j in range(k)])
30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 """ from utils import product BIGNUMSTR = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" prod = 0 for i in range(0, len(BIGNUMSTR)): slicestr = BIGNUMSTR[i:i+13] numbers = [int(slicestr[i]) for i in range(len(slicestr))] thisprod = product(numbers) if thisprod > prod: prod = thisprod print prod
def weight(ss): return (falling_fac(q,sum(ss))*product(k**s for k,s in zip(ks,ss)))
def p_first_occ_at_i(strand,start,stop,hyp,i): if strand == '+': return hyp[i%G]*product((1-hyp[j%G]) for j in xrange(start,i,+1)) else: return hyp[i%G]*product((1-hyp[j%G]) for j in xrange(stop,i,-1))
def class_probability(targetval): return (target_dist[targetval] * product(attr_dists[targetval, attr][example[attr]] for attr in dataset.inputs))
from utils import product from pyprimes import factors from itertools import combinations target = 2 * 2 * 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 count, primes = 0, list(set(factors(target))) for i in xrange(len(primes) + 1): for comb in combinations(primes, i): count += (-1) ** i * product(comb) R = abs(count) * target / product(primes) print target print R print target - 1 print R / float(target - 1) print 15499. / 94744. print R / float(target - 1) < 15499. / 94744.
def mat_permanent(M): m = M.rows n = M.cols return sum(product(M[i,perm[i]] for i in range(m)) for perm in itertools.permutations(range(n)))
def esp_ref(ks,j): """compute jth elementary symmetric polynomial on ks""" n = len(ks) return sum(product(rslice(ks,comb)) for comb in itertools.combinations(range(n),j))