def draw_bonds(self, ax, atom_coord=None, atom_names=None, **kwargs): """ Draw atomic bonds onto a matplotlib axis object. Params: - ax: Matplotlib axis object - atom_coord: List of atomic coordinates (not necessarily the original one in order to use a supercell). - atom_namse: List of atom names (same shape as atom_coord). Used to plot the proper color and atomic radius. """ from itertools import combinations_with_replacement as cwr if atom_coord is None: atom_coord = self.atoms_coord_cart if atom_names is None: atom_names = self.atoms_typ trees, names, rad = split_atom_list_by_name(atom_coord, atom_names) for rad_t, (tree1,tree2), (name1,name2) in zip(cwr(rad,2), cwr(trees,2), cwr(names,2)): bonds = tree1.query_ball_tree(tree2, sum(rad_t)) c1 = periodic_table[name1]['color'] c2 = periodic_table[name2]['color'] for i1,b in enumerate(bonds): for i2 in b: if i1 == i2 and tree1 == tree2: continue start = tree1.data[i1] end = tree2.data[i2] cg.draw_bond(ax, start, end, c1, c2, **kwargs)
def seq_gen(n): p = [2, 3] q = [6, 7, 8, 9] r = [] if n > 1: for i in p: r += [(i, ) + j for j in cwr(q, n - 1)] r += [i for i in cwr(q, n)] r = [int(''.join(str(k) for k in i)) for i in r] else: r = [2, 3, 6, 7, 8, 9] return r
def car2sph(sh, cart, orderedp=True): """Cartesian to spherical transform matrices. .. code-block:: python sh = solid_harmonics(8) # symbolic solid harmonics cart = gen_enum_cartesian(8) # cartesian powers in a defined order c2s = car2sph(sh, cart) # dictionary of {l: transform_matrix} Args: sh (OrderedDict): symbolic solid harmonics cart (OrderedDict): cartesian powers in a defined order orderedp (bool): order l=1 as ['x', 'y', 'z'], not [-1, 0, 1] (default True) Returns: c2s (OrderedDict): cartesian to spherical transform matrices """ c2s = OrderedDict([(L, np.zeros(((L + 1) * (L + 2) // 2, 2 * L + 1))) for L in range(max(sh.keys()) + 1)]) for L, mls in sh.items(): if not L or (L == 1 and orderedp): c2s[L] = np.array(cart[L]) continue cdxs = [reduce(mul, xyz) for xyz in cwr((_x, _y, _z), L)] for ml, sym in mls.items(): mli = ml + L coefs = sym.expand().as_coefficients_dict() #for crt, coef in coefs.items(): for crt, _ in coefs.items(): if isinstance(crt, (Integer, Float)): continue idx = cdxs.index(crt) c2s[L][idx, mli] = coefs[cdxs[idx]] return c2s
def solution(): consecutives = {} ops = (add, sub, mul, truediv) ops = set(p for c in cwr(ops, 3) for p in permutations(c)) for key in combinations(range(10), 4): generated = set() for a, b, c, d in permutations(key): for x, y, z in ops: # Non-parenthesized case try: generated.add(x(y(z(a, b), c), d)) except ZeroDivisionError: pass # Parenthesized case try: generated.add(x(y(a, b), z(c, d))) except ZeroDivisionError: pass consecutive = list(takewhile(lambda n: n in generated, count(1))) if consecutive: consecutives[tuple(sorted(key))] = max(consecutive) return ''.join(map(str, max((v, k) for k, v in consecutives.items())[1]))
def test(n, rank): """ Using combinations with replacement to generate index mappings and check against recursive implementation. """ dim = np.arange(n) combos = np.asarray(list(cwr(dim, rank))) arr = np.zeros(rank * (n,), dtype=int) if rank == 2: for a,idx in enumerate(combos): i,j = idx arr[i,j] = a for idx in combos: i,j = idx print(flatten(n, rank, i,j)) print(flatten(n, rank, i,j) == arr[i,j], end=' ') if rank == 3: for a,idx in enumerate(combos): i,j,k = idx arr[i,j,k] = a for idx in combos: i,j,k = idx print(flatten(n, rank, i,j,k) == arr[i,j,k], end=' ') if rank == 4: for a,idx in enumerate(combos): i,j,k,l = idx arr[i,j,k,l] = a for idx in combos: i,j,k,l = idx print(flatten(n, rank, i,j,k,l) == arr[i,j,k,l], end=' ') print(" ") print(" ")
def solve(): links = dict() for tri_count in range(10): for pair in cwr(range(28 - 3 * tri_count), tri_count): tup1 = ('t', ) + tuple(map(lambda x: x // 2, pair)) tup2 = ('b', ) + tuple(map(lambda x: (x + 1) // 2, pair)) if tup1 not in links: links[tup1] = [] if tup2 not in links: links[tup2] = [] links[tup1].append(tup2) links[tup2].append(tup1) configs = dict() for layer in links: configs[layer] = 1 for new_row in range(9): new_configs = dict() for layer in links: for new_layer in links[layer]: if new_layer in new_configs: new_configs[new_layer] += configs[layer] else: new_configs[new_layer] = configs[layer] configs = new_configs result = 0 for layer in configs: result += configs[layer] return result
def problem030(n): ''' Returns the sum of all the numbers which can be written as the sum of n-th powers of their digits, where n is greater than 3. The function first determines all the possible configurations of digits with combinations_with_replacement in itertools. It subsequently calculates the sum of those digits to the power n and determines whether this is equal to the corresponding configuration. With this method, this function can calculate sum of all numbers that can be written as the 10-th powers of their digit in less than a second ''' def convert(num): ''' Convert an integer to an ordered tuple of its digits padded by zeros. While this conversion can be done with the str() function ,this method is faster when n gets larger. ''' digitList = [] while num != 0: digitList.append(num % 10) num = num // 10 return tuple([0] * (n - len(digitList) + 1) + sorted(digitList)) total = 0 possibleDigits = cwr(range(10), n + 1) for perm in possibleDigits: sumDigits = sum(d**n for d in perm) digitTuple = convert(sumDigits) if sumDigits > 1 and digitTuple == perm: total += sumDigits return total
def genotype_combinations(ref: str, alt_list: list) -> list: """ The `GC` column (not VCF-standard) in the Wellderly tsv files represents the count of genotypes in the following patterns. Suppose a, b, c, ..., z represent the allele frequencies. For n = 2 alleles, the genotype frequencies are expanded as (a+b)^2 = a^2 + 2ab + b^2. For n = 3 alleles, (a+b+c)^2 = (a+b)^2 + 2(a+b)c + c^2 = a^2 + 2ab + b^2 + 2ac + 2bc + c^2 For n = 4 alleles, (a+b+c+d)^2 = (a+b+c)^2 + 2(a+b+c)d + d^2 = ... Therefore, the genotype combinations (i.e. the order of the `GC` column) would be 0/0, 0/1, 1/1, 0/2, 1/2, 2/2, 0/3, 1/3, 2/3, 3/3, ... ... Note that this expanding scheme seems only apply to the Wellderly tsv files. For n alleles, there would be {(n+1) choose 2} genotypes regardless of the combination order. """ # The REF must be the first allele in the list allele_list = [ref] + alt_list genotype_list = [ Genotype(first_allele=q, second_allele=p) for (p, q) in cwr(reversed(allele_list), 2) ] genotype_list.reverse() return genotype_list
def get_clothing(self, temperature): warm_coef = Wardrobe._warmness_coefficient(temperature) keys = self._data.keys() lengths = [len(item) for item in self._data] elms = list(range(max(lengths))) indexes = list(cwr(elms, len(keys))) best_error = 100000 diff = 100000 spread = 100000 best_index = None for index in indexes: try: vals = list() for i, key in enumerate(keys): cloth_item = self._data[key][index[i]] vals.append(cloth_item) if not (cloth_item.temperature_range[0] <= temperature <= cloth_item.temperature_range[1]): raise ValueError cur_spread = max(val.warmness for val in vals) - \ min(val.warmness for val in vals) cur_diff = abs(warm_coef - sum(val.warmness for val in vals)) cur_error = Wardrobe._estimation(cur_diff, cur_spread ** 2) if cur_error < best_error: best_index = index best_error = cur_error except: pass clothing = [self._data[key][best_index[i]] for i, key in enumerate(keys)] return clothing
def find_fewest_coins(coins: list, target: int) -> list: """[Function to find the fewest coins in change] Args: coins ([list]): [List of the coins available] target ([int]): [Value of which change is made] Raises: ValueError: [Target input is less than change] ValueError: [Couldn't get the proper amount in coins] Returns: [list]: [List of coins for appropriate change] """ if target == 0: return [] if target < min(coins): raise ValueError("Somethins whack with your target") # iterate up to target value divided by the minimum coin # Seeing as at the very least you'd use all of that min coin # to reach the target value. # From those coins generate combinations with replacement # ie - all possible coin combinations with the coins available # If the sum is == to the target. You've got the mininum coins~! for i in range(1, target // min(coins) + 1): for c in cwr(coins, i): if sum(c) == target: return list(c) raise ValueError("No entiendo! Change not possible!")
def _nbo_labels(): """Generate dataframes of NBO label, L, and ml or l, m, n.""" sph = pd.DataFrame([(L, m) for L in range(7) for m in range(-L, L + 1)], columns=('L', 'ml')) # See the NBO 6.0 manual for more details # This is the basis function labeling scheme # In order of increasing ml from most negative # to most positive in the same order as the # results from the solid_harmonics code. sph['label'] = [ 1, 101, 102, 103, 251, 253, 255, 252, 254, 357, 355, 353, 351, 352, 354, 356, 459, 457, 455, 453, 451, 452, 454, 456, 458, 561, 559, 557, 555, 553, 551, 552, 554, 556, 558, 560, 663, 661, 659, 657, 655, 653, 651, 652, 654, 656, 658, 660, 662 ] Ls, ls, ms, ns, label = [], [], [], [], [] # Even NBO 6.0 doesn't support cartesian basis # functions with an l value greater than g functions for i in range(5): start = i * 100 + 1 label += list(range(start, start + cart_lml_count[i])) car = [''.join(i) for i in list(cwr('xyz', i))] Ls += [i for k in car] ls += [i.count('x') for i in car] ms += [i.count('y') for i in car] ns += [i.count('z') for i in car] car = pd.DataFrame({'L': Ls, 'l': ls, 'm': ms, 'n': ns, 'label': label}) return sph, car
def probability(dices, sides, value): return round(( sum(factorial(len(set(shot))) for shot in cwr(range(1,sides), dices) if sum(shot) == value) / sides ** dices), 4)
def sopdfe(ex): s, p = 0, {str(i):i**ex for i in range(10)} if ex >= 5: ex += 1 for cx in cwr('0123456789', ex): t = sum(p[x] for x in cx) sd = sum(p[x] for x in str(t)) if t == sd and t > 9: s += t return (s if s > 0 else "NONE")
def find_minimum_coins(change, coins): if change < 1: raise ValueError('Impossible to change imaginary money') cycles = 1 + (change // min(coins)) for i in range(1, cycles): for found in filter(lambda x: sum(x) == change, cwr(coins, i)): return sorted(found) raise ValueError('Sorry, we cant change your money today')
def Euler023(): amic_map = {} for i in range(12, 28124): f = Factor(i) if f > i: amic_map[i] = f nums = set([x for x in (sum(i) for i in cwr(amic_map, 2)) if x < 28124]) return sum(set(range(1, 28124)) - nums)
def get_random_mask(self): schemeta = [] masks = list(cwr([0, 1], self.num_dim)) masks = masks[1:-1] # remove all zero or all one mask s = np.random.randint(len(masks)) schema = list(masks[s]) np.random.shuffle(schema) return schema
def main(): colin_probs = [0] * (36 - 6 + 1) peter_probs = [0] * (36 - 9 + 1) for combo in cwr(range(1, 7), 6): score = sum(combo) colin_probs[score - 6] += num_perms(combo) for combo in cwr(range(1, 5), 9): score = sum(combo) peter_probs[score - 9] += num_perms(combo) colin_denom = sum(colin_probs) peter_denom = sum(peter_probs) result = 0 for pete_score, pp in enumerate(peter_probs, 9): result += (pp) * (sum(colin_probs[0:pete_score - 6])) print(result / (colin_denom * peter_denom))
def solution(arr): for i, j in cwr(range(len(arr)), 2): new_arr = arr[:] new_arr[i], new_arr[j] = new_arr[j], new_arr[i] if new_arr == sorted(arr): return True break else: return False
def combrep(L, K): sum = 0 choose = lambda L, K: cwr(list(range(L)), K) for coordinate in choose(L, K): #print("coordinate",coordinate) occurence = [coordinate.count(k) for k in range(L)] #print("occurence",occurence) if all(occurence): sum += multi_comb(occurence) return sum
def replacer(n): N = list(str(n)) swaps = getcombs(len(N)) for thisswap in swaps: N_temp = N reps = cwr('0123456789', len(thisswap)) for rep in reps: for it, dig in enumerate(thisswap): N_temp[int(dig)] = rep[it] print(int(''.join(N_temp)))
def alphabet_columns(): alphabet = string.ascii_uppercase length = 2 column_names = [] for letter in alphabet: column_names.append(letter) for comb in cwr(alphabet, length): column_names.append(''.join(comb)) return column_names
def package_lipid(key): body = classes[key][1][1] N_Tails = classes[key][1][0] if body == 'Glycerol': lst = [list(comb) for comb in cwr(tails[0], N_Tails)] elif body == 'SB': lst = [ list(filter(None, comb)) for comb in product( tails[1], [tail * N_Tails for tail in tails[0]]) ] # Hacky, only works for 0 and 1. return lst
def total_probs(base, count, comb): ''' Get the probability of rolling each possible total. Return it in a list where the index is the total and the value is the probability. Indexes 0 through 'count-1' will have a value of 0 ''' perms = len(base)**count probs = [0] * 37 for roll in cwr(base, count): values = tuple(roll.count(n) for n in set(roll)) values = tuple(sorted(values)) probs[sum(roll)] += comb[values] / perms return probs
def run_workloads(output, queries, workload_size, perf_model): import time x = 0 start = time.clock() for workload in cwr(queries, workload_size): partitions = eval_goodness(workload, perf_model) results = {'workload': workload, 'partitions': partitions} pickle.dump(results, output) x += 1 if x % 100 == 0: print x, x / (time.clock() - start)
def SmartForce(): t0 = clock() totalsum = 0 for k in range(1, 7): for i in cwr(range(9, -1, -1), k): if sixty(i): ctr = Counter(i) totalsum += permut(ctr) print(int(totalsum)) t1 = clock() print("Took", t1 - t0)
def new_differentiate_nn(E, geom, order=3): """ geom must be a LIST of single-variable torch.tensors """ # Compute derivatives. Build up higher order tensors one dimension at a time. nparam = len(geom) #.size()[0] # indices of geometry parameters 0 --> n indices = [i for i in range(nparam)] # indices of unique tensor elements h_idx = torch.tensor(list(cwr(indices, 2)), dtype=torch.long) c_idx = torch.tensor(list(cwr(indices, 3)), dtype=torch.long) gradient = torch.autograd.grad(E, geom, create_graph=True) h1 = [] c1 = [] for i, g in enumerate(gradient): for j in range(i, nparam): h = torch.autograd.grad(g, geom[j], create_graph=True)[0] h1.append(h) for k in range(j, nparam): c = torch.autograd.grad(h, geom[k], create_graph=True)[0] c1.append(c) # To build up tensors after finding unique derivatives: with torch.no_grad(): hess = torch.zeros((nparam, nparam), dtype=torch.float64, requires_grad=False) for i, idx in enumerate(h_idx): hess[idx[0], idx[1]] = h1[i] hess[idx[1], idx[0]] = h1[i] cubic = torch.zeros((nparam, nparam, nparam), dtype=torch.float64, requires_grad=False) for i, idx in enumerate(c_idx): for p in list(itertools.permutations([0, 1, 2])): cubic[idx[p[0]], idx[p[1]], idx[p[2]]] = c1[i] return hess, cubic
def palindrome(num): if not isinstance(num, int) or num < 0: return "Not valid" num = str(num) count = 0 # generate indexes for all possible list slices for i, j in cwr(range(len(num) + 1), 2): check = num[i:j] if check == check[::-1] and len(check) > 1: count += 1 return count
def iterations(arr, length): #<---This function generates all possible rows for connect 4 of a given length---> possible = [] combs = list(cwr(arr, length)) for c in combs: c = list(c) if c not in possible: perms = permutations(c) for p in perms: p = list(p) if p not in possible: possible.append(p) return possible
def generate(key): lipid_body = D.classes[key][1][1] number_of_tails = D.classes[key][1][0] if lipid_body == 'Glycerol': lst = [list(comb) for comb in cwr(tails[0], number_of_tails)] elif lipid_body == 'SB': lst = [ list(filter(None, comb)) for comb in product( tails[1], [tail * number_of_tails for tail in tails[0]]) ] # Hacky, only works for 0 and 1. return lst
def find_nr_chain_length_v2(): total = 0 for tup in cwr(range(1, 10), 6): numstr = (''.join([str(i) for i in tup])) num_leading_ones = get_num_leading_ones(numstr) if num_leading_ones == len(numstr): continue for i in range(num_leading_ones + 1): if find_nr_chain_length(int(numstr[i:])) == 60: add = 0 for elem in include_zero_substitutions(numstr[i:]): add = num_permutations(elem) print(total, add, elem) total += add return total
def compute(self): numbers_sets = cwr([n for n in range(self.max, self.min - 1, -1)], numbers) # min - 1 to print min # generates the sets of n numbers to be multiplied pal_number = 0 for numbers_set in numbers_sets: # iterate the set of numbers product = 1 for number in numbers_set: product *= number # finds the product of the n numbers in the set if self.check(product) and product > pal_number: pal_number = product PalSet = numbers_set print(pal_number) # print(product, set) print(pal_number, PalSet) return
def solve(): #Declare variables start = time.time() facts, ans = [[i, fact(i)] for i in range(10)], 0 #Solve the problem for digits in range(2, 8): for comb in list(cwr(facts, digits)): #Note 1 num = ''.join(str(i[0]) for i in comb) sumfacts = sum(i[1] for i in comb) if sorted(str(sumfacts)) == sorted(num): ans += sumfacts #Note 2 #Print the results print 'The sum of all numbers which are equal to the ' print 'sum of the factorial of their digits is ' + str(ans) + '.' print 'This took ' + str(time.time() - start) + ' seconds to calculate.'
def M(p,q,N): exp = ceil((log(N)-log(max([p,q])))/log(min([p,q]))) tmp = [0] for e in range(1,exp+1): combos = cwr([p,q],e) nums = [] for i in combos: if p in i and q in i: j = reduce(mul,i) if j<=N: nums+=[j] #nums = [j for j in reduce(mul,i) for i in combos if j<=N and p in i\ #and q in i] if nums: tmp+=[max(nums)] #if N in tmp:return N return max(tmp)
def get_expected_probability(probabilities): """ Calculates the expected probability of two variables :param probabilities: dictionary with all the probabilites per element :return: expected probabilites per pair of values """ expected = dict() for a, b in cwr(probabilities.keys(), 2): if a == b: expected["".join(sorted([a, b ]))] = probabilities[a] * probabilities[b] else: expected["".join(sorted( [a, b]))] = 2 * (probabilities[a] * probabilities[b]) return expected
def __init__( self, **kwargs ) : from P2VV.RooFitWrappers import __check_req_kw__ __check_req_kw__('AmpNames',kwargs) __check_req_kw__('Amplitudes',kwargs) __check_req_kw__('AngFunctions',kwargs) try : from itertools import combinations_with_replacement as cwr except: from P2VV.Compatibility import cwr # get amplitude names from arguments self._ampNames = kwargs.pop('AmpNames') # get amplitudes from arguments self._amplitudes = kwargs.pop('Amplitudes') for amp in self._ampNames : assert amp in self._amplitudes, 'Amplitudes_AngularPdfTerms: no amplitude \'%s\' found' % amp # get keys for angular terms keys = [ key for key in cwr( self._ampNames, 2 ) ] # get angular functions from arguments angFuncs = { } angFuncsArg = kwargs.pop('AngFunctions') for key in keys : assert key in angFuncsArg, 'Amplitudes_AngularPdfTerms: no angular function %s found' % str(key) angFuncs[key] = angFuncsArg[key] # check if there are no arguments left if kwargs: raise KeyError('Amplitudes_AngularPdfTerms: got unknown keyword%s: %s'\ % ( '' if len(kwargs) == 1 else 's', kwargs )) # build angular coefficients from P2VV.RooFitWrappers import FormulaVar angCoefs = { } Re = lambda Ai, Aj :\ FormulaVar( Name = 'Re_c_%s_%s' % ( Ai, Aj ), Formula = '@0*@2 + @1*@3', Arguments = [ Ai.Re, Ai.Im, Aj.Re, Aj.Im ] ) Im = lambda Ai, Aj :\ FormulaVar( Name = 'Im_c_%s_%s' % ( Ai, Aj ), Formula = '@0*@3 - @1*@2', Arguments = [ Ai.Re, Ai.Im, Aj.Re, Aj.Im ] ) for key in keys : angCoefs[key] = ( Re( self._amplitudes[ key[0] ], self._amplitudes[ key[1] ] ) , Im( self._amplitudes[ key[0] ], self._amplitudes[ key[1] ] ) ) # initialize Coefficients_AngularPdfTerms.__init__( self, Keys = keys, AngCoefficients = angCoefs, AngFunctions = angFuncs )
def add_polynomial_terms(X): """ Return matrix X augmented with columns representing 2-dgree polynomial expansions of its columns. Examples -------- >>> X = np.array([[1,2,3,4],[5,6,7,8]]).T array([[1, 5], [2, 6], [3, 7], [4, 8]]) >>> add_polynomial_terms(X) array([[ 1, 5, 1, 5, 25], [ 2, 6, 4, 12, 36], [ 3, 7, 9, 21, 49], [ 4, 8, 16, 32, 64]]) """ from itertools import combinations_with_replacement as cwr # TODO: will need to combine column indices col_combinations = [x for x in cwr(range(X.shape[1]), 2)] poly_cols = [np.prod(X[:, c], axis=1) for c in col_combinations] return np.hstack((X, np.array(poly_cols).T))
def precondition(self): """Get the indices through which we should run, and check if anything is missing. Populate the dictionaries part_list (that has the list of particle indices for each type) and pair_list (the list of particle pair indices for each particle pair). """ self.part_list = {} for j in self.names: self.part_list[j] = \ [i for i, _x in enumerate(self.name) if _x == j] #Create all pair_list arrays self.pair_list = {} for pair_name in cwr(self.names, 2): self.pair_list[tuple(sorted(pair_name))] = [] #Populate pair_list for pair in combinations(xrange(self.N), 2): name_1 = self.name[pair[0]] name_2 = self.name[pair[1]] pair_name = tuple(sorted((name_1, name_2))) self.pair_list[pair_name].append((pair[0], pair[1]))
from operator import add, sub, mul, truediv from itertools import combinations_with_replacement as cwr INDEXES = [tuple(map(int,i)) for k in range(1,7) for i in cwr("123456",k) if sum(int(j) for j in i) == 6] OPER = [op for op in cwr((add,sub,mul, truediv),5)] print(INDEXES) print(OPER)
import csv from pandas import DataFrame, ExcelFile, Series from pandas.io.parsers import read_csv as rc from pandas.io.json import read_json import re import numpy as np DATA_TYPE_TYPES = { "float64": float, "int64": int, "object" : object, } import string from itertools import product as cwr stuff = string.ascii_lowercase # We generate a hexavigecimal alphabet which allows us to convert between base 26 letter codes and numbers alphabet = ["".join(comb) for comb in cwr(stuff, repeat=1)] alphabet += ["".join(comb) for comb in cwr(stuff, repeat=2)] alphabet += ["".join(comb) for comb in cwr(stuff, repeat=3)] def get_data_frame(read_csv, skiprows=0, header=None, names=None): '''Returns a dataframe from a csv buffer''' pd = rc(read_csv, infer_datetime_format=True,index_col=None, header=header, skiprows=skiprows,names=names,) return pd def get_excel_data_frame(read_excel, skiprows=0, header=None, names=None): data = ExcelFile(read_excel) df = data.parse(data.sheet_names[0], header=header,index_col=None, skiprows=skiprows,names=names, ) return df def rename_column(df, position, new_name):
#Changes: # OFFSET(B2,0,4) #To: # INDIRECT("'New Matrix'!$F$" & ROW($A2)) import string from itertools import combinations_with_replacement as cwr alphabet = string.ascii_lowercase length = 2 alpha1 = ["".join(letter) for letter in string.ascii_lowercase] alpha2 = ["".join(comb) for comb in cwr(alphabet, length)] extended_alphabet = alpha1+alpha2 string = r'IF(ISBLANK(OFFSET(B2,0,4)),"",OFFSET(B2,0,4)&"?"&"utm_source=facebook&utm_medium="&IF(OR(OFFSET(B2,0,13)="des",OFFSET(B2,0,13)="mob",OFFSET(B2,0,13)="mob-tab",OFFSET(B2,0,13)="a",OFFSET(B2,0,13)="mob-all"),"pla","banr")&"&utm_term="&SUBSTITUTE(LOWER(AlphaNumericOnly(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(OFFSET(B2,0,19),"e","e"),"&","and"),"+","and")))," ","_")&"&utm_content="&OFFSET(B2,0,17)&"&utm_campaign="&OFFSET(B2,0,2)&"&db_dest="&OFFSET(B2,0,21)&"&db_unit=d&db_cid=60&db_terms="&OFFSET(B2,0,23)&"-"&OFFSET(B2,0,24)&"&db_class="&IF(OR(OFFSET(B2,0,13)="des",OFFSET(B2,0,13)="banr"),"des",OFFSET(B2,0,13))&"&db_seg="&OFFSET(B2,0,22)&"&db_sku=&c3ch=Facebook&c3nid="&OFFSET(B2,0,2)&"&db_vref1="&IF(ISBLANK(OFFSET(B2,0,25)),"n",OFFSET(B2,0,25))&"&db_vref2="&IF(ISBLANK(OFFSET(B2,0,26)),"n",OFFSET(B2,0,26))&"&lb=force")' substring = 'OFFSET' # for substring in string: # print substring start = string.find('OFFSET') end = string.find(')', start) num_reference = string[start+6:end].split(',')[2] letter_reference = extended_alphabet[int(num_reference)+1] text_to_replace = string[start:end+1] print text_to_replace ind_reference = r'INDIRECT("\'New Matrix\'!${0}$" & ROW($A2))'.format(letter_reference.upper()) print ind_reference
from itertools import combinations_with_replacement as cwr x,y = input().split() [print(''.join(c)) for c in cwr(sorted(x),int(y))]
lmap = OrderedDict() rlmap = OrderedDict() spher_ml_count = OrderedDict() cart_ml_count = OrderedDict() spher_lml_count = OrderedDict() cart_lml_count = OrderedDict() enum_cartesian = OrderedDict() for i, L in enumerate(lorder): lmap[L] = i rlmap[i] = L spher_ml_count[L] = 2 * i + 1 cart_ml_count[L] = (i + 1) * (i + 2) // 2 spher_lml_count[i] = spher_ml_count[L] cart_lml_count[i] = cart_ml_count[L] enum_cartesian[i] = [] cnts = [Counter(c) for c in cwr('xyz', i)] enum_cartesian[i] = np.array([[0, 0, 0]]) if not cnts \ else np.array([[c[x] for x in 'xyz'] for c in cnts]) lmap.update([('px', 1), ('py', 1), ('pz', 1)]) gaussian_cartesian = enum_cartesian.copy() gaussian_cartesian[2] = np.array([[2, 0, 0], [0, 2, 0], [0, 0, 2], [1, 1, 0], [1, 0, 1], [0, 1, 1]]) def _hermite_gaussians(lmax): """Symbolic hermite gaussians up to order lmax. Args: lmax (int): highest order angular momentum quantum number """ order = 2 * lmax + 1
def __init__(self, angFuncs, Amplitudes,CP, itag, dilution, order ) : def combine( name, afun, A, CPparams, tag, i, j) : # TODO: deal with tag = None: create the untagged PDF in that case! from P2VV.RooFitWrappers import ConstVar, Product plus = ConstVar( Name = 'plus', Value = 1 ) minus = ConstVar( Name = 'minus', Value = -1 ) if type(CP['C'])==ConstVar and CP['C'].getVal() == 0 : Norm = [ ] else : Norm = [ self._parseArg( 'Norm', kwargs, Formula = '1.0/(1.0+sign(@0)*@1)', Arguments = [ tag, CP['C'] ] , ObjectType = 'FormulaVar' ) ] Norm[0].setAttribute("CacheAndTrack") # define functions which return Re(Conj(Ai) Aj), Im( Conj(Ai) Aj) Re = lambda ai, aj : self._parseArg( 'Re_c_%s_%s' % ( ai, aj ), { }, Type = 'ProdCarthCToRe', ObjectType = 'ConvertPolAmp' , Arguments=[ ai.Re,ai.Im,aj.Re,aj.Im ] ) Im = lambda ai, aj : self._parseArg( 'Im_c_%s_%s' % ( ai, aj ), { }, Type = 'ProdCarthCToIm', ObjectType = 'ConvertPolAmp' , Arguments=[ ai.Re,ai.Im,aj.Re,aj.Im ] ) # define functions which return the coefficients that define the time-dependence... _minus_if = lambda b, x : [ minus ] + x if b else x coef = { 'cosh' : lambda ai,aj,CP : ( plus if ai.CP == aj.CP else CP['C'] , None ) , 'cos' : lambda ai,aj,CP : ( tag if ai.CP != aj.CP else Product('Re_%s_%s_cos' %(ai,aj), [ tag, CP['C'] ] ) , None ) , 'sinh' : lambda ai,aj,CP : ( None if ai.CP != aj.CP else Product('Re_%s_%s_sinh'%(ai,aj), _minus_if( ai.CP < 0 , [ CP['D'] ] )) , None if ai.CP == aj.CP else Product('Im_%s_%s_sinh'%(ai,aj), _minus_if( ai.CP < aj.CP , [ CP['S'] ] )) ) , 'sin' : lambda ai,aj,CP : ( None if ai.CP != aj.CP else Product('Re_%s_%s_sin' %(ai,aj), _minus_if( ai.CP > 0 , [ tag, CP['S'] ] )) , None if ai.CP == aj.CP else Product('Im_%s_%s_sin' %(ai,aj), _minus_if( ai.CP < aj.CP , [ tag, CP['D'] ] )) ) } (c_re,c_im) = coef[name](A[i],A[j],CPparams) (f_re,f_im) = afun[(i,j)] (a_re,a_im) = ( Re(A[i],A[j]),Im(A[i],A[j]) ) # NOTE: thes sign are just the obvious Re(a b c) = Re(a)Re(b)Re(c) - Re(a)Im(b)Im(c) - Im(a)Re(b)Im(c) - Im(a)Im(b)Re(c), # i.e. there is a minus in case there are 2 imaginary contributions prod = lambda name, args : [ Product(name, args) ] if all(args) else [] s = prod('ReReRe_%s_%s_%s'%(name,A[i],A[j]), [ a_re , c_re, f_re ]+Norm ) \ + prod('ImImRe_%s_%s_%s'%(name,A[i],A[j]), [ minus, a_im , c_im, f_re ]+Norm ) \ + prod('ImReIm_%s_%s_%s'%(name,A[i],A[j]), [ minus, a_im , c_re, f_im ]+Norm ) \ + prod('ReImIm_%s_%s_%s'%(name,A[i],A[j]), [ minus, a_re , c_im, f_im ]+Norm ) assert len(s) == 1 # for now, coefficients are either real, or imaginary, but not both... (not true in general, but I'm lazy today ;-) return s[0] args = dict() from P2VV.RooFitWrappers import Addition,Product, RealCategory try : # this requires python 2.7 or later... from itertools import combinations_with_replacement as cwr except: from P2VV.Compatibility import cwr tag = Product('tag',( RealCategory('tag_real', itag ),dilution)) for name in [ 'cosh', 'sinh', 'cos', 'sin' ] : # NOTE: 'Amplitudes' must be traversed 'in order' -- so we cannot use Amplitudes.keys() out of the box, but use the # specified order (which also selects which ones to include!)... args[ name ] = Addition( 'a_%s'% name, [ combine(name,angFuncs,Amplitudes,CP,tag,i,j) for (i,j) in cwr( order, 2 ) ] ) BDecayBasisCoefficients.__init__( self, **args )
def configure_features(self, orders=range(1, 5), **extras): from itertools import combinations_with_replacement as cwr all_features = [t for order in orders for t in cwr(['logt', 'logg', 'feh'], order)]
return get_energy(output_file) DISP = 0.005 os.makedirs('disp/', exist_ok=True) # Run the reference geometry e0_in = 'disp/e0.in' write_input(e0_in, mol) run(e0_in) e0 = get_energy('disp/e0.out') print("E0: " + str(e0)) # Iterate over all pairs of coordinates in the upper triangle for q1, q2 in cwr(range(3*len(mol)), r=2): # Displace forwards and back for disp in [DISP, -DISP]: sign = '+' if disp > 0 else '-' if q1 == q2: print(q1, sign) inp_name = single_displace_form.format(q1, sign) + '.in' displaced = displace(mol, q1, disp, q2, 0) else: print(q1, q2, sign) inp_name = double_displace_form.format(q1, sign, q2, sign) + '.in' displaced = displace(mol, q1, disp, q2, disp) write_input(inp_name, displaced) run(inp_name)
def __init__( self, AngFuncs, Amplitudes, CPParams, Order ) : def combine( tCoefType, angFuncs, amplitudes, CPParams, iIndex, jIndex ) : from P2VV.RooFitWrappers import ConstVar one = ConstVar( Name = 'one', Value = 1 ) minus = ConstVar( Name = 'minus', Value = -1 ) # define functions which return Re(Ai* Aj), Im( Ai* Aj) Re = lambda Ai, Aj : self._parseArg( 'Re_amps_%s_%s' % ( Ai, Aj ), { }, Type = 'ProdCarthCToRe', ObjectType = 'ConvertPolAmp' , Arguments = [ Ai.Re, Ai.Im, Aj.Re, Aj.Im ] ) Im = lambda Ai, Aj : self._parseArg( 'Im_amps_%s_%s' % ( Ai, Aj ), { }, Type = 'ProdCarthCToIm', ObjectType = 'ConvertPolAmp' , Arguments = [ Ai.Re, Ai.Im, Aj.Re, Aj.Im ] ) # define functions which return the coefficients of the time dependence def CPVDec( termInd, iInd, jInd, amps, CPPar ) : # get parameters for CP violation in decay assert termInd in ( 'plus', 'min', 'Re', 'Im' ) if CPPar.CPVInDecay() : return CPPar.R( termInd, iInd, jInd ) # only CP violation in mixing (or lambdas for all polarizations identical): # R^+ = ( 1 + eta_i * eta_j ) / 2 # R^- = ( 1 - eta_i * eta_j ) / 2 # R^Re = ( eta_i + eta_j ) / 2 # R^Im = i * ( eta_i - eta_j ) / 2 if termInd == 'plus' : return ( None if amps[iInd].CP != amps[jInd].CP else one, None ) if termInd == 'min' : return ( None if amps[iInd].CP == amps[jInd].CP else one, None ) if termInd == 'Re' : return ( None if amps[iInd].CP != amps[jInd].CP else one if amps[iInd].CP > 0 else minus, None ) if termInd == 'Im' : return ( None, None if amps[iInd].CP == amps[jInd].CP else one if amps[iInd].CP > 0 else minus ) def tCoefTerm( name, dec, mix, sign ) : # build one of the two terms within the time function coefficient: # + R^+ * 1, + R^- * C, + R^- * 1, + R^+ * C, + R^Re * D, + R^Im * S, + R^Im * D, - R^Re * S if not dec or not mix : return None if dec == minus : sign = -sign if mix == minus : sign = -sign sign = minus if sign < 0 else None if dec in [ one, minus ] : dec = None if mix in [ one, minus ] : mix = None facs = [ fac for fac in ( sign, dec, mix ) if fac ] return self._parseArg( name, { }, Arguments = facs, ObjectType = 'Product' ) if len(facs) > 1\ else facs[0] if len(facs) == 1 else one def tCoef( tCType, iInd, jInd, amps, CPPar ) : # build the coefficient of the time function: # cosh: + R^+ * 1 + R^- * C # cos: + R^- * 1 + R^+ * C # sinh: + R^Re * D + R^Im * S # sin: + R^Im * D - R^Re * S assert tCType in ( 'cosh', 'sinh', 'cos', 'sin' ) CPVDecInds = [ 'plus', 'min' ] if tCType in ( 'cosh', 'cos' ) else [ 'Re', 'Im' ] if tCType in ( 'cos', 'sin' ) : CPVDecInds = [ CPVDecInds[1], CPVDecInds[0] ] CPVDecs = [ CPVDec( CPVDecInd, iInd, jInd, amps, CPPar ) for CPVDecInd in CPVDecInds ] CPVMixs = [ one, CPPar.C() ] if tCType in ( 'cosh', 'cos' ) else [ CPPar.D(), CPPar.S() ] signs = [ +1, +1 ] if tCType in ( 'cosh', 'cos', 'sinh' ) else [ +1, -1 ] name = '%s_%s_%s' % ( iInd , jInd, tCType ) terms = [ ( tCoefTerm( 'Re_%s%d_%s_%s' % ( tCType, ind, iInd, jInd ), dec[0], mix, sign ) , tCoefTerm( 'Im_%s%d_%s_%s' % ( tCType, ind, iInd, jInd ), dec[1], mix, sign ) ) for ind, ( dec, mix, sign ) in enumerate( zip( CPVDecs, CPVMixs, signs ) ) ] assert any( comp for term in terms for comp in term ) add = lambda name, args : self._parseArg( name, { }, Arguments = args, ObjectType = 'Addition' ) if len(args) > 1\ else args[0] if len(args) == 1 else None return ( add( 'Re_%s_%s_%s' % ( tCType, iInd, jInd ), [ term[0] for term in terms if term[0] ] ) , add( 'Im_%s_%s_%s' % ( tCType, iInd, jInd ), [ term[1] for term in terms if term[1] ] ) ) # create complex amplitude, time and angular factors ( reAmps, imAmps ) = ( Re( amplitudes[iIndex], amplitudes[jIndex] ), Im( amplitudes[iIndex], amplitudes[jIndex] ) )\ if iIndex != jIndex else ( amplitudes[iIndex].Mag2, None ) ( reTime, imTime ) = tCoef( tCoefType, iIndex, jIndex, amplitudes, CPParams ) ( reAng, imAng ) = angFuncs[ ( iIndex, jIndex ) ] # (real part of) product of amplitude, time and angular (complex) factors: # Re(abc) = Re(a)Re(b)Re(c) - Im(a)Im(b)Re(c) - Re(a)Im(b)Im(c) - Im(a)Re(b)Im(c) # (there is a minus in case there are 2 imaginary contributions) prod = lambda name, args : [ self._parseArg( name, { }, Arguments = args, ObjectType = 'Product' ) ] if all(args) else [ ] return prod( 'ReReRe_%s_%s_%s' % ( tCoefType, amplitudes[iIndex], amplitudes[jIndex] ), [ reAmps , reTime, reAng ] ) \ + prod( 'ImImRe_%s_%s_%s' % ( tCoefType, amplitudes[iIndex], amplitudes[jIndex] ), [ minus, imAmps , imTime, reAng ] ) \ + prod( 'ReImIm_%s_%s_%s' % ( tCoefType, amplitudes[iIndex], amplitudes[jIndex] ), [ minus, reAmps , imTime, imAng ] ) \ + prod( 'ImReIm_%s_%s_%s' % ( tCoefType, amplitudes[iIndex], amplitudes[jIndex] ), [ minus, imAmps , reTime, imAng ] ) try : # this requires python 2.7 or later... from itertools import combinations_with_replacement as cwr except: from P2VV.Compatibility import cwr args = dict() for tCoefType in [ 'cosh', 'sinh', 'cos', 'sin' ] : # NOTE: 'Amplitudes' must be traversed 'in order' : A0, Apar, Aperp, AS, so we cannot use Amplitudes.keys() out of the box coef = self._parseArg( '%sCoef' % tCoefType, { }, ObjectType = 'Addition' , Arguments = [ term for ( i, j ) in cwr( Order, 2 )\ for term in combine( tCoefType, AngFuncs, Amplitudes, CPParams, i, j ) ] ) # same B/Bbar sign for cosh and sinh coefficients ("even"), opposite B/Bbar sign for cos and sin coefficients ("odd") args[ tCoefType ] = ( coef, None ) if tCoefType in [ 'cosh', 'sinh' ] else ( None, coef ) BDecayBasisCoefficients.__init__( self, **args )
from itertools import combinations_with_replacement as cwr with open('sensor.in') as fin: N = int(fin.read()) k = set() for i in range(1, N + 1): for j in cwr([1, 2, 3, 4, 5, 6], r=i): if sum(j) == N: print(j) new_sum = sum([7 - i for i in j]) print(new_sum) k.add(new_sum) with open('sensor.out', 'w') as fout: print(len(k), file=fout)
from itertools import combinations_with_replacement as cwr s,k = input().split() print("\n".join("".join(it) for it in cwr(sorted(s),int(k))))
def __init__( self, **kwargs ) : ampNames = kwargs.pop('AmplitudeNames') amps = kwargs.pop('Amplitudes') magNames = kwargs.pop('MagnitudeNames') phaseNames = kwargs.pop('PhaseNames') RPlusDict = { } RMinDict = { } RReDict = { } RImDict = { } try : from itertools import combinations_with_replacement as cwr # this requires python 2.7 or later except: from P2VV.Compatibility import cwr for ampComb in cwr( ampNames, 2 ) : eta0 = amps[ ampComb[0] ].CP eta1 = amps[ ampComb[1] ].CP RPlusDict[ampComb] = tuple( [ self._parseArg( '%sRPlus_%s_%s' % ( comp, ampComb[0], ampComb[1] ), kwargs , Formula = '(%s@0*@1*%s(@2-@3)) / 2.'\ % ( '1. + ' if comp == 'Re' and eta0 == eta1\ else '1. - ' if comp == 'Re' and eta0 != eta1\ else '' if eta0 == eta1 else '-' , func ) , Arguments = [ getattr( self, '_%s' % magNames[ ampComb[0] ] ) , getattr( self, '_%s' % magNames[ ampComb[1] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[0] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[1] ] ) ] , ObjectType = 'FormulaVar' ) for ( comp, func ) in [ ( 'Re', 'cos' ), ( 'Im', 'sin' ) ] ] ) RMinDict[ampComb] = tuple( [ self._parseArg( '%sRMin_%s_%s' % ( comp, ampComb[0], ampComb[1] ), kwargs , Formula = '(%s@0*@1*%s(@2-@3)) / 2.'\ % ( '1. - ' if comp == 'Re' and eta0 == eta1\ else '1. + ' if comp == 'Re' and eta0 != eta1\ else '-' if eta0 == eta1 else '' , func ) , Arguments = [ getattr( self, '_%s' % magNames[ ampComb[0] ] ) , getattr( self, '_%s' % magNames[ ampComb[1] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[0] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[1] ] ) ] , ObjectType = 'FormulaVar' ) for ( comp, func ) in [ ( 'Re', 'cos' ), ( 'Im', 'sin' ) ] ] ) RReDict[ampComb] = tuple( [ self._parseArg( '%sRRe_%s_%s' % ( comp, ampComb[0], ampComb[1] ), kwargs , Formula = '(%s@0*%s(@2) %s @1*%s(-@3)) / 2.'\ % ( '' if eta0 > 0 else '-', func, '+' if eta1 > 0 else '-', func ) , Arguments = [ getattr( self, '_%s' % magNames[ ampComb[0] ] ) , getattr( self, '_%s' % magNames[ ampComb[1] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[0] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[1] ] ) ] , ObjectType = 'FormulaVar' ) for ( comp, func ) in [ ( 'Re', 'cos' ), ( 'Im', 'sin' ) ] ] ) RImDict[ampComb] = tuple( [ self._parseArg( '%sRIm_%s_%s' % ( comp, ampComb[0], ampComb[1] ), kwargs , Formula = '(%s@0*%s(@2) %s @1*%s(-@3)) / 2.'\ % ( '-' if ( eta0 > 0 and comp == 'Re' )\ or ( eta0 < 0 and comp == 'Im' ) else '' , func , '+' if ( eta1 > 0 and comp == 'Re' )\ or ( eta1 < 0 and comp == 'Im' ) else '-' , func ) , Arguments = [ getattr( self, '_%s' % magNames[ ampComb[0] ] ) , getattr( self, '_%s' % magNames[ ampComb[1] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[0] ] ) , getattr( self, '_%s' % phaseNames[ ampComb[1] ] ) ] , ObjectType = 'FormulaVar' ) for ( comp, func ) in [ ( 'Re', 'sin' ), ( 'Im', 'cos' ) ] ] ) self._check_extraneous_kw( kwargs ) CPParam.__init__( self, AmplitudeNames = ampNames , C = self._parseArg( 'C', kwargs , Formula = '(1. - @0*@0) / (1. + @0*@0)' , Arguments = [ getattr( self, '_%s' % magNames['mix'] ) ] , ObjectType = 'FormulaVar' ) , D = self._parseArg( 'D', kwargs , Formula = '-2. * @0 * cos(@1) / (1. + @0*@0)' , Arguments = [ getattr( self, '_%s' % magNames['mix'] ) , getattr( self, '_%s' % phaseNames['mix'] ) ] , ObjectType = 'FormulaVar' ) , S = self._parseArg( 'S', kwargs , Formula = '-2. * @0 * sin(@1) / (1. + @0*@0)' , Arguments = [ getattr( self, '_%s' % magNames['mix'] ) , getattr( self, '_%s' % phaseNames['mix'] ) ] , ObjectType = 'FormulaVar' ) , RPlusDict = RPlusDict , RMinDict = RMinDict , RReDict = RReDict , RImDict = RImDict )
bounds = {} features = {} def pad_bounds(inbounds, tpad=500., gpad=0.5, zpad=0.1, **extras): mm = np.array([-1,1]) outbounds = {} outbounds['logt'] = tuple(np.log10(10**np.array(inbounds['logt']) + mm * tpad)) outbounds['logg'] = tuple(np.array(inbounds['logg']) + mm*gpad) outbounds['feh'] = tuple(np.array(inbounds['feh']) + mm*zpad) return outbounds #you get (order + 3 - 1)!/(order! * 2!) combinations for each order # terms_of_order = [t for t in cwr(['logt', 'logg', 'feh'], order)] all_features = [t for order in [1, 2, 3 ,4, 5] for t in cwr(['logt', 'logg', 'feh'], order)] bounds["Test"] = {'logt': (np.log10(2549.0), np.log10(4249)), 'logg': (3.49, 5.51), 'feh': (-2.01, 0.51)} features["Test"] = (['logt'], ['feh'], ['logg'], # Quadratic ['logt', 'logt'], ['logg', 'logg'], ['feh', 'feh'], # Cross-quadratic ['logt', 'feh'],
# A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers # is 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit numbers. from itertools import combinations_with_replacement as cwr def ispalindrome(x): y = str(x) if y == y[::-1]: return True else: return False combinations = cwr(range(999, 99, -1), 2) products = [x * y for x, y in combinations] print(max([x for x in products if ispalindrome(x)]))
from itertools import permutations, combinations, combinations_with_replacement as cwr import sys from util import isprime # iterate over each combination of 4 numbers for digits in cwr("0123456789", 4): # all permutations of digits, in numerical order perms = [int("".join(p)) for p in permutations(digits)] perms = sorted(perms) # each increasting pair for t1, t2 in combinations(perms, 2): if t1 < 1000: continue # must be 4 digits if t2 == t1: continue # must be increasing if t1 == 1487: continue t3 = t2 + (t2 - t1) if not isprime(t1) or not isprime(t2): continue if not isprime(t3) or t3 not in perms: continue print "%4.4i%4.4i%4.4i" % (t1, t2, t3) sys.exit(1)
from itertools import combinations_with_replacement as cwr #take input word and length k input_str = raw_input().split() keyword = input_str[0] keyword = sorted(keyword) k = int(input_str[1]) L = list(cwr(keyword,k)) #print the formatted answer for i in range(0,len(L)): print ''.join(L[i])