Пример #1
0
def main():
    n = input()
    moves = set(P([add, sub] * 2, 2))
    for i in range(1, n):
        x = []
        for j in range(1, n):
            x.append(bfs(gen_board(i, j, n, set(P([add, sub] * 2, 2))), n))
        print " ".join(map(str, x))
Пример #2
0
    def __init__(self, imgs_path, pose_path, idx_path, transform, img_loader,
                 pose_loader):
        # train/test index
        lines = open(idx_path, 'r').readlines()
        idx = [int(line.split()[0]) for line in lines]

        classes = idx
        classes.sort()
        class_to_idx = {classes[i]: i for i in range(len(classes))}

        # images
        images = os.listdir(imgs_path)
        poses = os.listdir(pose_path)
        images = [
            im for im in images
            if int(im.split('_')[0]) in idx and im[:-3] + 'npy' in poses
        ]

        # pairs
        data = []
        for i in idx:  # i being the class
            tmp = [j for j in images if int(j.split('_')[0]) == i]
            data += list(P(tmp, 2))

        random.shuffle(data)
        # self.data = data[0:5000*cfg.TRAIN.BATCH_SIZE]
        self.data = data
        self.imgs_path = imgs_path
        self.pose_path = pose_path
        self.img_loader = img_loader
        self.pose_loader = pose_loader
        self.transform = transform

        self.class_to_idx = class_to_idx
def solution(expression):
    candis = []
    new_exp = split_exp(expression)
    operator = ['-', '*', '+']
    ranks = list(P(operator))
    for rank in ranks:
        temp = list(new_exp)
        for op in rank:  # - * +
            i = 0
            while (1):
                if op not in temp:
                    break
                if temp[i] == op:
                    temp.insert(i - 1, calculate(op, temp[i - 1], temp[i + 1]))
                    temp.pop(i)
                    temp.pop(i)
                    temp.pop(i)
                    i -= 1
                i += 1
            #     print(temp)
            # print()
        candis.append(abs(temp[0]))

    answer = max(candis)
    print(answer)
    return answer
Пример #4
0
    def __init__(self, imgs_path, pose_path, mask_path, idx_path, transform, loader):
        # train/test index
        lines = open(idx_path, 'r').readlines()
        idx = [int(line.split()[0]) for line in lines]

        # images
        images = os.listdir(imgs_path)
        poses = os.listdir(pose_path)
        masks = os.listdir(mask_path)
        
        images = [im for im in images if int(im.split('_')[0]) in idx and im in poses and (im.split('.')[0]+'.png') in masks]

        # pairs
        data = []
        for i in idx:
            tmp = [j for j in images if int(j.split('_')[0]) == i]
            data += list(P(tmp, 2))

        random.shuffle(data)
        # self.data = data[0:5000*cfg.TRAIN.BATCH_SIZE]
        self.data = data
        self.imgs_path = imgs_path
        self.pose_path = pose_path
        self.loader = loader
        self.transform = transform
        self.mask_path = mask_path
        self.transform_mask = transforms.Compose([transforms.Resize((256, 128), interpolation=3), transforms.ToTensor()])
Пример #5
0
    def __init__(self, imgs_path, pose_path, idx_path, transform, loader):
        # train/test index
        lines = open(idx_path, 'r').readlines()
        idx = [int(line.split()[0]) for line in lines]

        # images
        images = os.listdir(imgs_path)
        poses = os.listdir(pose_path)
        images = [
            im for im in images if int(im.split('_')[0]) in idx and im in poses
        ]

        # pairs
        data = []
        for i in idx:
            tmp = [j for j in images if int(j.split('_')[0]) == i]
            data += list(P(tmp, 2))

        random.shuffle(data)
        # self.data = data[0:5000*cfg.TRAIN.BATCH_SIZE]
        self.data = data
        self.imgs_path = imgs_path
        self.pose_path = pose_path
        self.loader = loader
        self.transform = transform
def score(team):  # [1,2,3]
    combi = list(P(team, 2))
    cnt = 0
    for c in combi:
        row = c[0] - 1
        col = c[1] - 1
        cnt += stat[row][col]
    return cnt
Пример #7
0
def gen(n):
    val = 0
    s = '0123456789'
    sn = s[:n + 1]
    for i in P(sn):
        k = ''.join(i)
        if ch(k):
            val += int(k)
    return val
Пример #8
0
def find_mult_3g(num):
    num = str(num)
    a = set()
    for i in range(1, len(num) + 1):
        for p in P(num, i):
            x = int(''.join(p))
            if x and x % 3 == 0:
                a.add(x)
    return [len(a), max(a)]
def solution(user_id, banned_id):
    answer = []
    candis = list(P(user_id, len(banned_id)))
    for users in candis:
        if check(users, banned_id):  # 일치할 경우
            if set(users) not in answer:
                answer.append(set(users))
    print(f"answer:{answer}")
    return len(answer)
Пример #10
0
def solution(expression):
    # 연산자 종류
    sep = ['*', '+', '-']

    # 주어진 expression을 숫자와 연산자로 구분해서 저장할 리스트
    numbers, operations = splitExpression(expression, sep)

    answer = 0
    # 가능한 모든 조합에 대해 우승 상금을 정해본다.
    for priority_ops in list(P(sep, 3)):
        temp_num, temp_op = numbers[:], operations[:]

        # 연산자 우선순위의 순열을 각각 조회
        for op in priority_ops:
            # 우선순위를 갖는 연산자부터 전부 연산을 수행해본 후 결과값 저장
            while True:
                try:
                    opIndex = temp_op.index(op)
                    temp_op.pop(opIndex)
                    left = temp_num.pop(opIndex)
                    right = temp_num.pop(opIndex)

                    if op == "+":
                        temp_num.insert(opIndex, left + right)
                    elif op == "-":
                        temp_num.insert(opIndex, left - right)
                    else:
                        temp_num.insert(opIndex, left * right)
                except:
                    break

        # 최종 계산 결과가 최대값을 갖는지 확인
        result = abs(temp_num[0])
        if result > answer:
            answer = result
    return answer
    def largestTimeFromDigits(self, arr: List[int]) -> str:
        from itertools import permutations as P

        h, m = -1, -1

        for a in list(P(arr)):
            hour = a[0] * 10 + a[1]
            minute = a[2] * 10 + a[3]
            if hour < 24 and minute < 60:
                if hour > h:
                    h, m = hour, minute
                elif hour == h and minute > m:
                    m = minute

        if h == -1 and m == -1:
            return ''

        if len(str(h)) == 1:
            h = '0' + str(h)

        if len(str(m)) == 1:
            m = '0' + str(m)

        return str(h) + ':' + str(m)
Пример #12
0
def calculate_pandigital():
    permutations = P(['1', '2', '3', '4', '5', '6', '7', '8', '9'])
    dic = {}
    for p in permutations:
        check_permutation_has_products(p, dic)
    return dic
Пример #13
0
        if key in costs:
            costs[key] += value
        else:
            costs[key] = value
            people.add(pers_a)
            people.add(pers_b)

print(costs)

part1 = max(
    sum(
        costs[tuple(sorted([perm[i], perm[(i + 1) % len(perm)]]))]
        for i in range(len(perm))
    )
    for perm in P(people)
)
print("part 1:", part1)

me = "foobar"
for p in people:
    costs[K(me, p)] = 0
people.add(me)

print(costs)

part2 = max(
    sum(
        costs[tuple(sorted([perm[i], perm[(i + 1) % len(perm)]]))]
        for i in range(len(perm))
    )
Пример #14
0
from itertools import permutations as P
L, R = lambda: map(int, input().split()), range
n, m, k = L()
A, B, C = 5001, [[*L()] for _ in R(n)], [[*L()] for _ in R(k)]
for p in P(R(k), k):
    b = [[B[y][x] for x in R(m)] for y in R(n)]
    for K in p:
        r, c, S = C[K]
        r, c, q = r - 1, c - 1, []
        for s in R(S, 0, -1):
            q += [(r - s, i + 1, b[r - s][i]) for i in R(c - s, c + s)]
            q += [(i + 1, c + s, b[i][c + s]) for i in R(r - s, r + s)]
            q += [(r + s, i - 1, b[r + s][i]) for i in R(c + s, c - s, -1)]
            q += [(i - 1, c - s, b[i][c - s]) for i in R(r + s, r - s, -1)]
        for y, x, v in q:
            b[y][x] = v
    A = min(*map(sum, b), A)
print(A)
Пример #15
0
#2309
import sys
import math
from itertools import permutations as P

a = []
for _ in range(9):
    a.append(int(sys.stdin.readline().rstrip('\n')))
total = list(P(range(9), 7))
for c in total:
    tmp = []
    for i in c:
        tmp.append(a[i])
    if sum(tmp) == 100:
        print('\n'.join(map(str, sorted(tmp))))
        break
Пример #16
0
                TF = False
                break
        if TF:
            prime_list.append(i)

    return prime_list


prime_list = primes(4)  ## 네 자리 소수 생성

while prime_list:  ## 방식이 독특. 하나씩 대상으로 하면서 지워감

    p = prime_list[0]  ## 리스트의 첫 번째 소수

    # Find permutation
    p_permu = map(lambda x: int(''.join(x)), P(str(p),
                                               4))  ## 첫 번째 소수를 permutations함
    p_permu = list(set(filter(lambda x: x in prime_list, p_permu)))  ## 소수인지 확인
    p_permu.sort()

    if not p_permu or len(p_permu) <= 2:  ## 없거나 두개 이하면
        prime_list.pop(0)  ## 그 소수 리스트에서 지워버리고 다음
        continue

    prime_list = list(filter(lambda x: x not in p_permu,
                             prime_list))  ## 아니면 우선 세 개 이상인 소수를 리스트에서 지워줌

    # Check if the permutation fits the condition
    for numbers in list(C(p_permu, 3)):  ## 3개씩 뽑아서 공차 확인
        if numbers[2] - numbers[1] == numbers[1] - numbers[0]:  ## 공차가 같으면
            print(numbers)  ## print
Пример #17
0
from operator import add
from itertools import product as P
from sys import maxsize as m
if __name__ == '__main__':

    n, m = map(int, input().split(' '))
    sC, sR = [0 for i in range(m)], []
    for i in range(n):
        M = list(map(int, input().split(' ')))
        sC = list(map(add, M, sC))
        sR += [
            sum(M),
        ]
    A = tuple(P(sR, sC))
    mXOR = -m
    for x, y in A:
        mXOR = max(x ^ y, mXOR)
    print(mXOR)
'''

Chandu and XOR
Max. Marks 100

Chandu is weak in maths. His teacher gave him homework to find maximum possible pair XOR in a matrix of size N x M with some conditions. Condition imposed is that, the pair can be formed between sum of elements in a column and sum of elements in a row.
See sample explanation for more details.

Input:
First line consists of two integers N, M.
Next N line contains M space separated integers denoting the value of matrix entry.

Output:
Пример #18
0
# -*- coding: utf-8 -*-
"""Project Euler problem 24"""

from itertools import permutations as P

print("Answer: " + str(list(sorted(["".join(l) for l in P("0123456789")]))[1000000-1]))
Пример #19
0
    def fit(self, X_train, y_true, rate=0.1, max_epochs=1000):
        """
        The training method.

        Tries out possible combinations of weights,
        and updates them whenever accuracy increases.

        By "tries out", it is meant:
            - Make a prediction, and compare it's accuracy with the
            set with the correct label (training set).

        Further, by making the prediction, it is meant:
            - Calculate the weighted sum of input-weight pair.
            - Check if this sum is greater than (for now) 0 (a constant
            bias).

        ----------------------------------------------------------------------
        :param: X_train:        2D list of training examples
        :param: y_true:        List of corresponding labels (preferably 0-1)
        :param: rate:           Learning rate of model (default 0.1)
        :param: max_epochs:     As the name says (default 1000)

        """

        # Assuming for simplicity that optimum learning rate lies
        # between -5 and 5.
        wt_range_lower = -5
        wt_range_upper = 6

        total_epochs = float(wt_range_upper - wt_range_lower) / rate

        weights = np.arange(wt_range_lower, wt_range_upper, step=rate)
        # Values between `wt_range_lower` and `wt_range_upper` are
        # checked for accuracy. The value where accuracy is max is finally
        # set as the optimum weight.
        '''
        Better solution:
            Create a temporary list of (here) 3 size.
            Multiply corresponding elements to all examples to update them.
        # Status: not happening.
        Using `itertools` instead.
        '''

        num_features = len(X_train[0])
        # LogicalError when ``r > len(weights)``
        wt_permutations = np.array(list(P(weights, r=num_features)))
        '''
        Multiplying each feature by a permutation, and
        calculating accuracy for each weight-permutation,
        by calculating the weighted sum for each weight-permutation.
        '''
        best_accuracy_so_far = 0.

        for weight in wt_permutations:
            modified_X_train = []
            for feature_set in X_train:
                modified_X_train.append(
                    np.multiply(feature_set, weight).tolist())

            # Finding weighted sum and corresponding output
            this_wt_sum = 0.
            y_pred = []
            for feature in modified_X_train:
                for val in feature:
                    this_wt_sum += val
                if this_wt_sum >= self.threshold:
                    y_pred.append(1)
                else:
                    y_pred.append(0)

            this_accuracy = accuracy_score(y_true, y_pred)
            if this_accuracy > best_accuracy_so_far:
                best_accuracy_so_far = this_accuracy
                self.optimum_weight = weight
            print('\n\n=========================')
            # print('Epochs: {} out of {}'.format(wt_permutations.index(weight),
            #                                     total_epochs))
            print('Accuracy: {}'.format(this_accuracy))
            print('=============================')

        print('Max accuracy achieved: {}'.format(best_accuracy_so_far))
        print('Weights set: {}'.format(self.optimum_weight))
from sys import maxsize as m
from itertools import product as P 
class Solution:
    def bazinga(self,N,p):
        pass 

if __name__=='__main__':
    n,a,b = map(int,input().split(' '))

    D = [str(i) for i in range(1,n+1,2)]    #odd
    R = [str(i) for i in range(2,n+1,2)]    #even
    M = [[0 for i in range(b)] for i in range(a)]
    #print(R,D,M)

    for p in P([i for i in range(a)],[i for i in range(b)]):
        x,y=p[0],p[1]

        if (x+y)%2!=0:
            if R!=[]:   M[x][y]=R.pop(-1)
            else:   M[x][y]= '0'
        else:
            if D!=[]:   M[x][y]=D.pop(-1)
            else:   M[x][y]= '0'

    if (len(D)>0 or len(R)>0) and n!=1:
        print(-1)
    else:
        for i in range(len(M)):
            print(' '.join(M[i]))
'''
Пример #21
0
    # find the best set of witnesses
    best_witnesses = i64_witnesses
    for bound, bound_ws in witnesses_bounds:
        if n < bound:
            best_witnesses = bound_ws
            break
    # check compositeness with the witnesses
    for a in best_witnesses:
        a %= n
        if a and check_composite(n, s, d, a):
            return False
    return True
s = '123456789'
l = []
for i in xrange(1,11):
    a = P(s[:i])
    for j in a:
		c = int(''.join(j))
		if is_prime(c):
			push(l,c)
h(l)
for i in xrange(input()):
	a = True
	n = input()
	ln = len(l)
	for j in xrange(ln):
		if l[ln -j-1] < n:
			a = False
			print l[ln - j-1]
			break
	if a:
Пример #22
0
def gen_board(a, b, n, moves):
    perms = list(P([a, b], 2))
    return {(i, j): set([(m1(i, a), m2(j, b)) for a, b in perms
                         for m1, m2 in moves
                         if 0 <= m1(i, a) < n and 0 <= m2(j, b) < n])
            for i in range(n) for j in range(n)}
Пример #23
0
#!/usr/bin python
''' 
TODO: 
	Performance 
	Do it more pythonically with generators.
'''
from itertools import permutations as P
import sys 
import operator

file = open(sys.argv[1])
lines = file.read().splitlines()
num_of_tests = int(lines[0])

for i in range(num_of_tests):
	num_of_coordinates = int(lines[i*3 + 1])
	permA = P(lines[i*3 + 2].split(' ')) # remove the spaces from the line
	permB = P(lines[i*3 + 3].split(' '))
	permA = [map(int, x) for x in permA] # change to int
	permB = [map(int, x) for x in permB]

	res = sys.maxint # start from something high
	for j in permA:		
		for k in permB:
			prod = reduce(operator.add, map(operator.mul, j, k))
			res = min(res, prod)
	print 'Case #%s: %s' % (str(i+1), res)

'''
4명의 학생 A, B, C, D에게 검은색 모자 6개와
흰색 모자 6개를 나누어줌
- 각 학생은 1개 이상 바음
- 학생 A가 받는 검은색 모자 개수는 4개 이상 -> 얘 기준으로 경우 나누기
- 흰색 모자보다 검은색 모자를 더 많이 받는 학생은 A를 포함하여 2명뿐
'''

from itertools import combinations_with_replacement as H
from itertools import product as P

'''
BB = ['Ab', 'Bb', 'Cb', 'Db'] #검은모자 받는 개수 -> 중복조합시켜서 개수 세기
bGet = list(H(BB, 6));
#print(len(bGet))
'''

BB = ['Ab', 'Bb', 'Cb', 'Db']
WW = ['Aw', 'Bw', 'Cw', 'Dw']

BBbc = list(H(BB, 6)) #4H6
WWwc = list(H(WW, 6)) #4H6
#두 집합의 곱: product

total = list(P(BBbc, WWwc))
WB = [i[0]+i[1] for i in total]
print(len(WB))
Пример #25
0
from itertools import permutations as P
n = list(map(int, input().split()))
numbers = list(map(int, input().split()))
comb = list(P(numbers, n[1]))
comb.sort()
for i in comb:
    answer = ""
    for j in i:
        answer += str(j) + " "
    print(answer)
Пример #26
0
from itertools import permutations as P

NATIONALITIES = 'Norwegian Englishman Ukrainian Spaniard Japanese'.split()
X = range(5)

WATER, ZEBRA = next(
    (water, zebra)
    for (red, green, ivory, yellow, blue) in P(X)
    if(green - ivory == 1)

    for (norway, english, ukraine, spain, japan) in P(X)
    if(all((norway == 0, english == red)))

    for (dog, fox, snails, horse, zebra) in P(X)
    if(spain == dog)

    for (coffee, tea, milk, orange, water) in P(X)
    if(all((coffee == green, ukraine == tea, milk == 2)))

    for (oldgold, kools, chesterfield, luckystrike, parliaments) in P(X)
    if(all((
        oldgold == snails, kools == yellow, parliaments == japan,
        abs(chesterfield - fox) == abs(kools - horse) == abs(norway - blue) == 1,
        luckystrike == orange
    ))))


def drinks_water():
    return NATIONALITIES[WATER]

Пример #27
0
 def permute(self, nums: List[int]) -> List[List[int]]:
     return P(nums)
Пример #28
0
import sys

input = sys.stdin.readline
from itertools import combinations as C, permutations as P

people = [x for x in range(int(input()))]
S = [list(map(int, input().split())) for x in range(len(people))]
team = list(C(people, len(people) // 2))

limit = len(team)
gap = 9001
for i in range(limit // 2):
    sum1 = 0
    sum2 = 0
    startTeam = list(P(team[i], 2))
    linkTeam = list(P(team[limit - i - 1], 2))
    for j in range(len(startTeam)):
        sum1 += S[startTeam[j][0]][startTeam[j][1]]
        sum2 += S[linkTeam[j][0]][linkTeam[j][1]]
    if gap > abs(sum1 - sum2):
        gap = abs(sum1 - sum2)

print(gap)
Пример #29
0
#!/usr/bin/env python3

import re
from itertools import permutations as P
from typing import Dict, List, Tuple, Set

# INPUT_FILE_NAME: str = "test-input"
INPUT_FILE_NAME: str = "input"

LINE_PATTERN: re.Pattern = re.compile(r"^(\S+) to (\S+) = (\d+)$")

distances: Dict[Tuple[str, str], int] = {}
cities: Set[str] = set()
with open(INPUT_FILE_NAME, "r") as input_file:
    for line in input_file:
        m = LINE_PATTERN.match(line)
        if not m:
            raise Exception(f"Can't parse line: {line}")

        distances[tuple(sorted([m[1], m[2]]))] = int(m[3])
        cities.add(m[1])
        cities.add(m[2])

print(
    min(
        sum(distances[tuple(sorted([perm[i], perm[i + 1]]))]
            for i in range(len(perm) - 1)) for perm in P(cities)))
Пример #30
0
from itertools import product as P
n = list(map(int, input().split()))
numbers = list(map(int, input().split()))
numbers.sort()
comb = list(P(numbers, repeat=n[1]))
comb.sort()
for i in comb:
    answer = ""
    for j in i:
        answer += str(j) + " "
    print(answer)