예제 #1
0
def test_normal():
    assert permutations('ABC') == {'ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'}
    assert permutations("PEPE") == {
        "EEPP", "EPEP", "EPPE", "PEEP", "PEPE", "PPEE"
    }
    assert permutations("LMAO") == {
        "LMAO", "MLAO", "ALMO", "LAMO", "MALO", "AMLO", "OMLA", "MOLA", "LOMA",
        "OLMA", "MLOA", "LMOA", "LAOM", "ALOM", "OLAM", "LOAM", "AOLM", "OALM",
        "OAML", "AOML", "MOAL", "OMAL", "AMOL", "MAOL"
    }
def bruteForce(string):
  permuts = permutations(string)
  for p in permuts:
    if isPalindrome(p):
      return True

  return False
예제 #3
0
파일: 8.py 프로젝트: thran/the_code
 def find_mapping(self, digits):
     for permutation in permutations(list('abcdefg')):
         mapping = dict(zip('abcdefg', permutation))
         if all(
                 self.convert_digit(digit, mapping) in self.digits
                 for digit in digits):
             return mapping
예제 #4
0
파일: breeder.py 프로젝트: devssh/mopoken
 def advantageous_fight_order(breeder1, breeder2):
     breeder1_pokemon = breeder1.pokemon_list
     breeder2_pokemon = breeder2.pokemon_list
     sample_space = [list(zip(x, breeder2_pokemon)) for x in permutations(breeder1_pokemon, len(breeder1_pokemon))]
     outcomes = [len(["win" for duel in combination if duel[0].check_odds(duel[1]) == advantage_types[1]])
                 for combination in sample_space]
     wins = [sample_space[index] for index, outcome in enumerate(outcomes) if outcome >= min_wins_to_victory]
     return [duel[0] for duel in wins[0]] if len(wins) > 0 else breeder1.pokemon_list
def num_possible_rearrangements(grid):
    num = 0
    new_list = [x for x in grid]

    for perm in permutations([i for i in range(0, len(grid))]):
        new_list = apply_permutation(grid, new_list, perm)
        if is_magic(new_list):
            num += 1

    return num
예제 #6
0
    def test_permutations(self):
        self.assertEqual(permutations.permutations('HACK', '2'), '''AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH''')
예제 #7
0
def balanced(n):
    '''
    Given a positive number n, yield all strings of length n, in any order, that only contain balanced brackets. For example:
    >>> sorted(list(balanced(6)))
    ['((()))', '(()())', '(())()', '()(())', '()()()']
    '''
    if n % 2 != 0 or n < 0:
        raise ValueError(
            'the input number should be a positive double integer to be balanced'
        )
    string = ''
    for _ in range(n // 2):
        string += '('
    for _ in range(n // 2):
        string += ')'
    string = list(permutations(string))
    string = list(dict.fromkeys(string))  # remove duplicated string
    for bracket in string:
        if is_balanced(bracket):
            yield bracket
예제 #8
0
def test_single():
    assert list(permutations('a')) == ['a']
예제 #9
0
def test_single_permutation():
    assert sorted(list(permutations('A'))) == ['A']
예제 #10
0
def test_empty_string():
    assert list(permutations('')) == ['']
__licence__ = 'GNU Public Licence (GPL) v3'

import os.path
import sys

# FIXME: the different functions return different sequence structures.

if sys.argv[0] == 'words_iteration.py':
    from permutations import permutations_iteration as permutations
elif sys.argv[0] == 'words_comprehension.py':
    from permutations import permutations_comprehension as permutations
elif sys.argv[0] == 'words_comprehension_alt.py':
    from permutations import permutations_comprehension_alt as permutations
else:
    from permutations import permutations_generator as permutations

if __name__ == '__main__':
    argCount = len(sys.argv) - 1
    if argCount not in (1, 2):
        print('Usage: {} <string> [ <dictionary> ]'.format(
            os.path.basename(sys.argv[0])))
    else:
        wordListFileName = sys.argv[
            2] if argCount == 2 else '/usr/share/dict/words'
        with open(wordListFileName) as file:
            wordList = file.read().split()
            for trial in permutations(sys.argv[1]):
                putative = ''.join(trial)
                if putative in wordList:
                    print(putative)
예제 #12
0
 def test_permutations(self):
     self.assertTrue(permutations('act', 'cat'))
     self.assertFalse(permutations('', 'foo'))
     self.assertFalse(permutations('Nib', 'bin'))
     self.assertTrue(permutations('a ct', 'ca t'))
     self.assertTrue(permutations('', ''))
예제 #13
0
def test_repeat():
    assert sorted(list(
        permutations('ABB'))) == ['ABB', 'ABB', 'BAB', 'BAB', 'BBA', 'BBA']
예제 #14
0
192 x 1 = 192
192 x 2 = 384
192 x 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576.
We will call 192384576 the concatenated product of 192 and (1,2,3)

The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645,
which is the concatenated product of 9 and (1,2,3,4,5).

What is the largest 1 to 9 pandigital 9-digit number
that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?
"""

import permutations

allPermutations = set([permutations.combine_numbers(x) for x in permutations.permutations(range(1, 10))])
highestNumber = 0

for n in xrange(1, 10000):  # the was found experimentally
    pandigitalMultiply = 0

    for i in xrange(1, 10):
        pandigitalPart = n * i
        pandigitalMultiply *= (10 ** len(str(pandigitalPart)))
        pandigitalMultiply += pandigitalPart

        if len(str(pandigitalMultiply)) >= 9:
            break

    if pandigitalMultiply in allPermutations:
        if pandigitalMultiply > highestNumber:
예제 #15
0
def test_permutations():
    assert permutations("12") == ["12", "21"]
    assert permutations("123") == ['123', '132', '213', '231', '312', '321']
    assert permutations("ab ") == ['ab ', 'a b', 'ba ', 'b a', ' ab', ' ba']
예제 #16
0
 def test_case_b(self):
     string = 'aabb'
     self.assertEqual(permutations(string),
                      ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'])
예제 #17
0
 def test_permutations(self):
     self.assertEqual(sorted(["cba", "bca", "bac", "cab", "acb", "abc"]),
                      sorted(permutations("abc")))
예제 #18
0
 def test_permutations(self):
     self.assertEqual(list(permutations([1, 2, 3], 3)),
                      [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1),
                       (3, 1, 2), (3, 2, 1)])
예제 #19
0
def test_number_permutation():
    assert sorted(list(
        permutations('123'))) == ['123', '132', '213', '231', '312', '321']
예제 #20
0
def test_duplicate_permutation():
    assert sorted(list(
        permutations('ABB'))) == ['ABB', 'ABB', 'BAB', 'BAB', 'BBA', 'BBA']
예제 #21
0
def test_two_permutation():
    assert sorted(list(permutations('AB'))) == ['AB', 'BA']
예제 #22
0
def test_two():
    assert list(permutations('ab')) == ['ab', 'ba']
 def test_permutations(self):
     self.assertEqual(sorted(permutations('a')), ['a'])
     self.assertEqual(sorted(permutations('ab')), ['ab', 'ba'])
     self.assertEqual(sorted(permutations('aabb')),
                      ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'])
예제 #24
0
def test_ABC():
    assert list(
        permutations('ABC')) == ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
예제 #25
0
import itertools
from permutations import permutations
from primes import primes, is_prime

for p in primes():
    if p > 10**4:
        break

    found = []
    for perm in permutations(list(str(p))):
        n = int("".join(perm))
        if is_prime(n) and len(str(n)) == len(str(p)):
            found.append(n)

    found = list(set(found))

    for f in itertools.combinations(found, 3):
        f = list(f)
        f.sort()
        if f[1] - f[0] == f[2] - f[1]:
            print f
예제 #26
0
def test_all_same():
    assert list(
        permutations('AAA')) == ['AAA', 'AAA', 'AAA', 'AAA', 'AAA', 'AAA']
예제 #27
0
from permutations import permutations
from primes import is_prime

digits = list("7654321")

for p in permutations(digits):
    if is_prime(int("".join(p))):
        print "".join(p)
        exit()
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits
1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
The lexicographic permutations of 0, 1 and 2 are:

012   021   102   120   201   210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""

import permutations

print sorted(permutations.permutations(range(0, 10)))[1000 * 1000 - 1]
__version__ = '1.2'
__copyright__ = 'Copyright © 2007, 2012, 2014  Russel Winder'
__licence__ = 'GNU Public Licence (GPL) v3'

import os.path
import sys

# FIXME: the different functions return different sequence structures.

if sys.argv[0] == 'words_iteration.py':
    from permutations import permutations_iteration as permutations
elif sys.argv[0] == 'words_comprehension.py':
    from permutations import permutations_comprehension as permutations
elif sys.argv[0] == 'words_comprehension_alt.py':
    from permutations import permutations_comprehension_alt as permutations
else:
    from permutations import permutations_generator as permutations

if __name__ == '__main__':
    argCount = len(sys.argv) - 1
    if argCount not in (1, 2):
        print('Usage: {} <string> [ <dictionary> ]'.format(os.path.basename(sys.argv[0])))
    else:
        wordListFileName = sys.argv[2] if argCount == 2 else '/usr/share/dict/words'
        with open(wordListFileName) as file:
            wordList = file.read().split()
            for trial in permutations(sys.argv[1]):
                putative = ''.join(trial)
                if putative in wordList:
                    print(putative)
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:

- d2 d3 d4  = 406 is divisible by 2
- d3 d4 d5  = 063 is divisible by 3
- d4 d5 d6  = 635 is divisible by 5
- d5 d6 d7  = 357 is divisible by 7
- d6 d7 d8  = 572 is divisible by 11
- d7 d8 d9  = 728 is divisible by 13
- d8 d9 d10 = 289 is divisible by 17

Find the sum of all 0 to 9 pandigital numbers with this property.
"""

import permutations

allPermutations = permutations.permutations(range(0, 10))
divisibleBy = [2, 3, 5, 7, 11, 13, 17]
sumOfPermutations = 0


def is_special_number(numbers):
    i = 1
    for d in divisibleBy:
        if permutations.combine_numbers(numbers[i : (i + 3)]) % d != 0:
            return False
        i += 1
    return True


for perm in allPermutations:
    if is_special_number(perm):
예제 #31
0
def subpermutations(seq, K):
    return sorted(sum([list(permutations.permutations(s)) for s in subsets(seq, K)], []))
예제 #32
0
 def test_case_a(self):
     string = 'ab'
     self.assertEqual(permutations(string), ['ab', 'ba'])
예제 #33
0
def test_empty_permutation():
    assert sorted(list(permutations(''))) == []
예제 #34
0
import primes
import permutations

primesToCheck = primes.create_primes(sqrt(987654321))
primeFound = False


def is_prime(number):
    limit = sqrt(number)
    for p in primesToCheck:
        if p > limit:
            return True
        elif number % p == 0:
            return False

    return True


for x in xrange(10, 1, -1):
    allPermutations = permutations.permutations(range(1, x))

    for perm in sorted([permutations.combine_numbers(y) for y in allPermutations], reverse=True):
        if is_prime(perm):
            print str(perm)
            primeFound = True
            break

    if primeFound:
        break
예제 #35
0
def test_example1():
    assert sorted(list(
        permutations('ABC'))) == ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
예제 #36
0
i = 0
positions = {}
while find_pos(i, map):
    positions[i] = (find_pos(i, map))
    i += 1

distances = {}
for n, p in positions.items():
    for n2, p2 in positions.items():
        if n < n2:
            distances[(n2, n)] = distances[(n, n2)] = distance(map, p, p2)

for n in positions.keys():
    for n2 in positions.keys():
        print('{:>3} '.format(distances[(n, n2)] if n != n2 else 0), end='')
    print()

to_visit = list(positions.keys())
to_visit.remove(0)

dists = []
for path in permutations.permutations(to_visit):
    current = 0
    d = 0
    for next in path + [0]:
        d += distances[(current, next)]
        current = next
    dists.append(d)

print(min(dists))
예제 #37
0
def test_example2():
    assert sorted(list(
        permutations('ABB'))) == ['ABB', 'ABB', 'BAB', 'BAB', 'BBA', 'BBA']
예제 #38
0
def test_property(n):
    prime_factors = list(permutations(n))
    for string in prime_factors:
        assert len(string) == len(n)
예제 #39
0
for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 x 186 = 7254,
containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
"""

import permutations

foundProducts = {}
foundProductsSum = 0

for perm in permutations.permutations(range(1, 10)):
    product = permutations.combine_numbers(perm[-4:])  # last four digits

    for x in xrange(1, 4):
        factor1 = perm[:x]  # first x digit
        factor2 = perm[x:-4]  # starting from x'th digit + 1 (0-based index) all except the last four

        factor1 = permutations.combine_numbers(factor1)
        factor2 = permutations.combine_numbers(factor2)

        if factor1 * factor2 == product:
            if product not in foundProducts:
                foundProductsSum += product
                foundProducts[product] = 1
            #print str(factor1) + " x " + str(factor2) + " = " + str(product)