Example #1
0
def rubik():
    n = 48
    base = Permutation.identity(n)

    L = [(1, 3, 8, 6), (2, 5, 7, 4), (33, 9, 41, 32), (36, 12, 44, 29),
         (38, 14, 46, 27)]
    F = [(9, 11, 16, 14), (10, 13, 15, 12), (38, 17, 43, 8), (39, 20, 42, 5),
         (40, 22, 41, 3)]
    R = [(17, 19, 24, 22), (18, 21, 23, 20), (48, 16, 40, 25),
         (45, 13, 37, 28), (43, 11, 35, 30)]
    B = [(25, 27, 32, 30), (26, 29, 31, 28), (19, 33, 6, 48), (21, 34, 4, 47),
         (24, 35, 1, 46)]
    U = [(33, 35, 40, 38), (34, 37, 39, 36), (25, 17, 9, 1), (26, 18, 10, 2),
         (27, 19, 11, 3)]
    D = [(41, 43, 48, 46), (42, 45, 47, 44), (6, 14, 22, 30), (7, 15, 23, 31),
         (8, 16, 24, 32)]

    generator_set = [L, F, R, B, U, D]
    generator_set = [
        Permutation.from_cycles(n, move) for move in generator_set
    ]

    example = Schreier.Algorithm(n, generator_set, base)
    example.run()

    print(example.get_order())
Example #2
0
def listAll(anInt):
   theList = []
   for k in range(anInt):
       theList.append(k)
   z = Permutation(theList)
   for k in range(factorial(len(z.data))):
       b = factoradic(k,len(z.data))
       c = z.permutation(k)
       d = z.getPermutationIndex(c)
       print "%s\t%s\t%s\t%s" % (k,b,c,d)
Example #3
0
    def rec(self, pos):
        self.stab_chain[pos].build_tree()
        schreier_generators = self.stab_chain[pos].get_schreier_generators()

        for h in schreier_generators:
            residue, break_pos = self.check_element(h)
            if residue != Permutation.identity(self.n):
                if break_pos == len(self.stab_chain) - 1:
                    self.stab_chain.append(
                        self.ChainSegment(self.n, [Permutation.identity(self.n)], self.base[len(self.stab_chain) + 1]))
                for broken in range(break_pos, pos, -1):
                    self.stab_chain[broken].stab_gen.append(residue)
                    self.rec(broken)
Example #4
0
    def getPermutedFeynmans(self):
        # This method finds all possible permutaions of a list of photon
        # objects, returns a list of Feynman objects, each with a different
        # possible permutation
        
        feyn_list = []  #list of feynman diagrams
        photon_list = self.getTupleSet()
        N_photons = len(photon_list)

        permuted_photons = Permutation.getPermutations(photon_list)
        N_permutations = len(permuted_photons)

        # create list of feynman objects for each permutation
        for i in range(N_permutations):
            temp_feyn = Feynman()   #new feynman diagram
            for j in range(N_photons):
                # generate temp_photon from permutation
                temp_tuple = permuted_photons[i][j]
                temp_photon = Photon.Photon(temp_tuple[0],temp_tuple[1])
                #add new photon to new feynman diagram
                temp_feyn.addPhoton(temp_photon)
            
            # make Omegas and Mus consistent for all permutations of feyn
            temp_feyn.linkMolecule(self.linkedMol)
            
            # add new feynman diagram to list of feynman diagrams
            feyn_list.append(temp_feyn)

        return feyn_list
Example #5
0
    def testPermutation(self):
        print("\n%%%%%%% Testing Permutation")

        expectedResult = 336
        result = Permutation.permutation(8, 3)
        print("permutation(8,3)=" + str(result))
        self.assertEqual(result, expectedResult, msg="Permutation(8,3)")

        expectedResult = 120
        result = Permutation.permutation(5, 5)
        print("permutation(5,5)=" + str(result))
        self.assertEqual(result, expectedResult, msg="Permutation(5,5)")

        expectedResult = 132
        result = Permutation.permutation(12, 2)
        print("permutation(12,2)=" + str(result))
        self.assertEqual(result, expectedResult, msg="Permutation(12,2)")
Example #6
0
def example_A_5():

    print('Пример работы с группой A_5\n')

    a = Permutation([2, 3, 1, 4, 5])
    b = Permutation([1, 3, 4, 2, 5])
    c = Permutation([1, 2, 4, 5, 3])

    print('Образующие A_5:')
    print('a =', a)
    print('b =', b)
    print('c =', c)
    print()

    A_5 = StabilizerChain([a, b, c])

    print('|A_5| =', A_5.ord())
    print()

    print('Орбита 1: ', A_5.get_orbit(1))
    print('Орбита 2 в Stab_1:', A_5[1].tree.get_orbit())
    print('Образующие Stab_{1, 2}:', A_5.get_gen_set(2))
    print()

    print('Сильное порождающее множество для A_5:')
    print(A_5.get_strong_gen_set())
    print()

    sigma = Permutation([2, 1, 3, 4, 5])
    print('Сожержится ли', sigma, 'в A_5?', A_5.contains(sigma))
    print()

    sigma = Permutation([2, 1, 4, 3, 5])
    print('Содержится ли', sigma, 'в A_5?', A_5.contains(sigma))
    print()

    print('Разложение через Сильное порождающее множество:')
    print(sigma, '=', A_5.contains(sigma, need_decomp=True))

    print('\n- - - - - - - - - - - - - - - - - - - - - - - - -\n')

    return A_5
Example #7
0
def example_permutations():

    print('\n- - - - - - - - - - - - - - - - - - - - - - - - -\n')

    print('Пример работы с перестановками\n')

    a = Permutation([3, 4, 1, 2, 6, 7, 5])
    print('a =', a)

    b = to_perm([1, 5, 4, 3, 2])
    print('b =', b)

    c = to_perm('(5 7 1 4 8)')
    print('c =', c)
    print()

    print('a * b =', a * b)
    print('b * a =', b * a)
    print()

    print('b * c =', b * c)
    print('c * b =', c * b)
    print()

    print('a ^ 0 =', a**0)
    print('a ^ 1 =', a**1)
    print('a ^ 3 =', a**3)
    print('a ^ 226 =', a**226)
    print('a ^ 123456789 =', a**123456789)
    print('a ^ -1 =', a**-1)
    print('a ^ -2 =', a**-2)
    print()

    print('ord(a) =', a.ord())
    print('ord(b) =', b.ord())
    print()

    print('a = b ?', a == b)
    print('c = (8 5 7 1 4) ?', c == to_perm('(8 5 7 1 4)'))

    print('\n- - - - - - - - - - - - - - - - - - - - - - - - -\n')
Example #8
0
def task():
    n = 56
    rows = 7
    cols = 8

    swap_rows_cols = []
    for i in range(rows):
        for j in range(cols):
            swap_rows_cols.append(j * rows + i + 1)
    swap_rows_cols = Permutation.Perm(swap_rows_cols)
    print(swap_rows_cols.as_cycles())  # first generator

    swap_halves = Permutation.Perm([(n // 2 + i) % n + 1 for i in range(n)])
    print(swap_halves.as_cycles())  # second generator

    generator_set = [swap_rows_cols, swap_halves]

    # top cards in right order
    print("Enter top cards order")
    print("example: 1 3 2 4 will check deck with these cards on the top")
    order = list(map(int, input().split()))
    base = order.copy()
    for i in range(1, n + 1):
        if i not in base:
            base.append(i)
    base = Permutation.Perm(base)
    print(order)

    cards = Schreier.Algorithm(n, generator_set, base)
    cards.run()

    print(cards.get_order())  # order of group
    print(cards.stab_chain[1].stab_gen)  # generators of stabilizer of point 1

    residue, level = cards.check_element(base)
    print(residue, level)
    if level >= len(order):
        print("Possible")
    else:
        print("Impossible")
Example #9
0
 def summary(self):
     x_features = self.x
     if self.xbin and self.x_bin != 0:   # x bins
         x_freq = equal_freq(x_features, self.x_bin) \
             if self.bin_type == 'freq' \
             else equal_width(x_features, self.x_bin)
     else:
         x_freq = x_features
     if self.ybin and self.y_bin != 0:  # y bins
         y_freq = equal_freq(self.y, self.y_bin) \
             if self.bin_type == 'freq' \
             else equal_width(self.y, self.y_bin)
     else:
         y_freq = self.y
     mi = fGain(x_freq, y_freq) if self.fraction else gain(x_freq, y_freq)
     if self.permut:
         permut = Permutation(x_freq, y_freq).summary()
         permut = permut / entropy(y_freq) if self.fraction else permut
         mi -= permut
     return mi
Example #10
0
import Permutation

prime = [0, 2, 3, 5, 7, 11, 13, 17]

num = [str(i) for i in range(10)]
allnums = []
while not Permutation.isEnd(num):
    isPan = True
    for k in range(1, 8):
        if int(''.join(num[k:k + 3]).lstrip('0')) % prime[k] != 0:
            isPan = False
            break

    if isPan:
        print(int(''.join(num)))
        allnums.append(int(''.join(num)))
    num = Permutation.nextPermuteStr(num)

sum = 0
for n in allnums:
    sum += n

print(sum)
Example #11
0
import MathUtils
import Permutation as permutation

num = 987654321
max = 2
while num > 0:
    if MathUtils.isPrime(num):
        max = num
        print("max prime: {}".format(num))
        break

    if permutation.isBegin(list(str(num))):
        num = list(str(num / 10)).sort(reverse=True)
        num = int(str(num))
    else:
        num = int(''.join(permutation.lastPermuteStr(list(str(num)))))
Example #12
0
def my_task():
    '''
    
    Условие задачи
    
    Цыганка гадает вам на картах. Она раскладывает 56 карт из младшей колоды таро на столе в семь рядов по 8 карт в каждом (сначала она заполняет верхний ряд слева направо, а потом переходит к следующему и т.д.). Потом она собирает карты обратно в колоду по столбцам (сверху оказывается карта в левом верхнем углу, снизу в правом нижнем). Собирая карты, цыганка может немного их перемешать, снимая верхнюю половину колоды и кладя её под низ.
    
    Цыганка хочет добиться воспроизводимости гадания (полезно для бизнеса).
    
    1). Какими способами она может тасовать карты так, чтобы сверху оставалась та же карта, которая была там до тасования?
    
    2). Может ли она при этом подложить под верхнюю карту любую другую заранее выбранную, и если да, то каким количеством способов?
    
    '''

    print('Тестовая задача\n')

    print('Перестановки, порождающие группу TG: ')  # как я понял из условия
    a = Permutation([
        1, 9, 17, 25, 33, 41, 49, 2, 10, 18, 26, 34, 42, 50, 3, 11, 19, 27, 35,
        43, 51, 4, 12, 20, 28, 36, 44, 52, 5, 13, 21, 29, 37, 45, 53, 6, 14,
        22, 30, 38, 46, 54, 7, 15, 23, 31, 39, 47, 55, 8, 16, 24, 32, 40, 48,
        56
    ])

    b = Permutation([
        29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
        47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
        11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28
    ])

    print('a =', a)  # (2 ... 8)(4 ... 22)(6 ... 36)(12 ... 23)
    print('b =', b)  # (1 29)(2 30)(3 31)(4 32)...(27 55)(28 56)
    print()
    stdout.flush()

    # Строим полную цепочку стабилизаторов
    TG = StabilizerChain([a, b])

    print('|TG| =', TG.ord())  # 20460710453732638271310403731456000000

    stab_1 = TG.ord() // len(TG[0].tree)
    print('|Stab_1| =', stab_1)  # 365369829530939969130542923776000000
    print()

    print('Орбита второй карты в Stab_1 =',
          TG[1].tree.get_orbit())  # {2, 3, 4, ..., 54, 55}
    # -> Для всех чисел, кроме {1, 56} ответ на 2-ой вопрос - Можно
    print()

    stab_12 = TG.ord() // len(TG[0].tree) // len(TG[1].tree)
    print('|Stab_{1, 2}| =', stab_12)  # 6766107954276666095010054144000000
    print()

    x = int(input('Введите карту, которую нужно поместить под 1-ую: '))
    answer_x = stab_12
    if x in [1, 56]:
        answer_x = 0
    print('Количество способов поместить карту', x, 'под 1-ую =', answer_x)

    print('\n- - - - - - - - - - - - - - - - - - - - - - - - -\n')

    return TG
Example #13
0
# Am * Bn = Cm+n where 2*(m + n) = 9
# or Am * Bn = Cm+n+1 2*(m + n) + 1= 9
# =>  m + n = 4
import math
import Permutation as lp

numbers = [i for i in range(1, 10)]
ans = set([])

while (not lp.isEnd(numbers)):
    C = numbers[0] + numbers[1] * 10 + numbers[2] * 100 + numbers[3] * 1000
    A = numbers[4] + numbers[5] * 10
    B = numbers[6] + numbers[7] * 10 + numbers[8] * 100
    if A * B == C:
        ans.add(C)
    A = numbers[4]
    B = numbers[5] + numbers[6] * 10 + numbers[7] * 100 + numbers[8] * 1000
    if A * B == C:
        ans.add(C)
    numbers = lp.nextPermuteStr(numbers)

res = 0
ans = list(ans)
for i in range(len(ans)):
    res += ans[i]

print(res)
Example #14
0
    subs_count = {}
    for i in range(0, len(lst) - 2):
        for j in range(i + 1, len(lst) - 1):
            for k in range(j + 1, len(lst)):
                if lst[k] - lst[j] == lst[j] - lst[i]:
                    print(lst[i], lst[j], lst[k])
                    return


sequence_set = set([])
all_set = set([])
for prime in prime_tab:
    all_set.add(prime)
    sequence_set.add(prime)

    next_permutation = pmt.nextPermuteStr([int(i) for i in str(prime)])
    next_num = tmp_convert(next_permutation)

    while (not pmt.isEnd(next_permutation)):
        if next_num == prime or next_num in all_set:
            sequence_set.clear()
            break

        if next_num in prime_tab:
            sequence_set.add(next_num)
            all_set.add(next_num)

        next_permutation = pmt.nextPermuteStr(next_permutation)
        next_num = tmp_convert(next_permutation)

    if len(sequence_set) > 2:
Example #15
0
 def __init__(self, n, generator_set, base):
     self.n = n
     self.base = base
     self.stab_chain = [self.ChainSegment(n, generator_set, base[1]),
                        self.ChainSegment(n, [Permutation.identity(n)], base[2])]
Example #16
0
 def summary(self, scores=False):
     if self.individual:
         d = len(self.x[0]) if type(
             self.x[0]) in [np.array, np.ndarray, list] else 1
         for j in range(d):
             x_features = self.x[:, j] if d != 1 else self.x
             if self.xbin and self.x_bin != 0:  # x bins
                 x_freq = equal_freq(x_features, self.x_bin) \
                     if self.bin_type == 'freq' \
                     else equal_width(x_features, self.x_bin)
             else:
                 x_freq = x_features
             if self.ybin and self.y_bin != 0:  # y bins
                 y_freq = equal_freq(self.y, self.y_bin) \
                     if self.bin_type == 'freq' \
                     else equal_width(self.y, self.y_bin)
             else:
                 y_freq = self.y
             mi = fGain(x_freq, y_freq) if self.fraction else gain(
                 x_freq, y_freq)
             if self.permut:
                 permut = Permutation(x_freq, y_freq).summary()
                 permut = permut / entropy(
                     y_freq) if self.fraction else permut
                 mi -= permut
             self.mi_list.append((mi, str('X' + str(j))))
         self.mi_list.sort(reverse=True)
         if scores:
             self.indi_variables = [
                 (each[0], int(each[1][1:]))
                 for each in self.mi_list[:self.num_features]
             ]
         else:
             self.indi_variables = [
                 int(each[1][1:])
                 for each in self.mi_list[:self.num_features]
             ]
         return self.mi_list
     if self.interaction:
         all_interactions = list(
             itertools.combinations([_ for _ in range(len(self.x[0]))],
                                    self.x_bin))
         for cell in all_interactions:
             if self.xbin and self.x_bin != 0:
                 x_freq = equal_freq(self.x[:, cell], self.x_bin) \
                     if self.bin_type == 'freq' \
                     else equal_width(self.x[:, cell], self.x_bin)
             else:
                 x_freq = self.x[:, list(cell)]
             if self.ybin and self.y_bin != 0:
                 y_freq = equal_freq(self.y, self.y_bin) \
                     if self.bin_type == 'freq' \
                     else equal_freq(self.y, self.y_bin)
             else:
                 y_freq = self.y
             gains = 0
             for each in cell:
                 gains += fGain(self.x[:, each], y_freq)
             entro = fGain(x_freq, y_freq) - gains
             if self.x_bin and self.permut:
                 permut = Permutation(x_freq,
                                      y_freq).summary() / entropy(y_freq)
                 mi -= permut
             self.inter_list.append((entro, "-".join(list([str(each) for each in cell])))) \
                 if entro >= 0.05 \
                 else self.inter_list
         self.inter_list.sort(reverse=True)
         if scores:
             self.inter_variables = [
                 (each[0], [int(sub) for sub in each[1].split('-')])
                 for each in self.inter_list[:self.num_features]
             ]
         else:
             self.inter_variables = [[
                 int(sub) for sub in each[1].split('-')
             ] for each in self.inter_list[:self.num_features]]
     return self.indi_variables, self.inter_variables