예제 #1
0
def asymmetric(in_arr):
    """
    Creates the asymmetric form of input tensor.
    Input: Arraypy or TensorArray with equal axes (array shapes).
    Output: asymmetric array. Output type - Arraypy or TensorArray, depends of input

    Examples
    ========

    >>> from sympy.tensor.arraypy import list2arraypy
    >>> from sympy.tensor.tensor_methods import asymmetric
    >>> a = list2arraypy(list(range(9)), (3,3))
    >>> b = asymmetric(a)
    >>> print (b)
    0  -1.00000000000000  -2.00000000000000
    1.00000000000000  0  -1.00000000000000
    2.00000000000000  1.00000000000000  0
    """
    if not isinstance(in_arr, Arraypy):
        raise TypeError('Input must be Arraypy or TensorArray type')

    flag = 0
    for j in range(in_arr.rank):
        if (in_arr.shape[0] != in_arr.shape[j]):
            raise ValueError('Different size of arrays axes')

    # forming list of tuples for Arraypy constructor of type a = Arraypy( [(a,
    # b), (c, d), ... , (y, z)] )
    arg = [(in_arr.start_index[i], in_arr.end_index[i])
           for i in range(in_arr.rank)]

    # if in_arr TensorArray, then res_arr will be TensorArray, else it will be
    # Arraypy
    if isinstance(in_arr, TensorArray):
        res_arr = TensorArray(Arraypy(arg), in_arr.ind_char)
    else:
        res_arr = Arraypy(arg)

    signs = [0 for i in range(factorial(in_arr.rank))]
    temp_i = 0
    for p in permutations(range(in_arr.rank)):
        signs[temp_i] = perm_parity(list(p))
        temp_i += 1

    index = [in_arr.start_index[i] for i in range(in_arr.rank)]

    for i in range(len(in_arr)):
        perm = list(permutations(index))
        perm_number = 0
        for temp_index in perm:
            res_arr[tuple(index)] += signs[perm_number] * \
                in_arr[tuple(temp_index)]
            perm_number += 1
        if isinstance(res_arr[tuple(index)], int):
            res_arr[tuple(index)] = float(res_arr[tuple(index)])
        res_arr[tuple(index)] /= factorial(in_arr.rank)

        index = in_arr.next_index(index)

    return res_arr
예제 #2
0
def test_euler_axes():
    # Test there and back with all axis specs
    aba_perms = [(v[0], v[1], v[0]) for v in permutations('xyz', 2)]
    axis_perms = list(permutations('xyz', 3)) + aba_perms
    for (a, b, c), mat in zip(euler_tuples, euler_mats):
        for rs, axes in product('rs', axis_perms):
            ax_spec = rs + ''.join(axes)
            conventioned = [EulerFuncs(ax_spec)]
            if ax_spec in euler.__dict__:
                conventioned.append(euler.__dict__[ax_spec])
            mat = euler2mat(a, b, c, ax_spec)
            a1, b1, c1 = mat2euler(mat, ax_spec)
            mat_again = euler2mat(a1, b1, c1, ax_spec)
            assert_almost_equal(mat, mat_again)
            quat = euler2quat(a, b, c, ax_spec)
            a1, b1, c1 = quat2euler(quat, ax_spec)
            mat_again = euler2mat(a1, b1, c1, ax_spec)
            assert_almost_equal(mat, mat_again)
            ax, angle = euler2axangle(a, b, c, ax_spec)
            a1, b1, c1 = axangle2euler(ax, angle, ax_spec)
            mat_again = euler2mat(a1, b1, c1, ax_spec)
            assert_almost_equal(mat, mat_again)
            for obj in conventioned:
                mat = obj.euler2mat(a, b, c)
                a1, b1, c1 = obj.mat2euler(mat)
                mat_again = obj.euler2mat(a1, b1, c1)
                assert_almost_equal(mat, mat_again)
                quat = obj.euler2quat(a, b, c)
                a1, b1, c1 = obj.quat2euler(quat)
                mat_again = obj.euler2mat(a1, b1, c1)
                assert_almost_equal(mat, mat_again)
                ax, angle = obj.euler2axangle(a, b, c)
                a1, b1, c1 = obj.axangle2euler(ax, angle)
                mat_again = obj.euler2mat(a1, b1, c1)
                assert_almost_equal(mat, mat_again)
 def done(self, one):
     customers, products = one.split(';')
     customers = customers.split(',')
     products = map(get_letters, products.split(','))
     for customer in customers:
         row = []
         letters = get_letters(customer)
         vowels = get_vowels(customer)
         for product in products:
             row.append(get_ss(product, letters, vowels))
         self.matrix.append(row)
     row_num = len(self.matrix)
     col_num = len(row)
     max_ss = 0
     less = row_num
     if row_num > col_num:
         less = col_num 
         for one in itertools.combinations(range(row_num), less):
             for two in itertools.permutations(range(col_num)):
                 total = self.get_total(one, two, less)
                 max_ss = total if max_ss < total else max_ss
     else:
         for one in itertools.combinations(range(col_num), less):
             for two in itertools.permutations(range(row_num)):
                 total = self.get_total(two, one, less)
                 max_ss = total if max_ss < total else max_ss
     return max_ss
예제 #4
0
    def __needleman(self):
        # first and last 5 aminoacids are not considered for the alignment
        chains_first = self.__get_all_chains(0)
        chains_second = self.__get_all_chains(1)

        # all permutations of the chains
        perms_first = list(permutations(chains_first))
        perms_second = list(permutations(chains_second))

        best_score = None
        # aling all the permutations of the chains and return the best alignment
        for perm_first in perms_first:
            for perm_second in perms_second:
                # ordered residues, according to the current permutations
                aminoacids1 = self.__get_aminoacids(0, perm_first)[4:-5]
                aminoacids2 = self.__get_aminoacids(1, perm_second)[4:-5]

                score_matrix = self.__compute_score_matrix(aminoacids1, aminoacids2)

                needleman = Needleman(aminoacids1, aminoacids2, score_matrix)
                needleman.align()
                score = needleman.score
                if best_score is None or score < best_score:
                    best_score = score
                    best_alignment = needleman.get_alignment()

        return best_alignment
예제 #5
0
파일: problem_093.py 프로젝트: yred/euler
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]))
예제 #6
0
def reduce_dimension(m):
    """
    reduce the dimension of game matrix based on domination --
    player I will be better off if one row constently larger than another
    player II will be better off if one col constently smaller than anthoer
    Output: the reduced-size game matrix
    Note: This implements stric domination.
    TODO: convex reduction
    """
    local = np.array(m)
    flag = True
    while True:
        rbefore = len(local)
        candidates = []
        for nr in permutations(range(len(local)), 2):
            bigger = reduce(lambda x,y: x and y, local[nr[0]]>local[nr[1]])
            if bigger: 
                candidates.append(nr[1])
        for i in candidates:
            local = np.delete(local, i, 0)

        cbefore = len(local[0])
        candidates = []
        for nc in permutations(range(len(local[0])), 2):
            smaller = reduce(lambda x,y: x and y, local[:,nc[0]]<local[:, nc[1]])
            if smaller:
                candidates.append(nc[1])
        for i in candidates:
            local = np.delete(local, i, 1)

        if len(local[0])==cbefore and len(local)==rbefore:
            break

    return local
예제 #7
0
def digPerms(digset, nzcharset, okzcharset):
    """This function creates permutations given the set of digits,
       letters not alllowed to be 0, and letters allowed to be 0
    """
    nzcnt = len(nzcharset)  # How many letters are non-0
    okzcnt = len(okzcharset)  # How many letters are allowed 0
    totcnt = nzcnt + okzcnt  # Total number of letters
    if totcnt < 1:  # if total numbers of letters is 0
        return [()]  # return a singe empty permutation
    nzdigset = digset - set((0,))  # generate a non-zero digit set
    nzdigsetcnt = len(nzdigset)  # how many non-zero digits are available
    digsetcnt = len(digset)  # how many ok zero digits are available
    # if either fewer digits than letters at all or fewer non-0 digits
    # than letters that need to be non-zero
    if digsetcnt < totcnt or nzdigsetcnt < nzcnt:
        return []  # Return no permutations possible
    # Simple case when zeros are allowed everwhere
    # or no zero is containted within the given digits
    elif nzcnt == 0 or digsetcnt == nzdigsetcnt:
        return permutations(digset, totcnt)
    # Another simple case all letters are non-0
    elif okzcnt == 0:
        return permutations(nzdigset, totcnt)
    else:
        # General case
        # Generate a list of possible 0 positions
        poslst = list(range(nzcnt, totcnt))
        # Chain two iterators
        # first iterator with all non-0 permutations
        # second iterator with all permulations without 1 letter
        # insert 0 in all possible positions of that permutation
        return chain(permutations(nzdigset, totcnt),
                     map(lambda x: x[0][:x[1]] + (0,) + x[0][x[1]:],
                         product(permutations(nzdigset, totcnt - 1),
                                 poslst)))
예제 #8
0
def test_equivalent():
    ijk = CoordinateSystem('ijk')
    xyz = CoordinateSystem('xyz')
    T = np.random.standard_normal((4,4))
    T[-1] = [0,0,0,1]
    A = AffineTransform(ijk, xyz, T)

    # now, cycle through
    # all possible permutations of
    # 'ijk' and 'xyz' and confirm that
    # the mapping is equivalent

    yield assert_false, equivalent(A, A.renamed_domain({'i':'foo'}))

    try:
        import itertools
        for pijk in itertools.permutations('ijk'):
            for pxyz in itertools.permutations('xyz'):
                B = A.reordered_domain(pijk).reordered_range(pxyz)
                yield assert_true, equivalent(A, B)
    except (ImportError, AttributeError):
        # just do some if we can't find itertools, or if itertools
        # doesn't have permutations
        for pijk in ['ikj', 'kij']:
            for pxyz in ['xzy', 'yxz']:
                B = A.reordered_domain(pijk).reordered_range(pxyz)
                yield assert_true, equivalent(A, B)
예제 #9
0
def create_alternative_urls(params, ndp):
    library = params['library']
    model_name = params['model_name']
    def make_url(faxes, raxes):
        faxes = ",".join(map(str, faxes))
        raxes = ",".join(map(str, raxes))
        return '/libraries/%s/models/%s/views/solver/%s/%s/' % (library, model_name, faxes, raxes)

    # let's create the urls for different options
    fnames = ndp.get_fnames()
    rnames = ndp.get_rnames()

    fun_alternatives = []
    for option in itertools.permutations(range(len(fnames)), 2):
        url = make_url(faxes=option, raxes=params['res_axes'])
        desc = "%s vs %s" % (fnames[option[0]], fnames[option[1]])
        fun_alternatives.append({'url':url, 'desc':desc})

    res_alternatives = []
    for option in itertools.permutations(range(len(rnames)), 2):
        url = make_url(faxes=params['fun_axes'], raxes=option)
        desc = "%s vs %s" % (rnames[option[0]], rnames[option[1]])
        res_alternatives.append({'url':url, 'desc':desc})

    return fun_alternatives, res_alternatives
예제 #10
0
    def winnable(self, player):
        """Test if the current game state is winnable by <player>.

        If true, return the winning position.  Obviously, if the game is winnable for <player>, it is also blockable for
        the opponent, so this same function may be used for either detection depending on whose turn it is.
        """

        # Get the occupied positions for the player
        occupied = self.__getattribute__(PLAYERS[player])
        # Get the occupied position for the opponent
        opp = self.__getattribute__(PLAYERS[self.switch_player(player)])
        # Loop frenzy. I'll buy lunch for whoever comes up with the list comprehension for this sucker. I gave up.
        for v in WIN_VECTORS:  # Loop the win vectors
            for perm in itertools.permutations(v, 2):  # Loop through all 2-digit permutations of each vector
                vector = list(perm)  # Listify each permutation
                for p in itertools.permutations(occupied, 2):  # Loop through all 2-digit permutations of occupied
                    if list(p) == vector:
                        # At this point, we know the player holds two positions that match one of the win vectors
                        # which means we have a possible winner.  We then return the position that will result in the
                        # win (or block, as the case may be).  Easy enough using some "set" magic.
                        win = list(set(v) - set(vector))[0]
                        # Now we make sure win move is not held by the opponent
                        if win not in opp:
                            return win
        return False
예제 #11
0
    def test_la_links_permutations(self):
        """Make sure the order in which we add links doesn't matter."""
        users = self.add_objects(3, 'user', 'u_permutations')
        groups = self.add_objects(6, 'group', 'g_permutations')

        for g, p in zip(groups, itertools.permutations(users)):
            self.add_linked_attribute(g, p)

        # everyone should be in every group
        for g in groups:
            self.assert_forward_links(g, users)

        for u in users:
            self.assert_back_links(u, groups)

        for g, p in zip(groups[::-1], itertools.permutations(users)):
            self.replace_linked_attribute(g, p)

        for g in groups:
            self.assert_forward_links(g, users)

        for u in users:
            self.assert_back_links(u, groups)

        for g, p in zip(groups, itertools.permutations(users)):
            self.remove_linked_attribute(g, p)

        for g in groups:
            self.assert_forward_links(g, [])

        for u in users:
            self.assert_back_links(u, [])
예제 #12
0
파일: np_test.py 프로젝트: amjames/ambit
    def test_nd_dot_2idx(self):
        # All permutations of nd dot with two index removed
        # Can include all output permutations

        for rank in range(2, max_test_rank):
            perm1 = tuple(it.permutations(dim_inds[:rank]))
            perm2 = tuple(it.permutations(dim_inds[rank - 2:rank * 2 - 2]))
            collapse_ind = dim_inds[rank - 2:rank]

            for comb in it.product(perm1, perm2):
                left_inds = ''.join(comb[0])
                right_inds = ''.join(comb[1])
                [aA, nA] = self.build("A", left_inds)
                [aB, nB] = self.build("B", right_inds)

                ret_inds = (left_inds + right_inds)
                for collapse in collapse_ind:
                    ret_inds = ret_inds.replace(collapse, '')

                if full_test:
                    ret_ind_list = it.permutations(ret_inds)
                else:
                    ret_ind_list = [ret_inds]

                for iret_inds in ret_ind_list:
                    iret_inds = ''.join(iret_inds)
                    einsum_string = left_inds + ',' + right_inds + '->' + iret_inds

                    [aC, nC] = self.build("C", iret_inds)
                    aC[iret_inds] = aA[left_inds] * aB[right_inds]
                    np.einsum(einsum_string, nA, nB, out=nC)
                    self.assert_allclose(aC, nC)
예제 #13
0
 def validate_value(actual, expected):
     if isinstance(expected, list):
         actual_len = len(actual)
         expected_len = len(expected)
         if actual_len != expected_len:
             return False
         for actual_list in itertools.permutations(actual, actual_len):
             for expected_list in itertools.permutations(expected,
                                                         expected_len):
                 match = True
                 for i, actual_ele in enumerate(actual_list):
                     if not validate_value(actual_ele,
                                           expected_list[i]):
                         match = False
                         break
                 if match:
                     return True
         return False
     elif isinstance(expected, dict):
         for k in expected:
             if not validate_value(actual[k], expected[k]):
                 return False
         return True
     elif isinstance(expected, str):
         tokens = expected.split('*')
         if tokens[0] == '' and tokens[-1] == '':
             return actual.find(tokens[1]) != -1
         elif tokens[0] == '':
             return actual.endswith(tokens[-1])
         elif tokens[-1] == '':
             return actual.startswith(tokens[0])
         return actual == expected
     else:
         return actual == expected
예제 #14
0
    def listGameSelections(self):
        """Evaluate all bots in all possible permutations!  If there are more
        games requested, randomly fill up from a next round of permutations."""
        if not self.competitors: raise StopIteration 

        p = []
        r = set(itertools.permutations([True, True, False, False, False]))
        for players in itertools.permutations(self.competitors, 5):
            for roles in r:
                p.append((players, roles))

        permutations = []
        while len(permutations) < self.rounds:
            random.shuffle(p)
            permutations.extend(p)
        
        # DPT - 28-Jan-2014 - Let's let the user know what they're getting:
        if not self.quiet:
            compr = len(p)
            print("")
            print >>sys.stderr, 'Requested games: %i' % (self.rounds)
            print >>sys.stderr, 'Comprehensive size: %i' % (compr)
            if not (self.rounds == compr):
                print >>sys.stderr, 'Comprehensive sets played: %f' % (self.rounds/float(compr))
            if not ((self.rounds % compr) == 0):
                print("")
                print >>sys.stderr, 'Requested games is not divisible by comprehensive size.'
                print >>sys.stderr, 'Some bots will not compete in an equal number of games.'
        # End DPT
        
        print("")

        for players, roles in permutations[:self.rounds]:
            yield (players, roles)
예제 #15
0
    def install(cls, mh):
        super(TestServerDel, cls).install(mh)
        # prepare topologysegments for negative test cases
        # it should look like this for DOMAIN_SUFFIX_NAME:
        #             master
        #            /
        #           /
        #          /
        #   replica1------- replica2
        # and like this for CA_SUFFIX_NAME
        #             master
        #                  \
        #                   \
        #                    \
        #   replica1------- replica2

        tasks.create_segment(cls.client, cls.replica1, cls.replica2)
        tasks.create_segment(cls.client, cls.replica1, cls.replica2,
                             suffix=CA_SUFFIX_NAME)

        # try to delete all relevant segment connecting master and replica1/2
        segment_name_fmt = '{p[0].hostname}-to-{p[1].hostname}'
        for domain_pair in permutations((cls.master, cls.replica2)):
            tasks.destroy_segment(
                cls.client, segment_name_fmt.format(p=domain_pair))

        for ca_pair in permutations((cls.master, cls.replica1)):
            tasks.destroy_segment(
                cls.client, segment_name_fmt.format(p=ca_pair),
                suffix=CA_SUFFIX_NAME)
예제 #16
0
파일: logo.py 프로젝트: DaniUPC/gala
def logo_iterate(labels, image, fns=d + 'logo-%03i.png'):
    height, width = labels.shape
    background = (labels == 0)
    foreground = ~background
    counter = it.count()

    # part one: just foreground/background
    colorcombos = it.permutations(colors, 2)
    lab2 = np.zeros(labels.shape, np.uint8)
    lab2[foreground] = 1
    for cs in colorcombos:
        img = color.label2rgb(lab2, image, colors=cs)
        io.imsave(fns % next(counter), img)

    # part two: background split
    splits = np.arange(500, 1600, 100).astype(int)
    colorcombos = it.permutations(colors, 3)
    for s, cs in it.product(splits, colorcombos):
        im, lab = _split_img_horizontal(image, lab2, background, s)
        img = color.label2rgb(lab, im, colors=cs)
        io.imsave(fns % next(counter), img)

    # part three: foreground split
    colorcombos = it.permutations(colors, 3)
    for cs in colorcombos:
        img = color.label2rgb(labels, image, colors=cs)
        io.imsave(fns % next(counter), img)

    # part four: both split
    colorcombos = it.permutations(colors, 4)
    for s, cs in it.product(splits, colorcombos):
        im, lab = _split_img_horizontal(image, labels, background, s)
        img = color.label2rgb(lab, im, colors=cs)
        io.imsave(fns % next(counter), img)
예제 #17
0
파일: dota2_imp.py 프로젝트: Twestall/hacks
def predict_result(heros_playing, hero_dict):
    team_a = heros_playing[:5]
    team_b = heros_playing[5:10]
    
    a_wins = 0
    a_loses = 0
    
    for i in xrange(range_min,range_max):
        for hero in permutations(team_a,i):
            a_wins += i*hero_dict[hero]['wins']
            a_loses += i*hero_dict[hero]['loses']
        
    a_ratio = float(a_wins)/(a_wins + a_loses)

    b_wins = 0
    b_loses = 0
    
    for i in xrange(range_min,range_max):
        for hero in permutations(team_b,i):  
            b_wins += i*hero_dict[hero]['wins']
            b_loses += i*hero_dict[hero]['loses']
    
    b_ratio = float(b_wins)/(b_wins + b_loses)            
        
    if a_ratio >= b_ratio:
        return 1
    
    else:
        return 2
예제 #18
0
def checkio(chips):
    # generate all possible status for each chip
    chipPlaces = []
    for i in chips:
        chipPlaces.append([ij for ij in itertools.permutations(i)])
    # permutations for chips
    possiblePlaces = []

    # not all permutations are unique,
    # in loop, (1, 2, 3) == (3, 1, 2) == (2, 3, 1)
    counter = 0
    totalUniqueCounter = math.factorial(len(chipPlaces) - 1)
    for j in itertools.permutations(chipPlaces):
        if counter > totalUniqueCounter:
            break
        for i in itertools.product(*j):
            if (i[0][2] == i[1][0]
                    and i[1][2] == i[2][0]
                    and i[2][2] == i[3][0]
                    and i[3][2] == i[4][0]
                    and i[4][2] == i[5][0]
                    and i[5][2] == i[0][0]):
                possiblePlaces.append(i)
        counter += 1
    if possiblePlaces:
        sumOfSolutions = [sum(map(lambda x: x[1], i)) for i in possiblePlaces]
        return max(sumOfSolutions)
    else:
        return 0
예제 #19
0
 def check_topological_embedding_brute(self, verbose=False):
     '''
     Brute-force combinatoric method to check topological embedding
     '''
     # Clear table and nodemap:
     self.T = { superN:{ subN:None for subN in self.subD.nodes } 
               for superN in self.superD.nodes }  
     self.AB_nodemap = None
     N = len(self.subD.nodes) # number of subdesign nodes
     if len(self.superD.nodes) < N:
         # shortcut - fewer nodes in superdesign
         self.AB_nodemap = None
         return False
     # compute number of matchings:
     num_matchings = math.factorial(len(self.subD.nodes))*math.factorial(len(self.superD.nodes))
     count = 0
     for sub_perm in permutations(self.subD.nodes):
         for super_perm in permutations(self.superD.nodes, N):
             #sys.stdout.write("%d  \r" % count )
             #sys.stdout.flush()    # carriage returns don't work in Eclipse :-(
             if verbose:
                 print str(count) + " / " + str(num_matchings)
                 count += 1
             self.AB_nodemap = dict (zip(sub_perm, super_perm))
             if self.check_vertex2vertex():
                 if self.check_edge2path():
                     if self.check_vertex_disjointness():
                         return True
     # no embedding found.
     self.AB_nodemap = None
     return False
예제 #20
0
 def setUp(self):
     super(IndexIntegrityTest, self).setUp()
     self.make_random_table()
     # make some indexes
     cols = [c for c in self._table.columns()][1:]
     self._indexes = []
     for c in cols:
         name = c.get_name()
         i = wt.Index(self._table, name)
         i.add_key_column(c)
         i.open("w")
         i.build()
         i.close()
         self._indexes.append(i)
     for c1, c2 in itertools.permutations(cols, 2):
         name = c1.get_name() + "+" + c2.get_name()
         i = wt.Index(self._table, name)
         i.add_key_column(c1)
         i.add_key_column(c2)
         i.open("w")
         i.build()
         i.close()
         self._indexes.append(i)
     for c1, c2, c3 in itertools.permutations(cols, 3):
         name = c1.get_name() + "+" + c2.get_name() + "+" + c3.get_name()
         i = wt.Index(self._table, name)
         i.add_key_column(c1)
         i.add_key_column(c2)
         i.add_key_column(c3)
         i.open("w")
         i.build()
         i.close()
         self._indexes.append(i)
예제 #21
0
def _test(consolidate=consolidate):

    def freze(list_of_sets):
        'return a set of frozensets from the list of sets to allow comparison'
        return set(frozenset(s) for s in list_of_sets)

    # Define some variables
    A,B,C,D,E,F,G,H,I,J,K = 'A,B,C,D,E,F,G,H,I,J,K'.split(',')
    # Consolidate some lists of sets
    assert (freze(consolidate([{A,B}, {C,D}])) == freze([{'A', 'B'}, {'C', 'D'}]))
    assert (freze(consolidate([{A,B}, {B,D}])) == freze([{'A', 'B', 'D'}]))
    assert (freze(consolidate([{A,B}, {C,D}, {D,B}])) == freze([{'A', 'C', 'B', 'D'}]))
    assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) ==
             freze([{'A', 'C', 'B', 'D'}, {'G', 'F', 'I', 'H', 'K'}]))
    assert (freze(consolidate([{A,H}, {H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) ==
             freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))
    assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}])) ==
             freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))
    # Confirm order-independence
    from copy import deepcopy
    import itertools
    sets = [{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}]
    answer = consolidate(deepcopy(sets))
    for perm in itertools.permutations(sets):
            assert consolidate(deepcopy(perm)) == answer

    assert (answer == [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}])
    assert (len(list(itertools.permutations(sets))) == 720)

    print('_test(%s) complete' % consolidate.__name__)
예제 #22
0
def test_equivalent():
    ijk = CoordinateSystem("ijk")
    xyz = CoordinateSystem("xyz")
    T = np.random.standard_normal((4, 4))
    T[-1] = [0, 0, 0, 1]
    A = AffineTransform(ijk, xyz, T)

    # now, cycle through
    # all possible permutations of
    # 'ijk' and 'xyz' and confirm that
    # the mapping is equivalent

    yield assert_false, equivalent(A, A.renamed_domain({"i": "foo"}))

    try:
        import itertools

        for pijk in itertools.permutations("ijk"):
            for pxyz in itertools.permutations("xyz"):
                B = A.reordered_domain(pijk).reordered_range(pxyz)
                yield assert_true, equivalent(A, B)
    except ImportError:
        # just do some if we can't find itertools
        for pijk in ["ikj", "kij"]:
            for pxyz in ["xzy", "yxz"]:
                B = A.reordered_domain(pijk).reordered_range(pxyz)
                yield assert_true, equivalent(A, B)
def get_smart_permutations_left(letters):
    perms = []
    for perm4 in list(permutations(letters[0:4])):
        for perm6 in list(permutations(letters[4:])):
            perm = perm4 + perm6
            perms.append(perm)
    return perms
예제 #24
0
def euler32():
	ansset = []
	digitset = set('123456789')
	perms1 = itertools.permutations(digitset, 3)
	for digits1 in perms1:
		digit1set = set(digits1)
		perms2 = itertools.permutations(digitset-digit1set, 2)
		for digits2 in perms2:
			num1, num2, remainingdigits = int("".join(digits1)), int("".join(digits2)), (digitset-digit1set)-set(digits2)
			num3 = num1*num2
			testdigits = set(str(num3))
			if testdigits >= remainingdigits and len(str(num3)) == len(testdigits) and len(str(num3)) == 4:
				ansset.append((num1, num2, num3))


	perms3 = itertools.permutations(digitset, 4)

	for digits1 in perms3:
		digit1set = set(digits1)
		perms2 = digitset-digit1set
		for digits2 in perms2:
			num1, num2, remainingdigits = int("".join(digits1)), int("".join(digits2)), (digitset-digit1set)-set(digits2)
			num3 = num1*num2
			testdigits = set(str(num3))
			if testdigits >= remainingdigits and len(str(num3)) == len(testdigits) and len(str(num3)) == 4:
				ansset.append((num1, num2, num3))

	print ansset
예제 #25
0
def permuta_palabras(lista):
    """Función que realiza las permutaciones de las palabras contenidas en la lista, las permutaciones se realizan con la función permutations() del módulo
    itertools. Cuando la palabra es mayor a 7 caracteres se particionan las permutaciones porque solamente llega a 7!.
    Se agregan a las conraseñas generadas desde las palabras originales con una simple modificación (una letra mayúscula en cada posición, cambiar letras por números),
    las contraseñas generadas de forma aleatoria de acuerdo a la función mezclar_todas_palabras y después se agregan las contraseñas generadas por las permutaciones.
    Recibe: la lista que contiene las sublistas de las palabras a permutar
    Devuevle: una lista con las contraseñas que se generaron"""
    cad = ''
    final,mezclas, resultado = [], [], []
    for palabra in lista:
        if len(palabra) <= 7:
            mezclas += permutations(palabra)
        if len(palabra) > 7 and len(palabra) < 15:
            mezclas+= permutations(palabra[:7])
            mezclas+= permutations(palabra[7:])
    for pal in mezclas:
        final += [ (list(pal)) ]
    temporal = []  # lista para verificar que las palabras originales no se repitan en la lista final sin permutaciones
    for original in lista:
        if original not in temporal:  # si la palabra que se va a agregar no se encuentra en la lista original, se escribe en el archivo
            temporal += [original]
            resultado.append(cad.join(original))
    for cadaUna in final:
        numero = randint(0,5)
        for i in range(0,numero):
            numOsimboloOmayus = randint(0,2)  # variable para decidir aleatoriamente si se agrega un simbolo, mayúscula/minúscula o número en las contraseñas de las permutaciones
            aleat = randint(0,len(cadaUna)-1)
            if numOsimboloOmayus == 0:
                cadaUna.insert(aleat, choice(simbolos))  # se elige algún caracter de la cadena símbolos y se inserta en una posición aleatoria
            elif numOsimboloOmayus == 1:
                cadaUna.insert(aleat, choice(numeros))  # se elige algún caracter de la números símbolos y se inserta en una posición aleatoria
            else:
                cadaUna[aleat] = cadaUna[aleat].swapcase()  # se elige algún caracter y se cambia a minúscula o mayúscula con swapcase()
        resultado.append(cad.join(cadaUna))
    return (list(set(resultado)))  # Devuelve las contraseañas en una lista donde antes se obtiene el conjunto (set) para tener únicamente las contraseñas únicas
예제 #26
0
def expandList(indices, energies):
    """
    this is to expand the indices for plotting purposes...
    """ 
    expandedIndices = []
    expandedEnergies = []

    neg1 = [1,-1, 1]
    neg2 = [1, -1, -1]
    neg3 = [-1,-1,-1]
    permutedNeg1 = [list(a) for a in permutations(neg1)]
    permutedNeg2 = [list(a) for a in permutations(neg2)]   

    for miller, ener in zip(indices, energies):
        expandedIndices.append(miller)
        expandedEnergies.append(ener)
        permuted_indices = [list(a) for a in permutations(miller)]
        permuted_energies = [ener for i in range(0, len(permuted_indices))]
        expandedIndices += permuted_indices
        expandedEnergies += permuted_energies
        for (x, y) in zip(permutedNeg1,permutedNeg2): # add directions in negative
            expandedIndices += (permuted_indices*np.array(x)).tolist()
            expandedEnergies += permuted_energies
            expandedIndices += (permuted_indices*np.array(y)).tolist()
            expandedEnergies += permuted_energies
        expandedIndices += (permuted_indices*np.array(neg3)).tolist()
        expandedEnergies += permuted_energies

    return expandedIndices, expandedEnergies
예제 #27
0
    def test_computable(self):
        self.assertTrue(computable([('a', 'SET', (12,))]))
        self.assertTrue(computable([]))
        self.assertTrue(computable([('a', 'SET', (12,)),
                                    ('b', 'SET', (42,))]))
        self.assertTrue(computable([('a', 'SET', (12,)),
                                    ('b', 'SET', ('a',))]))
        self.assertTrue(computable([('a', 'SET', ('b',)),
                                    ('b', 'SET', (12,))]))
        for t in permutations([('a', 'SET', (12,)),
                               ('b', 'NOT', ('a',)),
                               ('c', 'LSHIFT', ('a', 2)),
                               ('d', 'AND', ('b', 'c'))
                               ]):
            u = t[:]
            self.assertTrue(computable(t))
            self.assertEqual(u, t)

        for t in permutations([('a', 'AND', ('b', 'd')),
                               ('b', 'AND', ('c', 'd')),
                               ('c', 'LSHIFT', ('f', 2)),
                               ('d', 'OR', ('c', 'f')),
                               ('e', 'NOT', ('d',)),
                               ('f', 'SET', ('g',)),
                               ('g', 'SET', (42,))]):
            u = t[:]
            self.assertTrue(computable(t))
            self.assertEqual(u, t)

        self.assertTrue(computable(read("input1.txt")))
        self.assertTrue(computable(read("input2.txt")))
예제 #28
0
def permute_levenshtein(s1, s2, limit=100):
    min_distance = max(len(s1), len(s2))
    for s1_perm in itertools.permutations(s1.split()):
        for s2_perm in itertools.permutations(s2.split()):
            distance = levenshtein(' '.join(s1_perm), ' '.join(s2_perm), limit)
            min_distance = distance if distance < min_distance else min_distance
    return min_distance
예제 #29
0
    def try_graph(self, start, count, vertex):
        def map_down(s):
            return [-1 if s == 0 else int(math.sqrt(ss))-1 for ss in s]

        self.max_value_width = 6
        possible = set(reduce(lambda x,y: x+y, [list(x) for x in start]))
        for sset in itertools.combinations(start, 3):
            if any(vertex not in s for s in sset):
                print "Failed to find %d in %r" % (vertex, sset)
                continue
            # Try each possible diagonal (not all perms because of symetry)
            for arrangement in ((0,1,2), (0,2,1), (2,1,0)):
                row = [i for i in sset[arrangement[0]] if i != vertex]
                col = [i for i in sset[arrangement[1]] if i != vertex]
                dia = [i for i in sset[arrangement[2]] if i != vertex]
                for r in itertools.permutations(row):
                    for c in itertools.permutations(col):
                        for d in itertools.permutations(dia):
                            square = [vertex, r[0], r[1], c[0], d[0], 0, c[1], 0, d[1]]
                            all = set(square)
                            rest = map_down(possible - all)
                            square = map_down(square)
                            #print "Trying:"
                            #self.print_sq(square)
                            for s1,s2 in itertools.permutations(rest, 2):
                                new_s = square[:]
                                new_s[5] = s1
                                new_s[7] = s2
                                if self.is_magic(new_s, quiet=False):
                                    self.print_sq(new_s)
                                    return True
        return False
예제 #30
0
 def test_permutations(self):
     res = permutations('ABC')
     self.assertEqual(['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'], [''.join(_) for _ in res])
     res = permutations('ABC', 1)
     self.assertEqual(['A', 'B', 'C'], [''.join(_) for _ in res])
     res = permutations('ABC', 2)
     self.assertEqual(['AB', 'AC', 'BA', 'BC', 'CA', 'CB'], [''.join(_) for _ in res])
예제 #31
0
cunmin_ = [[0 for _ in range(m)] for _ in range(n)]
cunmin__ = [[0 for _ in range(m)] for _ in range(n)]
for i in range(n):
    for j in range(m):
        cunmin_[i][j] = [j + 1, juli(cunmin[i][0], \
                        cunmin[i][1], youju[j][0], youju[j][1])]

    cunmin_[i].sort(key=lambda x: x[1])
    for j in range(m):
        cunmin__[i][j] = cunmin_[i][j][1]
        cunmin_[i][j] = cunmin_[i][j][0]

cnt = INF
ans = 0
tmp_ = list(permutations([i for i in range(1, m + 1)], k))
tmp = []
for i in range(len(tmp_)):
    tmp__ = list(tmp_[i])
    tmp__.sort()
    if tmp__ not in tmp:
        tmp.append(tmp__)

for i in range(len(tmp)):
    dist = 0
    for j in range(n):
        dist += cunmin__[j][min(zhuanhuan(j, tmp[i]))]
    if dist < cnt:
        ans = i
        cnt = dist
예제 #32
0
tsp = [[0, 91.8, 105.2, 89.9, 189.9, 76.2, 278.3, 54.4],
       [91.8, 0, 187.2, 38.9, 271.3, 162.9, 363.3, 88.4],
       [105.2, 187.2, 0, 194.1, 182.3, 31.4, 176.1, 153.8],
       [89.9, 38.9, 194.1, 0, 249.4, 166.1, 368.3, 63.6],
       [189.9, 271.3, 182.3, 249.4, 0, 168.0, 243.0, 185.9],
       [76.2, 162.9, 31.4, 166.1, 168.0, 0, 202.2, 122.8],
       [278.3, 363.3, 176.1, 368.3, 243.0, 202.2, 0, 320.0],
       [54.4, 88.4, 153.8, 63.6, 185.9, 122.8, 320.0, 0]]

import random
import itertools
import numpy as np
nums = itertools.permutations([1, 2, 3, 4, 5, 6, 7, 8])
nums2 = list(nums)
n = []  #族群大小n
distance = 0
first = []  #第一個最好的染色體
second = []  #次要最好的染色體


def length(k):
    global distance
    distance = tsp[k[len(k) - 1] - 1][k[0] - 1]
    for i in range(len(tsp[0])):
        if (i == len(tsp) - 1):
            break
        else:
            distance += tsp[k[i] - 1][k[i + 1] - 1]
    distance = "%.1f" % distance
    distance = float(distance)
예제 #33
0
def solve_brute_force(numbers):
    """This takes 510,33s. """
    nr_sum = sum(numbers)
    for a, b in permutations(numbers, 2):
        if a*b == nr_sum - a - b:
            return set([a, b])
예제 #34
0
n = itertools.count(1)  # 创建一个无限的迭代器,上述代码会打印出自然数序列
n = itertools.count(100, 2)  # 100开始,2为步长,无限序列
n = itertools.cycle('abc')  # 把传入的一个序列无限重复下去,a,b,c,a,b,c不停迭代
n = itertools.repeat('abc',
                     10)  #把一个元素无限重复下去,不过如果提供第二个参数就可以限定重复次数,'abc','abc','abc'
# 上述三个都是无限迭代器
n = itertools.chain('abc', 'xyz')  # 把一组迭代对象串联起来,形成一个更大的迭代器

n = itertools.groupby('aaabbbccaadd')  # 把迭代器中相邻的重复元素挑出来放在一起,aaa,bbb,cc,aa,dd
for key, group in itertools.groupby('AAABBBCCAAA'):
    print(key, list(group))
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
# 上述两行代码,指定输出的限制条件,输出1到10
n = itertools.permutations([2, 4, 5, 6], 3)  # 表示从序列中挑出3个元素进行排列
n = itertools.combinations([2, 4, 5, 6], 3)  # 表示从序列中挑出3个元素进行组合
n = itertools.product([2, 3, 4], [5, 6, 7], [8, 9, 0])  # 笛卡尔积
n = itertools.islice('abdhklhldhwoh', 2, 7,
                     2)  # 生成一个从字符串第3个字符开始,第8个字符结束,步长为2的迭代器对象
n = itertools.starmap(
    max, [[5, 14, 5], [2, 34, 6], [3, 5, 2]])  # 针对列表中的每一个元素执行max函数
# n = itertools.imap(lambda x: x*x, [1, 2, 3])
# imap()和map()的区别在于,imap()可以作用于无穷序列,并且,如果两个序列的长度不一致,以短的那个为准,
# 同理izip,ifilter也是如此

with open('20170627101259.txt', 'a+') as file:
    print(file.read())

list_3 = range(1, 11)
예제 #35
0
# N 과 M 9

"""
2021-06-06 오전 1:23
안영준

문제 : https://www.acmicpc.net/problem/15663
"""

import itertools
import sys

input = lambda: sys.stdin.readline().rstrip()

N, M = map(int, input().split())

number = list(map(int, input().split()))

number.sort()

comb = itertools.permutations(number, M)
result = sorted(list(set(comb)))

for i in result:
    print(' '.join(map(str, i)))
from itertools import permutations
x=list(permutations(input()))
print(len(x))
for i in x:
    print(''.join(i))
예제 #37
0
def plotter(data_clean,
            plot_name='',
            show=True,
            plot_reacs=True,
            norm=True,
            legend_handler=None,
            marker_func=None,
            minx=None,
            miny=None,
            maxx=None,
            maxy=None,
            ylog=False,
            return_vals=False,
            **filters):

    # create fig, ax
    plt.figure()
    ax = plt.subplot(1, 1, 1)

    data = get_filtered_data(data_clean, **filters)

    # now plot data
    to_plot = ['runtime']
    if filters.pop('plot_compilation', False):
        to_plot.append('comptime')
    if filters.pop('plot_overhead', False):
        to_plot.append('overhead')
    # get data
    plot_data = flatten(data)
    # get labels

    diffs, diff_locs, diff_check = get_diffs(plot_data)
    plot_cores = False
    if 'cores' in [diff_check[loc] for loc in diff_locs]:
        # can only process one
        plot_cores = len(diff_locs) == 1
        if plot_cores:
            diffs = [sorted(data.keys())]
            diff_locs = [-1]
            diff_check.append('mechdata.mech')
            plot_reacs = False
            plot_cores = True

    retval = None
    # delete diff for vecwidth / par thing
    if 'vectype' in [diff_check[loc] for loc in diff_locs]:
        ind = next((i for i, loc in enumerate(diff_locs)
                    if diff_check[loc] == 'vecwidth'), None)
        if ind is not None:
            diffs.pop(ind)
            diff_locs.pop(ind)

    if len(diff_locs) > 2:
        raise NotImplementedError
    if not diff_locs:
        # regular plot
        for plot in to_plot:
            gp.plot(*gp.process_data(plot_data, plot, reacs_as_x=plot_reacs))
    else:
        # create map dict
        loc_map = {}
        for i, diff in enumerate(diffs):
            for subdiff in diff:
                loc_map[subdiff] = diff_locs[i]

        # sort
        try:
            diffs = [sorted(diff, key=lambda x: float(x)) for diff in diffs]
        except:
            if plot_cores:
                # sort by mech size
                diffs = [
                    sorted(diff, key=lambda x: data[x][0].mechdata.n_reactions)
                    for diff in diffs
                ]
            else:
                diffs = [sorted(diff) for diff in diffs]

        # first pass - process data
        x_vals = []
        y_vals = []
        z_vals = []
        labels = []

        def __get_compound_names(val1, val2):
            c1 = diff_check[loc_map[val1]]
            c2 = diff_check[loc_map[val2]]

            # generic name ordering
            ordering = ['vectype', 'order']

            # sort by order
            check_vals = [None for _ in diff_check]
            check_vals[loc_map[val1]] = c1
            check_vals[loc_map[val2]] = c2
            check_vals = sorted(check_vals,
                                key=lambda x: 100
                                if x not in ordering else ordering.index(x))

            # remove none
            check_vals = [x for x in check_vals if x is not None]

            # and return str
            return ' - '.join(
                ps.pretty_names(check).format(val1 if check == c1 else val2)
                for check in check_vals)

        # handle 2 diffs
        if len(diffs) == 1:
            for val in [subdiff for diff in diffs for subdiff in diff]:
                check = diff_check[loc_map[val]]
                match = [
                    x for x in plot_data
                    if __compare(x, check, val, plot_cores=plot_cores)
                ]
                if match:
                    labels.append(ps.pretty_names(check).format(val))
                    x, y, z = gp.process_data(match,
                                              'runtime',
                                              reacs_as_x=plot_reacs,
                                              plot_cores=plot_cores)
                    x_vals.append(x)
                    y_vals.append(y)
                    z_vals.append(z)
        else:
            iterator = [
                zip(x, diffs[1])
                for x in itertools.permutations(diffs[0], len(diffs[0]))
            ]
            iterator = [subiter for i in iterator for subiter in i]
            for val1, val2 in iterator:
                match = [
                    x for x in plot_data
                    if __compare(x,
                                 diff_check[loc_map[val1]],
                                 val1,
                                 plot_cores=plot_cores)
                    and __compare(x, diff_check[loc_map[val2]], val2)
                ]
                if match:
                    labels.append(__get_compound_names(val1, val2))
                    x, y, z = gp.process_data(match,
                                              'runtime',
                                              reacs_as_x=plot_reacs,
                                              plot_cores=plot_cores)
                    x_vals.append(x)
                    y_vals.append(y)
                    z_vals.append(z)

        if return_vals:

            def __copy_arr(val):
                return [v[:] for v in val]

            retval = [
                __copy_arr(x_vals),
                __copy_arr(y_vals),
                __copy_arr(z_vals),
                copy.copy(labels)
            ]

        # second pass - normalize
        if norm and not plot_cores:
            xlen = len(next(x for x in x_vals if x))
            # find the max y for each x
            for ix in range(xlen):
                y_max = np.max(
                    [y_vals[i][ix] for i in range(len(y_vals)) if y_vals[i]])
                # divide
                for i in range(len(y_vals)):
                    z_vals[i][ix] = (z_vals[i][ix] /
                                     y_vals[i][ix]) * (y_max / y_vals[i][ix])
                    y_vals[i][ix] = y_max / y_vals[i][ix]

        elif norm:
            # parallel scaling eff
            for ix in range(len(x_vals)):
                for i in range(1, len(x_vals[ix])):
                    # scaling eff is t1 / (N * tN)
                    y_vals[ix][i] = y_vals[ix][0] / \
                        (x_vals[ix][i] * y_vals[ix][i])
                    # update uncertainty
                    z_vals[ix][i] = y_vals[ix][i] * np.sqrt(
                        np.power(z_vals[ix][0] / y_vals[ix][0], 2) +
                        np.power(z_vals[ix][i] / y_vals[ix][i], 2))
                # remove first entry (1 core)
                assert x_vals[ix][0] == 1
                x_vals[ix] = x_vals[ix][1:]
                y_vals[ix] = y_vals[ix][1:]
                z_vals[ix] = z_vals[ix][1:]

        if ylog:
            ax.set_yscale('log')

        # and finally plot
        for i in range(len(y_vals)):
            gp.plot(x_vals[i],
                    y_vals[i],
                    z_vals[i],
                    labels=labels,
                    plot_ind=i,
                    marker_func=marker_func)
        ax.set_xlim([minx, maxx])
        ax.set_ylim([miny, maxy])

    ylabel = r'Runtime (\si{\milli\second} / state)'
    xlabel = r'Number of {} in Model'.format(
        'Species' if not plot_reacs else 'Reactions')
    if norm:
        ylabel = 'Speedup'
        if plot_cores:
            ylabel = 'Parallel Scaling Efficiency'
    if plot_cores:
        xlabel = 'Number of Cores'

    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    if legend_handler:
        plt.legend(*legend_handler, **ps.legend_style).draggable()
    else:
        plt.legend(**ps.legend_style)
    ps.finalize()
    if plot_name:
        plt.savefig(plot_name)
    if show:
        plt.show()
    return retval
예제 #38
0
import itertools
a = [1,2,3,4,5]
b = 'manan'
iter_a = []
iter_b = []
iter_a2 = []
iter_b2 = []
for i in itertools.combinations(a,2):
    iter_a.append(i)
print(iter_a)
for i in itertools.combinations(b,2):
    iter_b.append(''.join(i))
print(iter_b)
for i in itertools.permutations(a):
    iter_a2.append(i)
print(iter_a2)
for j in range(len(b)+1):    
    for i in itertools.combinations(b,j):
        if ''.join(i)!='':
            iter_b2.append(''.join(i))
print(iter_b2)
예제 #39
0
def phase_settings(low, high):
    for x in itertools.permutations(range(low, high)):
        yield x
예제 #40
0
#Fetching the predictions
data.readline()  #won't need the length of predictions

predictions = [re.split('\s*', l.rstrip()) for l in data.readlines()]


def create_range_for_prediction(prediction):
    return set(range(int(prediction[0]), int(prediction[1]) + 1))


def prediction_is_available(prediction, ranges_used):
    prediction_range = create_range_for_prediction(prediction)
    for range_used in ranges_used:
        if len(range_used.intersection(prediction_range)) > 0:
            return False
    return True


totals = []
for permutation in itertools.permutations(predictions):
    ranges_used = []
    i_total = 0
    for i in permutation:
        if prediction_is_available(i, ranges_used):
            i_total = i_total + int(i[2])
            ranges_used.append(create_range_for_prediction(i))
    totals.append(i_total)

print max(totals)
예제 #41
0
import itertools

from day5.puzzle import opcodes, run_ops

state = {
    'value': 0,
    'input': 0,
    'phase': 0,
    'best_result': (0, 0),
    'interrupt': False
}
phase_settings = list(itertools.permutations(range(5)))


def reset_state():
    state['value'] = 0
    state['input'] = 0
    state['phase'] = 0


def output_func(value):
    state['value'] = value


def input_func():
    if state['input'] == 0:
        state['input'] = 1
        return state['phase']
    else:
        state['input'] = 0
        return state['value']
예제 #42
0
파일: tests2B.py 프로젝트: davis9ja/tfimsrg
def test_refs(plots_dir, main):
    """The purpose of this test is to compare the result of full 
    configuration interaction (i.e. exact diagonalization) to the result of 
    IM-SRG(2) for every possible reference state created from 8 single
    particle states and 4 particles.
    
    Arguments:

    plots_dir -- directory to store plot outputs
    main -- main method for IM-SRG(2) (PASSED IN FROM main.py)

    Returns:

    Nothing"""

    assert isinstance(plots_dir, str), "Enter plots directory as string"
    assert (plots_dir[-1] == '\\'
            or plots_dir[-1] == '/'), "Directory must end in slash (\\ or /)"

    if not os.path.exists(plots_dir):
        os.mkdir(plots_dir)

    start = -1.0
    stop = 1.0
    num = 5

    g_vals = np.linspace(start, stop, num)
    refs = list(map("".join, itertools.permutations('11110000')))
    refs = list(dict.fromkeys(refs))  # remove duplicates
    refs = [list(map(int, list(ref))) for ref in refs]

    fig_corr = plt.figure(figsize=[12, 8])
    fig_conv = plt.figure(figsize=[12, 8])
    ax_corr = fig_corr.add_subplot(1, 1, 1)
    ax_conv = fig_conv.add_subplot(1, 1, 1)

    for pb in g_vals:
        E_exacts = []

        for g in g_vals:
            E_corrs = []
            # plt.figure(figsize=[12,8])
            ref_rand = random.sample(refs, 20)
            E_exact = ci_matrix.exact_diagonalization(1.0, g, pb)
            # E_exacts.append(E_exact - (2-g))
            E_exacts.append(E_exact)
            refs_conv = []
            for ref in refs:

                data = main(4, 4, ref=ref, d=1.0, g=g, pb=pb)

                if data[0] == 1:
                    E_vals = data[7]
                    E_corr = E_vals[-1]

                    # E_corrs.append(E_corr - (2-g))
                    E_corrs.append(E_corr)
                    refs_conv.append(ref)

                    ax_conv.plot(data[6], data[7])

            # ymin, ymax = ax_conv.get_ylim()
            # ax_conv.set_ylim(bottom=0.7*ymin, top=0.7*ymax)
            ax_conv.set_ylabel('Energy')
            ax_conv.set_xlabel('scale parameter')
            ax_conv.set_title(
                'Convergence for \n g={:2.4f}, pb={:2.4f}'.format(g, pb))
            ax_conv.legend(refs_conv)
            pb_plots_dir = plots_dir + 'pb{:2.4f}\\'.format(pb)
            if not os.path.exists(pb_plots_dir):
                os.mkdir(pb_plots_dir)

            fig_conv.savefig(pb_plots_dir +
                             'g{:2.4f}_pb{:2.4f}.png'.format(g, pb))
            ax_conv.clear()

            with open(plots_dir + 'g{:2.4f}_pb{:2.4f}.txt'.format(g, pb),
                      'w') as f:
                f.write('Pairing model: d = 1.0, g = {:2.4f}, pb = {:2.4f}\n'.
                        format(g, pb))
                f.write(
                    'Full CI diagonalization -- correlation energy: {:2.8f}\n'.
                    format(E_exacts[-1]))
                f.write(
                    'IMSRG(2) variable reference state -- correlation energies:\n'
                )
                if len(refs_conv) == 0:
                    f.write(
                        'No convergence for range of reference states tested\n'
                    )
                else:
                    for i in range(len(refs_conv)):
                        f.write('{:2.8f} | {d}\n'.format(E_corrs[i],
                                                         d=refs_conv[i]))

                    f.write('Ground state from IMSRG(2):\n')
                    e_sort_ind = np.argsort(E_corrs)
                    print(e_sort_ind)
                    print(E_corrs)
                    f.write('{:2.8f} | {d}\n'.format(
                        E_corrs[e_sort_ind[0]], d=refs_conv[e_sort_ind[0]]))
예제 #43
0
            c = nc
    return c


def compare(m1, m2):
    l1 = getListFromSquare(m1)
    l2 = getListFromSquare(m2)

    cost = 0
    for i in range(9):
        cost += abs(l1[i] - l2[i])
    return cost


m = getRandomMatrix()
ls = itertools.permutations(list(range(1, 10)))
ms = getSquaresFromLists(ls)
ms = filterMagicSquares(ms)
#ms=filterMagicSquares15(ms)

ms = [[[2, 7, 6], [9, 5, 1], [4, 3, 8]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]],
      [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]],
      [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]],
      [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]]]

#qs=[[[1, 6, 8], [3, 5, 7], [2, 4, 9]], [[1, 6, 8], [7, 5, 3], [2, 4, 9]], [[1, 8, 6], [3, 5, 7], [4, 2, 9]], [[1, 8, 6], [7, 5, 3], [4, 2, 9]], [[1, 9, 5], [2, 6, 7], [4, 3, 8]], [[1, 9, 5], [3, 8, 4], [2, 7, 6]], [[1, 9, 5], [4, 8, 3], [2, 7, 6]], [[1, 9, 5], [7, 6, 2], [4, 3, 8]], [[2, 4, 9], [3, 5, 7], [1, 6, 8]], [[2, 4, 9], [7, 5, 3], [1, 6, 8]], [[2, 6, 7], [1, 5, 9], [3, 4, 8]], [[2, 6, 7], [9, 5, 1], [3, 4, 8]], [[2, 7, 6], [1, 5, 9], [4, 3, 8]], [[2, 7, 6], [3, 4, 8], [5, 1, 9]], [[2, 7, 6], [3, 8, 4], [1, 9, 5]], [[2, 7, 6], [4, 8, 3], [1, 9, 5]], [[2, 7, 6], [8, 4, 3], [5, 1, 9]], [[2, 7, 6], [9, 5, 1], [4, 3, 8]], [[2, 9, 4], [1, 6, 8], [5, 3, 7]], [[2, 9, 4], [1, 8, 6], [3, 7, 5]], [[2, 9, 4], [3, 5, 7], [6, 1, 8]], [[2, 9, 4], [6, 8, 1], [3, 7, 5]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[2, 9, 4], [8, 6, 1], [5, 3, 7]], [[3, 4, 8], [1, 5, 9], [2, 6, 7]], [[3, 4, 8], [9, 5, 1], [2, 6, 7]], [[3, 7, 5], [1, 8, 6], [2, 9, 4]], [[3, 7, 5], [2, 4, 9], [6, 1, 8]], [[3, 7, 5], [6, 8, 1], [2, 9, 4]], [[3, 7, 5], [9, 4, 2], [6, 1, 8]], [[3, 8, 4], [1, 5, 9], [6, 2, 7]], [[3, 8, 4], [9, 5, 1], [6, 2, 7]], [[4, 2, 9], [3, 5, 7], [1, 8, 6]], [[4, 2, 9], [7, 5, 3], [1, 8, 6]], [[4, 3, 8], [1, 5, 9], [2, 7, 6]], [[4, 3, 8], [2, 6, 7], [1, 9, 5]], [[4, 3, 8], [6, 2, 7], [5, 1, 9]], [[4, 3, 8], [7, 2, 6], [5, 1, 9]], [[4, 3, 8], [7, 6, 2], [1, 9, 5]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[4, 8, 3], [1, 5, 9], [7, 2, 6]], [[4, 8, 3], [9, 5, 1], [7, 2, 6]], [[4, 9, 2], [1, 6, 8], [7, 3, 5]], [[4, 9, 2], [1, 8, 6], [5, 7, 3]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[4, 9, 2], [6, 8, 1], [5, 7, 3]], [[4, 9, 2], [7, 5, 3], [8, 1, 6]], [[4, 9, 2], [8, 6, 1], [7, 3, 5]], [[5, 1, 9], [3, 4, 8], [2, 7, 6]], [[5, 1, 9], [6, 2, 7], [4, 3, 8]], [[5, 1, 9], [7, 2, 6], [4, 3, 8]], [[5, 1, 9], [8, 4, 3], [2, 7, 6]], [[5, 3, 7], [1, 6, 8], [2, 9, 4]], [[5, 3, 7], [4, 2, 9], [6, 1, 8]], [[5, 3, 7], [8, 6, 1], [2, 9, 4]], [[5, 3, 7], [9, 2, 4], [6, 1, 8]], [[5, 7, 3], [1, 8, 6], [4, 9, 2]], [[5, 7, 3], [2, 4, 9], [8, 1, 6]], [[5, 7, 3], [6, 8, 1], [4, 9, 2]], [[5, 7, 3], [9, 4, 2], [8, 1, 6]], [[5, 9, 1], [2, 6, 7], [8, 3, 4]], [[5, 9, 1], [3, 8, 4], [6, 7, 2]], [[5, 9, 1], [4, 8, 3], [6, 7, 2]], [[5, 9, 1], [7, 6, 2], [8, 3, 4]], [[6, 1, 8], [2, 4, 9], [3, 7, 5]], [[6, 1, 8], [3, 5, 7], [2, 9, 4]], [[6, 1, 8], [4, 2, 9], [5, 3, 7]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[6, 1, 8], [9, 2, 4], [5, 3, 7]], [[6, 1, 8], [9, 4, 2], [3, 7, 5]], [[6, 2, 7], [1, 5, 9], [3, 8, 4]], [[6, 2, 7], [9, 5, 1], [3, 8, 4]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[6, 7, 2], [3, 4, 8], [9, 1, 5]], [[6, 7, 2], [3, 8, 4], [5, 9, 1]], [[6, 7, 2], [4, 8, 3], [5, 9, 1]], [[6, 7, 2], [8, 4, 3], [9, 1, 5]], [[6, 7, 2], [9, 5, 1], [8, 3, 4]], [[6, 8, 1], [3, 5, 7], [9, 2, 4]], [[6, 8, 1], [7, 5, 3], [9, 2, 4]], [[7, 2, 6], [1, 5, 9], [4, 8, 3]], [[7, 2, 6], [9, 5, 1], [4, 8, 3]], [[7, 3, 5], [1, 6, 8], [4, 9, 2]], [[7, 3, 5], [4, 2, 9], [8, 1, 6]], [[7, 3, 5], [8, 6, 1], [4, 9, 2]], [[7, 3, 5], [9, 2, 4], [8, 1, 6]], [[7, 6, 2], [1, 5, 9], [8, 4, 3]], [[7, 6, 2], [9, 5, 1], [8, 4, 3]], [[8, 1, 6], [2, 4, 9], [5, 7, 3]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[8, 1, 6], [4, 2, 9], [7, 3, 5]], [[8, 1, 6], [7, 5, 3], [4, 9, 2]], [[8, 1, 6], [9, 2, 4], [7, 3, 5]], [[8, 1, 6], [9, 4, 2], [5, 7, 3]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]], [[8, 3, 4], [2, 6, 7], [5, 9, 1]], [[8, 3, 4], [6, 2, 7], [9, 1, 5]], [[8, 3, 4], [7, 2, 6], [9, 1, 5]], [[8, 3, 4], [7, 6, 2], [5, 9, 1]], [[8, 3, 4], [9, 5, 1], [6, 7, 2]], [[8, 4, 3], [1, 5, 9], [7, 6, 2]], [[8, 4, 3], [9, 5, 1], [7, 6, 2]], [[8, 6, 1], [3, 5, 7], [9, 4, 2]], [[8, 6, 1], [7, 5, 3], [9, 4, 2]], [[9, 1, 5], [3, 4, 8], [6, 7, 2]], [[9, 1, 5], [6, 2, 7], [8, 3, 4]], [[9, 1, 5], [7, 2, 6], [8, 3, 4]], [[9, 1, 5], [8, 4, 3], [6, 7, 2]], [[9, 2, 4], [3, 5, 7], [6, 8, 1]], [[9, 2, 4], [7, 5, 3], [6, 8, 1]], [[9, 4, 2], [3, 5, 7], [8, 6, 1]], [[9, 4, 2], [7, 5, 3], [8, 6, 1]]]
c = getMinimumCost(m, ms)
#print(c)

a1 = [[4, 9, 2], [3, 5, 7], [8, 1, 5]]
예제 #44
0
        case = 1
    if exclude_property_type is not None and exclude_atom_type is None:
        case = 2
    if exclude_property_type is not None and exclude_atom_type is not None:
        case = 3
    if include_property_type is not None:
        case = 4

    shortened_list = []
    for type_list, index_list in type_index_dict.items():
        if case == 1 and all(single_type not in type_list
                             for single_type in exclude_atom_type):
            shortened_list.extend(index_list)
        elif case == 2 and all(
                list(value) not in exclude_property_type
                for value in list(permutations(type_list))):
            shortened_list.extend(index_list)
        elif case == 3 and all(single_type not in type_list for single_type in exclude_atom_type) and \
                all(list(value) not in exclude_property_type for value in list(permutations(type_list))):
            shortened_list.extend(index_list)
        elif case == 4 and any(
                list(value) in include_property_type
                for value in list(permutations(type_list))):
            shortened_list.extend(index_list)

    return shortened_list


def set_up_openMM_system(folder_path, cluster_tag_number, shortened_bond_list):
    """ Feed pdb topology file and xml force field file into openMM, generate a system for the MD simulation/force
    calculation.
예제 #45
0
 def permute(self, word):
     return [''.join(x) for x in permutations(word)]
def mesh(n):
    oef = ''
    for (x, y) in permutations((d, h, b), 2):
        oef += duo(x, y, n)
    return oef
예제 #47
0
from itertools import permutations

n, k = map(int, input().split())
s = input()
for t in permutations(sorted(s)):
    cnt = 0
    for a, b in zip(s, t):
        if a == b:
            pass
        else:
            cnt += 1
    if cnt <= k:
        print(''.join(list(t)))
        exit()
if __name__ == '__main__':
    n, m, k = map(int, input().split())
    graph = list()
    action_list = list()
    pick_list = [num for num in range(0, k)]
    answer = 1000000

    for _ in range(n):
        graph.append(list(map(int, input().split())))

    for _ in range(k):
        action_list.append(list(map(int, input().split())))

    # s와 c를 1씩 빼주고 고려
    for pick_situation in permutations(pick_list, k):
        insert_graph = list()
        for arr in graph:
            insert_graph.append(arr[:])

        for pick_num in pick_situation:
            pick = action_list[pick_num]
            insert_start_list = [pick[0] - pick[2] - 1, pick[1] - pick[2] - 1]
            insert_end_list = [pick[0] + pick[2] - 1, pick[1] + pick[2] - 1]
            insert_graph = simulation(insert_start_list, insert_end_list,
                                      insert_graph)

        temp_answer = calc_graph(insert_graph)

        answer = min(answer, temp_answer)
예제 #49
0
    def test(self):
        all_psnr = []  # All signal to noise ratios over all the batches
        all_percentages = []  # All percentage accuracies
        dummy_metrics = []  # Metrics for the averaging value

        # Load the score network
        states = torch.load(os.path.join(self.args.log, 'checkpoint.pth'), map_location=self.config.device)
        scorenet = CondRefineNetDilated(self.config).to(self.config.device)
        scorenet = torch.nn.DataParallel(scorenet)
        scorenet.load_state_dict(states[0])
        scorenet.eval()

        # Grab the first two samples from MNIST
        trans = transforms.Compose([transforms.ToTensor()])
        dataset = MNIST(os.path.join(self.args.run, 'datasets', 'mnist'), train=False, download=True)

        first_digits_idx = dataset.train_labels <= 4
        second_digits_idx = dataset.train_labels >=5

        first_digits = dataset.train_data[first_digits_idx]
        second_digits = dataset.train_data[second_digits_idx]



        for iteration in range(100):
            print("Iteration {}".format(iteration))
            curr_dir = os.path.join(SAVE_DIR, "{:07d}".format(iteration))
            if not os.path.exists(curr_dir):
                os.makedirs(curr_dir)
            # image1, image2 = get_images_split(first_digits, second_digits)
            gt_images = []
            for _ in range(N):
                gt_images.append(get_single_image(dataset))

            mixed = sum(gt_images).float()

            mixed_grid = make_grid(mixed.detach() / float(N), nrow=GRID_SIZE, pad_value=1., padding=1)
            save_image(mixed_grid, os.path.join(curr_dir, "mixed.png"))

            for i in range(N):
                gt_grid = make_grid(gt_images[i], nrow=GRID_SIZE, pad_value=1., padding=1)
                save_image(gt_grid, os.path.join(curr_dir, "gt{}.png".format(i)))

            mixed = torch.Tensor(mixed).cuda().view(BATCH_SIZE, 1, 28, 28)

            xs = []
            for _ in range(N):
                xs.append(nn.Parameter(torch.Tensor(BATCH_SIZE, 1, 28, 28).uniform_()).cuda())

            step_lr=0.00002

            # Noise amounts
            sigmas = np.array([1., 0.59948425, 0.35938137, 0.21544347, 0.12915497,
                               0.07742637, 0.04641589, 0.02782559, 0.01668101, 0.01])
            n_steps_each = 100

            for idx, sigma in enumerate(sigmas):
                # if idx <= 5:
                #     lambda_recon = 1./(sigma**2)
                # else:
                #     lambda_recon = 2./(sigma**2)
                lambda_recon = 0.5/(sigma**2)
                # Not completely sure what this part is for
                labels = torch.ones(1, device=xs[0].device) * idx
                labels = labels.long()
                step_size = step_lr * (sigma / sigmas[-1]) ** 2

                for step in range(n_steps_each):
                    noises = []
                    for _ in range(N):
                        noises.append(torch.randn_like(xs[0]) * np.sqrt(step_size * 2))

                    grads = []
                    for i in range(N):
                        grads.append(scorenet(xs[i].view(BATCH_SIZE, 1, 28, 28), labels).detach())

                    recon_loss = (torch.norm(torch.flatten(sum(xs) - mixed)) ** 2)
                    recon_grads = torch.autograd.grad(recon_loss, xs)

                    for i in range(N):
                        xs[i] = xs[i] + (step_size * grads[i]) + (-step_size * lambda_recon * recon_grads[i].detach()) + noises[i]

                    # x = x + (-step_size * lambda_recon * recon_grads[0].detach()) + noise_x
                    # y = y + (-step_size * lambda_recon * recon_grads[1].detach()) + noise_y

            for i in range(N):
                xs[i] = torch.clamp(xs[i], 0, 1)

            x_to_write = []
            for i in range(N):
                x_to_write.append(torch.Tensor(xs[i].detach().cpu()))

            # PSNR Measure
            for idx in range(BATCH_SIZE):
                best_psnr = -10000
                best_permutation = None
                for permutation in permutations(range(N)):
                    curr_psnr = sum([psnr(xs[permutation[i]][idx], gt_images[i][idx].cuda()) for i in range(N)])
                    if curr_psnr > best_psnr:
                        best_psnr = curr_psnr
                        best_permutation = permutation

                all_psnr.append(best_psnr / float(N))
                for i in range(N):
                    x_to_write[i][idx] = xs[best_permutation[i]][idx] 

                    mixed_psnr = psnr(mixed.detach().cpu()[idx] / float(N), gt_images[i][idx])
                    dummy_metrics.append(mixed_psnr)
                
            for i in range(N):
                x_grid = make_grid(x_to_write[i], nrow=GRID_SIZE, pad_value=1., padding=1)
                save_image(x_grid, os.path.join(curr_dir, "x{}.png".format(i)))

            mixed_grid = make_grid(sum(xs)/float(N), nrow=GRID_SIZE, pad_value=1., padding=1)
            save_image(mixed_grid, os.path.join(curr_dir, "recon.png".format(i)))


            # average_grid = make_grid(mixed.detach()/2., nrow=GRID_SIZE)
            # save_image(average_grid, "results/average_cifar.png")
            
            print("Curr mean {}".format(np.array(all_psnr).mean()))
            print("Const mean {}".format(np.array(dummy_metrics).mean()))
예제 #50
0
import re
import itertools

lines = filter(None, open('d13.in').read().split('\n'))

match = {}
people = set()

for line in lines:
    a, signal, number, b = re.findall(r'(\w+) \w+ (\w+) (\d+) .* (\w+)\.', line)[0]
    match[a + b] = int(number) * (1 if signal == 'gain' else -1)
    people.add(a)

def cost(p):
    size = len(p)
    gain = 0
    for i in range(size):
        gain += match[p[i] + p[i-1]]
        gain += match[p[i] + p[(i+1) % size]]
    return gain

print('P1:',max([cost(p) for p in itertools.permutations(people)]))

for person in people:
    match[person + 'me'] = 0
    match['me' + person] = 0

people.add('me')

print('P2:',max([cost(p) for p in itertools.permutations(people)]))
예제 #51
0
        permutes = permutations(inputArr, 4)
        for arr in permutes:
            if self.isTenizable(arr):
                print("Yes")
                return
        else:
            print("No")
            return


if __name__ == "__main__":
    # four2ten = FourDigitsToTen()
    # four2ten.main()

    inputArr = list(map(str, input().split()))
    for nums in permutations(inputArr, 4):
        for ops in product(["+", "-", "*", "/"], repeat=3):
            for order in permutations(range(3), 3):
                arr = list(nums)
                stack = deque([])
                fst = order.index(0)
                snd = order.index(1)
                trd = order.index(2)
                stack.extend([arr[fst], arr[fst + 1], ops[fst]])
                arr.pop(fst + 1)
                arr.pop(fst)
                if abs(snd - fst) > 1:
                    stack.extend([*arr, ops[snd], ops[trd]])
                else:
                    sndNum = int(snd > trd)
                    trdNum = 1 - sndNum
예제 #52
0
                self.program[dest] = int(first < second)
            elif code == 8:
                _, _, dest = raw_params
                first, second, _ = params
                self.program[dest] = int(first == second)
            elif code == 9:
                pass


def run_amplifiers(program, phases):
    vms = [VM(program) for _ in range(5)]
    for phase, vm in zip(phases, vms):
        vm.add_input(phase)
    vms[0].add_input(0)

    while vms[4].done is False:
        for i, vm in enumerate(vms):
            vms[(i + 1) % 5].add_input(vm.output[-1])

    return vms[4].output[-1]


# p1
print(max(
    run_amplifiers(program, phases) for phases in permutations(range(5))))
# p2
print(
    max(
        run_amplifiers(program, phases)
        for phases in permutations(range(5, 10))))
예제 #53
0
 def support(self, sentence, phrase, h):
     indices = list(range(len(phrase)))
     return it.permutations(indices)
예제 #54
0
def checkio(chips):
    return max(count(p, 0, None, None, 0) for p in permutations(chips))
예제 #55
0
def solveAll(queens):
    perms = {p for p in permutations(''.join(str(i) for i in range(1, n + 1)))}
    return {perm for perm in perms if conflicts(perm) == 0}
예제 #56
0
def true_ngram_perm_norm(score, n, xs):
    return logsumexp(
        score_ngram_sequence(score, n, perm) for perm in it.permutations(xs))
예제 #57
0
m = {
    "acedgfb": 8,
    "cdfbe": 5,
    "gcdfa": 2,
    "fbcad": 3,
    "dab": 7,
    "cefabd": 9,
    "cdfgeb": 6,
    "eafb": 4,
    "cagedb": 0,
    "ab": 1
}

m = {"".join(sorted(k)): v for k, v in m.items()}

ans = 0
for line in data:
    a, b = line.split(" | ")
    a = a.split(" ")
    b = b.split(" ")
    for perm in itertools.permutations("abcdefg"):
        permMap = {a: b for a, b in zip(perm, "abcdefg")}
        aNew = ["".join(permMap[c] for c in x) for x in a]
        bNew = ["".join(permMap[c] for c in x) for x in b]
        if all("".join(sorted(an)) in m for an in aNew):
            bNew = ["".join(sorted(x)) for x in bNew]
            ans += int("".join(str(m[x]) for x in bNew))
            break
print(ans)
예제 #58
0
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()
def II(): return int(input())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res
def gcd(x, y):
    if x < y: x, y = y, x
    div = x % y
    while div != 0:
        x, y = y, div
        div = x % y
    return y

N=II()

DIC = list(permutations(list(range(1, N+1)), N))
a=DIC.index(tuple(LI()))
b=DIC.index(tuple(LI()))

print(abs(a-b))
예제 #59
0
from itertools import permutations

n = 3

# easy with itertools permutation
permut = list(permutations(range(1, n + 1)))
# write to file for large n
with open("rosalind_perm_results.txt", "w") as outfile:
    print(len(permut), file=outfile)
    [print(" ".join(list(map(str, i))), file=outfile) for i in permut]
예제 #60
0
def solve(queens):
    perms = {p for p in permutations(''.join(str(i) for i in range(1, n + 1)))}
    for perm in perms:
        if conflicts(perm) == 0:
            return perm