コード例 #1
0
def logic_puzzle():
    "Return a list of the names of the people, in the order they arrive."
    Monday, Tuesday, Wednesday, Thursday, Friday = 0, 1, 2, 3, 4
    days = list(perm(range(5)))
    # compute puzzle
    (Hamming, Knuth, Minsky, Simon, Wilkes) = next((Hamming, Knuth, Minsky, Simon, Wilkes)
        for (Hamming, Knuth, Minsky, Simon, Wilkes) in days
        for (programmer, designer, writer, manager, _) in days
        for (droid, tablet, iphone, laptop, _) in days
        if laptop == Wednesday #1
        if Wilkes != programmer #2
        if (programmer, droid) in perm([Wilkes, Hamming]) #3
        if writer != Minsky #4
        if Knuth != manager and tablet != manager #5
        if Knuth == Simon + 1 #6 
        if designer != Thursday #7
        if Friday != tablet #8
        if designer != droid #9
        if Knuth == manager + 1 #10
        if (laptop, Wilkes) in perm ([Monday, writer]) #11
        if iphone == Tuesday or tablet == Tuesday #12
        )
    # humanize solution
    result = [''] * 5
    result[Hamming] = 'Hamming'
    result[Knuth] = 'Knuth'
    result[Minsky] = 'Minsky'
    result[Simon] = 'Simon'
    result[Wilkes] = 'Wilkes'
    return result
コード例 #2
0
 def logic_matrix_init(self):
     n = self.dimension - 1
     self.mat = [[[] for i in range(self.dimension)]
                 for i in range(self.dimension**2)]
     coords = (0, n, -n)
     print(list(perm(coords, 3)))
     coords = (0, 0, -n)
     print(list(set(perm(coords, 3))))
     coords = (0, 0, n)
     print(list(set(perm(coords, 3))))
コード例 #3
0
ファイル: factorial.py プロジェクト: rajthilakm/Python
def printSequence(seq,fact):
    l=[]
#    for j in range(0,fact):
#        l=[]
#        for i in seq:
#            l.append(i)
#            l=l[0:i]+l[i:0]
#        print l    
    
    perm(seq)
    print (perm(seq))
コード例 #4
0
def get_qualifier_functions(data):
    """Loops through a list of qualifiers, initializing them
    and returning a list of qualifier functions that can be applied on
    any 'well formed' data.
    """
    #  append qualifier for each aspect and return list
    qualifier_function_list = []

    # 1. rcc8
    qualifier_function_list.append((qualify_rcc8, None))

    # 2. rcc11
    qualifier_function_list.append((qualify_rcc11, None))

    # 3. RegionStarVars
    fargs = {'num_sectors': 4}
    regstarvars_ref_objects = filter(data, type_list=['mountain'])
    regstarvars_ref_pairs = grp(perm(regstarvars_ref_objects, 2),
                                key=lambda x: x[0])
    fargs['reference_pair_groups'] = regstarvars_ref_pairs
    qualifier_function_list.append((qualify_relative_direction, fargs))

    # 4. relative distance
    qualifier_function_list.append((qualify_relative_distance, None))

    # 5. left-right relations
    qualifier_function_list.append((qualify_left_right, None))

    # 6. adjacency
    qualifier_function_list.append((qualify_adjacency, None))

    return qualifier_function_list
コード例 #5
0
def order_anchors(points):  #orders anchor points into config with largest area
    #duplicate point 0 and add to the end of the list
    #[p0,p1,p2,...pn,p0]
    points.append(points[0])
    #permutate points p1 to pn
    middle = points[1:-1]
    perms = list(perm(middle))
    (area, largest, sequence) = (0, 0, 0)
    for order in perms:
        #re-add point 0 to start and end
        ls = [points[0]]
        ls += order
        ls += [points[0]]
        #print ls
        boundary = []
        for pt in ls:
            boundary.append((pt.real, pt.imag))
        perm_area = shoelace_formula(boundary, absoluteValue=False)
        #print perm_area
        #print '\n'
        if perm_area > area:
            area = perm_area
            largest = perm_area
            sequence = ls
    sequence.pop(-1)
    return (sequence, largest)
コード例 #6
0
 def game_state_check(self, player_obj):
     length = len(player_obj.choices)
     if length >= 3:
         for comb in self.__combination:
             choice_comb = perm(player_obj.choices, 3)
             if comb in choice_comb:
                 player_obj.win = True
コード例 #7
0
def find_prime_pan(n_digits):
    for num in reversed([list_to_num(lst) for lst in perm(range(1,n_digits+1))]):
        if num % 10 in [0,2,4,5,6,8]:
            continue
        if is_prime(num):
            return num
    return -1
コード例 #8
0
def largest_number(A):
    A = list(A)
    A.sort(key=str, reverse=True)
    largest, equals, k = '', [], 0

    while k < len(A):
        current = str(A[k])

        if k + 1 < len(A):
            next = str(A[k + 1])

            if current[0] == next[0]:
                equals.append(current)
            else:
                largest += current

        elif equals:
            prev = str(A[k - 1])
            if prev[0] == current[0]:
                equals.append(current)

            equals = [e for e in perm(equals, len(equals))]
            biggest = ''
            for tup in equals:
                combination = ''.join(tup)
                if combination > biggest:
                    biggest = combination
            largest += biggest
            equals = []

        else:
            largest += current

        k += 1
    return largest
コード例 #9
0
def get_meshblocks(n_X, n_cpus):
    def divisors(n):
        divs = [1]
        for i in range(2, int(np.sqrt(n)) + 1):
            if n % i == 0:
                divs.extend([i, n // i])
        divs.extend([n])
        return np.sort(np.array(list(set(divs))))[::-1]

    def get_divs(n_points, n_dir, mesh, min_divs=10):
        if n_dir == 1:
            return [1], n_points
        n = n_points // mesh
        divs = divisors(n)
        return divs[(min_divs <= divs) & (divs <= n_dir) &
                    (n_dir % divs == 0)], n

    possible, sa_to_v = [], []
    nx, ny, nz = n_X
    MX, n = get_divs(np.prod(n_X), nx, n_cpus, min_divs=(nx // 10))
    for mx in MX:
        MY, n2 = get_divs(n, ny, mx)
        for my in MY:
            MZ = get_divs(n2, nz, my)[0]
            for mz in MZ:
                tup = (mx, my, mz)
                perm_in_poss = any([p in possible for p in list(perm(tup))])
                if (np.prod(n_X) /
                    (mx * my * mz) == n_cpus) and not perm_in_poss:
                    possible.append(tup)
                    sa_to_v.append(2 * (mx * my + my * mz + mz * mx) /
                                   (mx * my * mz))
    temp, meshblocks = zip(*sorted(zip(sa_to_v, possible)))
    meshblocks = np.array(meshblocks)
    return meshblocks
コード例 #10
0
ファイル: pandigital.py プロジェクト: 098799/project_euler
def giveme(howmany, which):
    i = howmany + 1
    j = which - 1
    stringu = ""
    for k in range(howmany):
        stringu += str(list(perm(range(1, i)))[j][k])
    return stringu
コード例 #11
0
ファイル: p043.py プロジェクト: yehnan/project_euler_python
def ssd():
    result = 0
    for np in perm('0134'):
        if np[0] == '0':
            continue
        ns = ''.join(np) + '952867'
        if is_ssd(ns):
            result += int(ns)
    for np in perm('0146'):
        if np[0] == '0':
            continue
        ns = ''.join(np) + '357289'
        if is_ssd(ns):
            result += int(ns)

    return result
コード例 #12
0
ファイル: euler41_50.py プロジェクト: poifra/euler
def prob43():
    #pandigital number with some property
    #dat 1 liner tho, splitted for readability
    from itertools import permutations as perm
    subset = [x for x in ["".join(y) for y in perm('0123456789') if y[0] != '0'] 
        if int(x[1] + x[2] + x[3]) % 2 == 0 and int(x[2] + x[3] + x[4]) % 3 == 0 and int(x[3] + x[4] + x[5]) % 5 == 0 and int(x[4] + x[5] + x[6]) % 7 == 0 and int(x[5] + x[6] + x[7]) % 11 == 0 and int(x[6] + x[7] + x[8]) % 13 == 0 and int(x[7] + x[8] + x[9]) % 17 == 0]
    return sum(map(int,subset))
コード例 #13
0
def solution(k, dungeons):
    # 가능한 순서 -- 첫번째의 최소 필요 피로도는 무조건 k(현재 피로도) 이상이어야함
    dungeons.sort(reverse=True)
    n = len(dungeons)
    cycle = math.factorial(n) // n
    base = 0

    for i in range(n):
        if dungeons[i][0] < k:
            break
        base = i

    nums = [i for i in range(n)]
    perms = list(perm(nums))[:cycle * (base + 2)]
    max_cnt = 0
    for p in perms:
        cnt, cur = 0, k
        for i in p:
            if cur < dungeons[i][0]:
                break
            cnt += 1
            cur -= dungeons[i][1]
        max_cnt = max(max_cnt, cnt)

    return max_cnt
コード例 #14
0
def sameInverse(n):
    Ps = list(perm([i for i in range(1, n + 1)], n))
    #print(Ps)
    same = 0
    for i in Ps:
        if list(i) == inverse(i):
            same += 1
    return same
コード例 #15
0
ファイル: Ch1-Projects.py プロジェクト: jgreenwd/Python
def p1_29():
    from itertools import permutations as perm
    test_string = ['c','a','t','d','o','g']

    print('All permuations of the letters in "catdog": \n')

    for x in perm(test_string, 6):
        print(x)
コード例 #16
0
def sum_target(nums, target):
    a = perm(nums, 2)
    while True:
        x, y = next(a)
        print(x,y)
        if x + y == target:
            return x, y
    return False
コード例 #17
0
def seats(ls, c, r):
    seats = []
    for x, y in set(perm([-1, -1, 1, 1, 0, 0], 2)) - set([(0, 0)]):
        x = r + x
        y = c + y
        if 0 <= x < w and 0 <= y < len(ls):
            seats.append(ls[y][x])
    return seats
コード例 #18
0
def find_link(elem,chips,hexa,hexas):
    if len(hexa) == 6 and hexa[0][0] == hexa[-1][-1] and hexa not in hexas:
        hexas.append(hexa)
    for i,chip in enumerate(chips):
        for perms in perm(chip):
            if elem[2] == perms[0]:
                temp_hexa = copy.deepcopy(hexa) + [perms]
                find_link(perms,chips[:i]+chips[i+1:],temp_hexa,hexas)
コード例 #19
0
 def __init__(self):
     self._circle = [0,1,2,5,8,7,6,3,0,1]
     self._cross = [(0,4,8),(1,4,7),(2,4,6),(3,4,5)]
     self._scores = {board:0.0 for board in perm('pppccc---',9)}
     self._player_boards = {}
     self._comp_boards = {}
     self.initialize_scores()
     self.inititialize_comp_boards()
コード例 #20
0
 def edit_distance_one(word):
     for i in range(len(word)):
         left, c, right = word[0:i], word[i], word[i + 1:]
         j = lookup[c]  # lowercase.index(c)
         for cc in lowercase[j + 1:]:
             for ccc in perm(left + cc + right):
                 s = ''
                 yield s.join(ccc)
コード例 #21
0
def permute():
    data = input('Enter elements seperated by comma to permute: ').split(',')
    a = set()
    for i in perm(data):
        if i not in a:
            a.add(i)
    return '{} permutations found\n'.format(len(a)) + '\n'.join(
        map(lambda x: str(x), a))
コード例 #22
0
ファイル: anneal.py プロジェクト: tscott8/cs306
def gen_perms(code):
    fout = open('perms.txt', 'w')
    perms = perm(code)
    for i, p in enumerate(perms):
        if i > 10000:
            break
        print(''.join(p), end='\n', file=fout)
    fout.close()
コード例 #23
0
def permutations(string):
    perm_list = []
    permutation = perm(string)
    for i in list(permutation):
        k = ''.join(i)
        if not k in perm_list:
            perm_list.append(k)
    return perm_list
コード例 #24
0
def permutations(_list):
    gen = perm(_list)
    while True:
        try:
            aux = gen.next()
            print "%s" % listToString(aux)
        except StopIteration:
            break
コード例 #25
0
 def isCNF(self):
     pp = set([''.join(x) for x in perm(self.var, 2)])
     for p in self.prod.values():
         for q in p:
             if not q in self.term and not q in pp:
                 return False
             if q == '':
                 return False
     return True
コード例 #26
0
def solution(user_id, banned_id):
    answer = []

    for perm_g in perm(user_id, len(banned_id)):
        if check(perm_g, banned_id):
            if sorted(perm_g) not in answer:
                answer.append(sorted(perm_g))

    return len(answer)
コード例 #27
0
ファイル: p043.py プロジェクト: yehnan/project_euler_python
def ssd_bf():
    result = 0
    for np in perm('0123456789'):
        if np[0] == '0':
            continue
        ns = ''.join(np)
        if is_ssd(ns):
            result += int(ns)
    return result
コード例 #28
0
ファイル: day9.py プロジェクト: poifra/adventOfCode
def hamPath(pairs, mode):
	'''
	returns shortest or longest hamiltonian path in non-oriented graph given by pairs
	'''
	allDist = []

	for x in perm(pairs):
		allDist.append(sum(pairs[x[i]][x[i+1]] for i in range(len(x) - 1)))
	return min(allDist) if mode == 'min' else max(allDist)
コード例 #29
0
 def _get_all_combinations(self, from_smaller=False, join=False):
     result = []
     for l in range(1, len(self.letters)+1):
         for subset in comb(self.letters, l if from_smaller else (len(self.letters) - l)):
             for each_possible in perm(subset):
                 if join:
                     yield ''.join(each_possible)
                 else:
                     yield each_possible
コード例 #30
0
ファイル: main.py プロジェクト: starlegendary/FP-Python
def seq(n, i):
    if i == 0: return ['0' * (2 * n)]
    result = seq(n, i - 1)
    rest = []
    part = list(map("".join, set(perm('1' * i + '0' * (n - i), n))))
    for x in part:
        rest += list(map(lambda y: x + y, part))

    return result + rest
コード例 #31
0
ファイル: main.py プロジェクト: starlegendary/FP-Python
    def inner(s):
        if '1' not in s: return [s]
        result = inner('0' + s[:-1])
        rest = []
        part = list(map("".join, set(perm(s, len(s)))))
        for x in part:
            rest += list(map(lambda y: x + y, part))

        return result + rest
コード例 #32
0
ファイル: day_7.py プロジェクト: Dragon-God/AdventOfCode
def amplify(init, program, num):
    machine = StateMachine(operators, program)
    for tpl in perm(range(num)):
        output = init
        for signal in tpl:
            machine.send(signal, output)
            output = next(machine.run())
            machine.reset()
        yield output
コード例 #33
0
ファイル: prob093.py プロジェクト: mercurium/proj_euler
def slow_test(digs):
  valids = set([])
  for g in perm(digs): #g for group of nums
    for a in xrange(4):
      for b in xrange(4):
        for c in xrange(4):
          val = ops[c](ops[b](ops[a](g[0],g[1]),g[2]),g[3])
          if val % 1 <= 0.1:
            valids.add(int(abs(val)))
  return valids
コード例 #34
0
def pd():
    result = set()
    answers = set()
    for i in ds:  # 1 4 4
        for jli in perm(ds[:int(i)] + ds[int(i) + 1:], 4):
            j = ''.join(jli)
            k = str(int(i) * int(j))
            if len(k) == 4 and is_pandigital(i + j + k):
                result.add((i, j, k))
                answers.add(int(k))
    for ili in perm(ds, 2):  # 2 3 4
        for jli in perm(''.join(set(ds) - set(ili)), 3):
            i = ''.join(ili)
            j = ''.join(jli)
            k = str(int(i) * int(j))
            if len(k) == 4 and is_pandigital(i + j + k):
                result.add((i, j, k))
                answers.add(int(k))
    return sum(answers)
コード例 #35
0
ファイル: p032.py プロジェクト: stephensemilla/project-euler
def specials(a_size):
    
    special = []
    for a in perm(digits, a_size):
        
        left = '123456789'
        for d in a: left = left.replace(d, '')
            
        a = int(''.join(a))
    
        for p in perm(left, 5 - a_size):
            b = int(''.join(p))
            product = str(a) + str(b) + str(a*b)

            if b < (9876 / a) and\
               ''.join(sorted(product)) == '123456789':
                special.append(a*b)
                
    return special
コード例 #36
0
ファイル: p041.py プロジェクト: yehnan/project_euler_python
def pp():
    n_max = 0
    dcheck = [4, 7]
    for d in dcheck:
        ds = '123456789'[:d]
        for nst in perm(ds):
            n = int(''.join(nst))
            if is_prime(n) and n > n_max:
                n_max = n
    return n_max
コード例 #37
0
ファイル: permutations.py プロジェクト: julzhk/codekata
def permutations(s):
    """
>permutations('aab')
{'aab', 'aba', 'baa'}
>permutations('aaba')
{'aaab', 'aaba', 'abaa', 'baaa'}
>permutations('abc')
{'abc', 'acb', 'bac', 'bca', 'cab', 'cba'}
    :param s: string
    :return: set of permutations
    """
    r = perm(s)
    return set([''.join(i) for i in r])
コード例 #38
0
def problem49():
    primes=ero_sieve(9999)
    for i in set(primes):
        if i<1001:
            primes.discard(i)
    for i in set(primes):
        permutations=set(int(''.join(j)) for j in perm(str(i)) if int(''.join(j)) in primes)
        if len(permutations)>=3:
            permutations=list(permutations)
            permutations.sort()
            for k in xrange(len(permutations)-2):
                if permutations[k+2]-permutations[k+1]==permutations[k+1]-permutations[k]:
                    return str(permutations[k])+str(permutations[k+1])+str(permutations[k+2])
コード例 #39
0
ファイル: euler41_50.py プロジェクト: poifra/euler
def prob43():
    #pandigital number with some property
    #dat 1 liner tho, splitted for readability
    from itertools import permutations as perm
    subset = [x for x in ["".join(y) for y in perm('0123456789') if y[0] != '0'] 
        if int(x[1]+x[2]+x[3])%2==0 
            and int(x[2]+x[3]+x[4])%3==0 
            and int(x[3]+x[4]+x[5])%5==0 
            and int(x[4]+x[5]+x[6])%7==0 
            and int(x[5]+x[6]+x[7])%11==0 
            and int(x[6]+x[7]+x[8])%13==0 
            and int(x[7]+x[8]+x[9])%17==0]
    return sum(map(int,subset))
コード例 #40
0
def sort(fileName):
    for line in open(fileName, 'r'):
        n = len(line.strip())
        limit = factorial(n)
        digits = sorted((char for char in line if char.isdigit()))
        alphaUpper = sorted((char for char in line if char.isupper()))
        alphaLower = sorted((char for char in line if char.islower()))

        for i, seq in enumerate(perm(digits + alphaUpper + alphaLower)):
            print("".join(seq), end="")
            if i < limit-1:
                print(",", end="")
            else:
                print()
コード例 #41
0
ファイル: water.py プロジェクト: opentan8/water-Capacity
def puring(pure):
    for src, dest in perm(ITER, 2):
        if src in LIMIT:
            continue
        num = min(pure[src], BOTTLES[dest] - pure[dest])
        if num == 0:
            continue
        pure_copy = pure[:]
        pure_copy[src] -= num
        pure_copy[dest] += num
        if pure_copy in CURR:
            ind = DUMP.index(pure_copy)
        elif pure_copy not in DUMP:
            ind = len(DUMP)
            DUMP.append(pure_copy)
        else:
            continue
        yield [src, dest, ind]
コード例 #42
0
def solve(n):
    answer = 0
    visited = set()
    start = n // 3 + 1
    for pi in perm(range(1, n + 1)):
        for i in range(start, min(2 * start, n - 1)):
            m = int(reduce(lambda x, y: str(x) + str(y), pi[:i]))
            if m in visited:
                continue
            elif i > n - i:
                break
            for j in range(i + 1, n):
                a = int(reduce(lambda x, y: str(x) + str(y), pi[i:j]))
                b = int(reduce(lambda x, y: str(x) + str(y), pi[j:]))
                if a * b in visited:
                    continue
                if m == a * b:
                    visited.add(m)
                    answer += m
    return answer
コード例 #43
0
def object_list(objects):
	"""
	Return the shortest Hamiltonian path through a collection of objects.

	This is calculated using a brute force method that is certainly not
	intented for real life use because for example going from ten to
	eleven objects will increase the running time elevenfold and even
	with caching expensive distance calculations this quickly becomes
	completely unworkable.

	But this routine is intended as our baseline algorithm that is meant
	to be replaced with an approximation algorithm that is 'good enough'
	for our purposes.
	"""
	@lru_cache()
	def distance_squared(a,b):
		return (objects[a].location-objects[b].location).length_squared

	def length_squared(chain):
		sum = 0.0
		for i in range(len(chain)-1):
			sum += distance_squared(chain[i],chain[i+1])
		return sum

	s = time()

	shortest_d2 = 1e30
	shortest_chain = None

	n_half = fac(len(objects))//2
	for i,chain in enumerate(perm(range(len(objects)))):
		if i >= n_half:
			break
		d2 = length_squared(chain)
		if d2 < shortest_d2:
			shortest_d2 = d2
			shortest_chain = chain

	print("{n:d} objects {t:.1f}s".format(t=time()-s, n=len(objects)))

	return [objects[i] for i in shortest_chain]
コード例 #44
0
ファイル: nbc.py プロジェクト: brianolsen87/Purdue-Projects
    def ruleGeneration(self, freqDict, itemSet = []):
        for val in freqDict:
            newSet = itemSet + [val]
            if self.level==len(newSet) and self.level > 1:
                for r in perm(newSet):
                    ruleCount = self.getFreq(r)
                    anetecedentCount = self.getFreq(r[0:len(r) - 1])

                    if not self.chiSquare:
                        conf = self.scoreRule(ruleCount,anetecedentCount)
                        if conf > 0:
                            support = ruleCount / self.N
                            self.R = self.R + [(conf, r, support)]
                    else:
                        self.chiCount +=1
                        (score, promise) = self.chiScoreCandidate(ruleCount,anetecedentCount,self.getFreq(r[len(r) - 1]))

                        if promise <= self.significance:
                            support = ruleCount / self.N
                            self.R = self.R + [(score, r, support, promise)]

            elif freqDict[val] is not None:
                self.ruleGeneration(freqDict[val], newSet)
コード例 #45
0
ファイル: p68.py プロジェクト: jctank/Euler
    return mat


def is_gon(gon):
    s = sum(gon[0])
    for i in range(1, 5):
        if sum(gon[i]) != s:
            return False
    return True


result = 0
result_p = None
result_g = None
gen = perm(range(1, 11))
for p in gen:
    if 10 not in p[:5]:
        # make sure 16-digit
        continue
    g = transform(p)
    if is_gon(g):
        r = ''
        for i in range(5):
            for j in range(3):
                r += str(g[i][j])
        assert len(r) == 16
        if int(r) > result:
            result = int(r)
            result_p = p
            result_g = g
コード例 #46
0
ファイル: p216.py プロジェクト: Tsunamicom/ProgChallenges
def network_distances():
    """For each set of coordinates, calculate and store the distances between all coordinates.

    Requires input for networks.
    Ex: networks = [[(1, 2), (3, 4), (4, 2)],[(7, 15), (22, 15), (5, 5)]]
    Ex2: networks = [[A, B, C]]

    variation = each element in the permutations of each network
    Ex: (ABC, ACB, BAC, BCA, CAB, CBA)

    subvar = each element in the unique combinations of each variation
    Ex for ABC in variation: (AB, BC, AC)

    subvar_set = a set of two sets of coordinates within each permutation set
    As long as the step is not greater than the length of each permutation
    Ex for ABC in variation: (variation[0], variation[1]) = (A, B)

    subvar_setdist = calculated length between two coordinates
    Ex for (A, B) in subvar_set:  calculate distance between A and B

    Store each set in a list for iteration
    Store each distance of the permutation set to find shortest (best_dist)

    """

    for locations in networks:
        best_dist = 999999999999
        best = list()
        for variation in perm(locations):    # Find all permutations of locations
            if variation in master:
                distance = master[variation]    # Get distance from memo
            else:
                distance = 0
                step = 0
                for subvar in comb(variation, 2):    # Check each unique comb of each perm
                    if not step+1 >= len(variation):    # Check for end of permutation list
                        subvar_set = (variation[step], variation[step+1])
                        if subvar_set in master:
                            subvar_setdist = master[subvar_set]
                        else:
                            subvar_setdist = con_length(subvar_set)
                            master[subvar_set] = subvar_setdist        # Store for memo
                            master[subvar_set[::-1]] = subvar_setdist  # Store reverse for memo

                        step += 1
                        distance += subvar_setdist

                master[distance] = variation          # Store distance for later lookup
                master[variation] = distance          # Store for memo
                master[variation[::-1]] = distance    # Store reverse for memo

            if best_dist >= distance:
                best_dist = distance


        # For each network, store the best connection sets in the network list for print iteration
        substep = 0
        for connections in master[best_dist]:

            if not substep+1 >= len(master[best_dist]):
                connection_step = (master[best_dist][substep], master[best_dist][substep+1])
                best.append([connection_step[0], connection_step[1], master[connection_step]])
                substep += 1

        network_list.append(best)
コード例 #47
0
ファイル: rot.py プロジェクト: jokoon/eio
def perm_n(ar, n):
    for i,a in enumerate(perm(ar)):
        if i == n: return a
コード例 #48
0
ファイル: detect.py プロジェクト: Auzzy/school
def detect_binary_const_funcs(section):
	return detect_const_funcs(section,perm(vars,2),funcs["binary"]["const"])
コード例 #49
0
ファイル: detect.py プロジェクト: Auzzy/school
def detect_unary_const_funcs(section):
	return detect_const_funcs(section,perm(vars,1),funcs["unary"]["const"])
コード例 #50
0
ファイル: detect.py プロジェクト: Auzzy/school
def detect_binary_funcs(section):
	return detect_var_funcs(section,perm(vars,3),funcs["binary"]["var"])
コード例 #51
0
ファイル: detect.py プロジェクト: Auzzy/school
def detect_unary_funcs(section):
	return detect_var_funcs(section,perm(vars,2),funcs["unary"]["var"])
コード例 #52
0
def P(i):
    i = str(i)
    list = [int(''.join(c for c in i)) for i in perm(i)]
    return list
コード例 #53
0
ファイル: p32.py プロジェクト: jctank/Euler
#!/usr/bin/env pypy

from itertools import permutations as perm


def get_num(lis):
    sum = 0
    num = len(lis)
    for i in range(num):
        sum += lis[i] * (10 ** (num - i - 1))
    return sum

results = set()

gen = perm(range(1, 10))
for tup in gen:
    for len1 in range(1, 5):
        x1 = get_num(tup[: len1])
        for len2 in range(1, 5):
            x2 = get_num(tup[len1: len1 + len2])
            x3 = get_num(tup[len1 + len2:])
            if x1 * x2 == x3:
                results.add(x3)
print results
print sum(results)
コード例 #54
0
ファイル: euler24.py プロジェクト: jokoon/eio
from itertools import permutations as perm

for i,a in enumerate(perm('0123456789')):
    if i == 1000000-1:
        print(''.join(a))
    if i == 1000000:
        print(''.join(a))
コード例 #55
0
ファイル: advent9.py プロジェクト: fnuttplus/advent
("Snowdin", "Straylight", 101),
("Snowdin", "AlphaCentauri", 84),
("Snowdin", "Arbre", 96),
("Straylight", "AlphaCentauri", 107),
("Straylight", "Arbre", 14),
("AlphaCentauri", "Arbre", 46)]

towns = ["Faerun", "Tristram", "Tambi", "Norrath", "Snowdin", "Straylight", "AlphaCentauri", "Arbre"]

def getdist(town1, town2):
	for d in dist:
		if (d[0] == town1 and d[1] == town2) or (d[1] == town1 and d[0] == town2):
			return d[2]

maxd = 0
#brute force 40320 permutations
for p in perm(range(8),8):
	d = 0
	town1 = p[0]
	for town2 in p[1:]:
		d += getdist(towns[town1], towns[town2])
		town1 = town2
	if d > maxd:
		for town in p:
			print(towns[town], end=" -> ")
		maxd = d
		print(d)

print(maxd)

コード例 #56
0
ファイル: permutations2.py プロジェクト: NaomiRison/Leetcode
def permutations(string):
    from itertools import permutations as perm
    return set(map(lambda x: "".join(x), perm(string)))
コード例 #57
0
# -(0)
from pprint import pprint
from itertools import permutations as perm

a = ['a', 'b', 'c']

b = list(perm(a))
pprint(b)

# -(/0)
# -(1)
c = [''.join(p) for p in perm(a)]
print(c)

# -(/1)
# -(2)
d = [''.join(p) for p in perm(a, 2)]
print(d)

# -(/2)
コード例 #58
0
	print "FAILED first place method."

T = int(raw_input())

for _ in xrange(T) :
	N = int(raw_input())
	mat = [0]*N
	S1 = set(xrange(1,N+1))
#	print "S1 = " , S1
	for _i_ in xrange(N) :
		mat[_i_] = map(int,raw_input().split())
	print "\n".join(map(str,mat))
	ans = []
	if N > 6 :
		counts = Counter([mat[i][0] for i in xrange(N)])
		print "Counts = " , counts
		firstPlaceNumber = findFirst(N,counts)
		continue	#TODO
	if len(ans) > 0 : continue
	for arr in perm(mat) :
		ans = getPossList(arr[0],1)
		for i in xrange(1,N) :
			ans = ans.intersection(getPossList(arr[i],i+1))
#			print ans
			if len(ans) == 0 :
				break
		if len(ans) > 0 :
			print " ".join(map(str,list(ans)[0]))
			break

コード例 #59
0
ファイル: prob043.py プロジェクト: mercurium/proj_euler
import time
START = time.time()
from itertools import permutations as perm
import string

lst = perm(['1','2','3','4','5','6','7','8','9','0'],10)
solution_set = set()

for next_num in lst:
    n = string.join(next_num, '') #1-3,2-5,3-6,4-7,5-8
    # Sadly, this many checks seems a bit primitive to me, but I'm not instantly seeing how to fix this...
    if n[5] in '05' and n[3] in '02468' and int(n[2:5])%3 == 0 and int(n[4:7])%7 ==0 and int(n[5:8])%11==0 and int(n[6:9])%13 == 0 and int(n[7:10])%17 == 0:
        solution_set.add(int(n))
print sum(solution_set)
print solution_set
print "Time taken:",time.time() -START


#we check in the order of numbers with dig 456 divisible by 5 first since it eliminates 80% of the numbers. We can also check it based on the last digit and without wasting time converting it to an int.

#by not converting "n[5] in '05' " to "int(n[5])%5 == 0", we shave the running time from 6.17 seconds to 3.77
#doing the same for "n[3] in '02468' " vs "int(n[3])%2 == 0, we go from 4.424 to 3.772, saving us .652 seconds, or cutting running time down by 14.7% 
コード例 #60
0
ファイル: permutations.py プロジェクト: the-zebulan/CodeWars
def permutations(strng):
    return set(''.join(a) for a in perm(strng))