コード例 #1
0
def maximizingXor(l, r):
    l1=list(range(l,r+1))
    h=list(com(l1,2))
    k=[]
    for i in range(len(h)):
        k.append(h[i][0]^h[i][1])
    return max(k)
コード例 #2
0
ファイル: utils.py プロジェクト: yueliangaaa/rdma-core
def get_dmabuf_access_flags(ctx):
    """
    Similar to get_access_flags, except that dma-buf MR only support
    a subset of the flags.
    :param ctx: Device Context to check capabilities
    :return: A random legal value for MR flags
    """
    attr = ctx.query_device()
    vals = [
        e.IBV_ACCESS_LOCAL_WRITE, e.IBV_ACCESS_REMOTE_WRITE,
        e.IBV_ACCESS_REMOTE_READ, e.IBV_ACCESS_REMOTE_ATOMIC,
        e.IBV_ACCESS_RELAXED_ORDERING
    ]
    if not attr.atomic_caps & e.IBV_ATOMIC_HCA:
        vals.remove(e.IBV_ACCESS_REMOTE_ATOMIC)
    arr = []
    for i in range(1, len(vals)):
        tmp = list(com(vals, i))
        tmp = filter(filter_illegal_access_flags, tmp)
        for t in tmp:  # Iterate legal combinations and bitwise OR them
            val = 0
            for flag in t:
                val += flag.value
            arr.append(val)
    return arr
コード例 #3
0
 def combinationSum31(self, k: int, n: int) -> List[List[int]]:
     tmp = list(map(list, list(com(range(1, 10), k))))
     res = []
     for i in tmp:
         if sum(i) == n:
             res.append(i)
     return res
コード例 #4
0
ファイル: utils.py プロジェクト: Edan7/rdma-core
def get_access_flags(ctx):
    """
    Provide an array of random legal access flags for an MR.
    Since remote write and remote atomic require local write permission, if
    one of them is randomly selected without local write, local write will be
    added as well.
    After verifying that the flags selection is legal, it is appended to an
    array, assuming it wasn't previously appended.
    :param ctx: Device Context to check capabilities
    :param num: Size of initial collection
    :return: A random legal value for MR flags
    """
    attr = ctx.query_device()
    attr_ex = ctx.query_device_ex()
    vals = list(e.ibv_access_flags)
    if not attr_ex.odp_caps.general_caps & e.IBV_ODP_SUPPORT:
        vals.remove(e.IBV_ACCESS_ON_DEMAND)
    if not attr.device_cap_flags & e.IBV_DEVICE_MEM_WINDOW:
        vals.remove(e.IBV_ACCESS_MW_BIND)
    if not attr.atomic_caps & e.IBV_ATOMIC_HCA:
        vals.remove(e.IBV_ACCESS_REMOTE_ATOMIC)
    arr = []
    for i in range(1, len(vals)):
        tmp = list(com(vals, i))
        tmp = filter(filter_illegal_access_flags, tmp)
        for t in tmp:  # Iterate legal combinations and bitwise OR them
            val = 0
            for flag in t:
                val += flag.value
            arr.append(val)
    return arr
コード例 #5
0
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        subsets = []
        nums.sort()

        for i in range(len(nums) + 1):
            subsets += com(nums, i)

        return list(map(list, set(subsets)))
コード例 #6
0
def combination(a, b):
    L = []
    count = 0
    for k in range(1, a + 1):  #a를 이용해서 [1,2,3,4,...a-2, a-1, a]의 리스트 만들기
        L.append(k)
    for c in com(L, b):
        count += 1
    return count
コード例 #7
0
def answer(num_buns, num_required):
    bunnies = [[] for i in range(num_buns)]
    if num_required == 0:
        return bunnies
    start = 0
    for c in com(bunnies, num_buns - num_required + 1):
        for item in c:
            item.append(start)
        start += 1
    return bunnies
コード例 #8
0
ファイル: [18]四数之和.py プロジェクト: wellqin/USTC
 def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
     from itertools import combinations as com
     dic, l = collections.defaultdict(list), [*com(range(len(nums)), 2)]
     for a, b in l:
         dic[target - nums[a] - nums[b]].append((a, b))
     r = [(*ab, c, d) for c, d in l for ab in dic[nums[c] + nums[d]]]
     return [
         *set(
             tuple(sorted(nums[i] for i in t))
             for t in r if len(set(t)) == 4)
     ]
コード例 #9
0
def solution(n, s):
    if n >= s:
        return [-1]
    else:
        L = [i for i in range(1, s + 1)]
        for j in com(
                L, n
        ):  #1부터 n까지 들어있는 리스트에서 sCn을 이용해서 그 중에 리스트의 합이 s인 것만 추출해서 M에 저장한다.
            if sum(j) == s:
                answer = list(j)
    return answer  #if문 바깥에서 값을 반환하면 맨마지막 원소가 반환되는 원리 이용
def solution(n, s):
    from itertools import combinations as com

    L=[i for i in range(1, s+1)]
    M=[]
    if (n*(n+1))/2 > s: #1,2,3...,n의 합보다 s가 작다면
        return [-1]
    else:
        for j in com(L,n):
            if sum(j)==s:
                M.append(j)
    return list(M[-1])
コード例 #11
0
def solution(n, s):
    L = []
    M = []
    if n >= s:
        return [-1]
    else:
        for i in range(1, s + 1):
            L.append(i)
        for j in com(
                L, n
        ):  #1부터 n까지 들어있는 리스트에서 sCn을 이용해서 그 중에 리스트의 합이 s인 것만 추출해서 M에 저장한다.
            if sum(j) == s:
                M.append(j)  #M은 s의 합으로 이루어진 원소가 n개 들어있는 조합들
        return list(M[-1])  #M의 원소들 중 맨마지막에 있는 원소의 총 곱이 가장 큼
コード例 #12
0
def apriori(itr):
    allCans, itr = [], list(itr)  # all candidates
    k, sup = 1, len(itr) * sr  # k-itemsets, support
    fi = [(x, ) for x in set(chain.from_iterable(itr))]  # C1

    # frequent k-itemsets
    while fi:
        dic = {k: 0 for k in fi}
        for it in itr:
            for c in dic:
                if set(c).issubset(it):
                    dic[c] += 1
        fi = [x for x in dic if dic[x] >= sup]
        allCans += fi
        k += 1
        if len(fi) < k:
            break
        # generate Ck
        fi = [
            x for x in com(set(chain.from_iterable(fi)), k)
            if not [y for y in com(x, k - 1) if y not in fi]
        ]

    return allCans
コード例 #13
0
 def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
     import collections
     from itertools import combinations as com
     # 将两个索引组合存入l中
     dic, l = collections.defaultdict(list), [*com(range(len(nums)), 2)]
     # 将剩下的两数之和作为索引存入dic
     for a, b in l:
         dic[target - nums[a] - nums[b]].append((a, b))
     # 如果nums[c]+nums[d]存在,从字典中取出对应a,b索引
     r = [(*ab, c, d) for c, d in l for ab in dic[nums[c] + nums[d]]]
     return [
         *set(
             tuple(sorted(nums[i] for i in t))
             for t in r if len(set(t)) == 4)
     ]
コード例 #14
0
def NaiveB(test, trusted_list, tr_total, tr_occ, untrusted_list, un_total, utr_occ):
    
    temp = list()
    for i in range(1, len(test)): # +1 in the len() for all, include the same list itself
        els = [set(x) for x in com(test, i)]
        temp.append(els)
        
    combs = list()
    for x in temp:
        [combs.append(each) for each in x]
        
    tn = len(trusted_list)
    un = len(untrusted_list)
    total = tn + un
    
    itemsets = list()
    [itemsets.append(x) for x in tr_occ if(x not in itemsets)]
    [itemsets.append(y) for y in utr_occ if(y not in itemsets)]

    D = len(itemsets)
    
    tnk = 0
    tts = 1
    for x in combs:
        if(str(x) in tr_occ):
            tnk = tr_occ[str(x)]
        else:
            tnk = 0
        tts *= (tnk+1)/(tr_total+D)

    tts *= (tn/total)

    unk = 0
    uts = 1
    for x in combs:
        if(str(x) in utr_occ):
            unk = utr_occ[str(x)]
        else:
            unk = 0
        uts *= (unk+1)/(un_total+D)

    uts *= (un/total)
    
    if(tts >= uts):
        return 'trustworthy'
        
    else:
        return 'untrustworthy'
コード例 #15
0
def comp10001go_group(discard_history, player_no):
    '''This function takes in a discard history for a game and finds the best
    groupings of cards for a player to get the highest score possible'''
    # extracts player deck & makes sublists of all combination of cards
    player_deck = [x[player_no] for x in discard_history]
    # print(f'Player {player_no+1}\'s Deck: {player_deck}')
    card_sublist = []
    for i in range(1, len(player_deck) + 1):
        card_sublist += [x for x in com(player_deck, i)]
    # calculates the score of each sublist and saves it to a score list
    score_list = []
    for sublist in card_sublist:
        score = comp10001go_score_group(sublist)
        if score:
            score_list.append((score, sublist))
    # finds & returns the combination of lists that leads to the highest score
    return max_score(score_list)[1]
コード例 #16
0
ファイル: correction.py プロジェクト: KylerAKAnderson/muver
 def splitChoose(r):
     if (avL + avR) < r: return []
     rc = []
     if r == 1:
         if avL > 0: rc = com(left, 1)
         if avR > 0: rc = plus(rc, com(right, 1))
     elif r < 6:
         if avL == 2: rc = cross(com(left, 2), com(right, r - 2))
         if avL >= 1 and avR >= r - 1:
             rc = plus(rc, cross(left, com(right, r - 1)))
         if avR >= r: rc = plus(rc, com(right, r))
     return rc
コード例 #17
0
def rod_nD(X, parallel):
    """
    Find ROD overall scores when n>3 Data:
      # scale dataset using Robust Scaler
      # decompose the full space into a combinations of 3D subspaces,
      # Apply ROD on each combination,
      # squish scores per subspace, so we compare apples to apples,
      # return the average of ROD scores of all subspaces per observation.
    """
    X = RobustScaler().fit_transform(X)
    dim = X.shape[1]
    all_subspaces = [X[:, _com] for _com in com(range(dim), 3)]
    if parallel:
        p = Pool(multiprocessing.cpu_count())
        subspaces_scores = p.map(process_sub, all_subspaces)
        return np.average(np.array(subspaces_scores).T, axis=1).reshape(-1)
    subspaces_scores = []
    for subspace in all_subspaces:
        subspaces_scores.append(process_sub(subspace))
    return np.average(np.array(subspaces_scores).T, axis=1).reshape(-1)
コード例 #18
0
def InitializeIntraTimestamp(timestamp):  # Fast learning / detection
    ''' Generate Intra-timestamp Correlation  '''
    ''' Investigates patterns associated with samples from within a single time group   '''

    # Get the differences between each sample with a timestamp
    diff = [i[1] - i[0] for i in com(timestamp, 2)]

    # print timestamp
    # print diff

    # initialize/store all timestamps
    for i in range(len(timestamp)):
        if len(normalProfile["Intra"]["hist"]) < len(timestamp):
            normalProfile["Intra"]["hist"][i] = [timestamp[i]]
            normalProfile["Intra"]["diff"][i] = [diff[i]]
            normalProfile["Intra"]["score"][i] = 0
        else:
            normalProfile["Intra"]["hist"][i].append(timestamp[i])
            normalProfile["Intra"]["diff"][i].append(diff[i])

    return
コード例 #19
0
from itertools import combinations as com

n = int(input())
array = list(map(int, input().split()))

array.sort()

if (len(array) > 1):
    co = list(com(array[1:len(array)], 2))
    diff = []
    if len(co):
        for j in co:
            diff.append(abs(j[0] - j[1]))
        if array[0] in diff:
            print(0)
        else:
            di = array[1] - array[0]
            if len(array) > 2:
                co = list(com(array[2:len(array)], 2))
                if len(co):
                    for j in co:
                        diff.append(abs(j[0] - j[1]))
                    if di in diff:
                        print(0)
                    else:
                        di = array[1] - array[0]
                        x = [x for x in array if x < di]
                        if len(x):
                            print(min(x))
                        else:
                            print(di)
コード例 #20
0
import sys
from itertools import combinations as com

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

sys.stdin = open('input.txt', 'r')

n, m = map(int, input().split())
no = [[False] * (n + 1) for _ in range(n + 1)]
cnt = 0

for i in range(m):
    x, y = map(int, input().split())
    no[x][y] = True
    no[y][x] = True

for case in com(range(1, n + 1), 3):
    if no[case[0]][case[1]] or no[case[0]][case[2]] or no[case[1]][case[2]]:
        continue
    cnt += 1
print(cnt)
コード例 #21
0
ファイル: 15652.py プロジェクト: rheehot/Algorithm-25
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4
예제 입력 3 
3 3
예제 출력 3 
1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 3 3
2 2 2
2 2 3
2 3 3
3 3 3
"""
from itertools import combinations_with_replacement as com

n, m = map(int, input().split())

c = list(com(list(range(1, n + 1)), m))
for i in c:
    print(*i)
コード例 #22
0
from itertools import combinations_with_replacement as com

string, r = input().split()
result = list(com(sorted(string), int(r)))
for item in result:
    print(''.join(item))
コード例 #23
0
ファイル: preprocess.py プロジェクト: nmakes/ANC-data-mining
with open(monthFile) as csvfile:

    reader = csv.reader(csvfile, delimiter=',')

    data = []

    for line in reader:
        data.append([int(x) for x in line])

two = set()
three = set()

for record in data:

    f = com(record, 2)

    for group in f:
        two.add(frozenset(group))


for record in data:

    f = com(record, 3)

    for group in f:
        three.add(frozenset(group))


with open('p2/nov/novTwoGroups.csv', 'w') as csvfile:
コード例 #24
0
import sys
from itertools import combinations as com
input = lambda: sys.stdin.readline().rstrip()

sys.stdin = open('input.txt', 'r')

n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))

for case in com(arr, m):
    print(' '.join(map(str, case)))
コード例 #25
0
hawks = [118.63, 117.48, 13.84, 13.94, "hawks", 0, 2]
hornets = [111.83, 115.24, 11.53, 12.43, "hornets", 0, 2]
wizards = [118.07, 120.08, 13.04, 14.24, "wizards", 0, 2]
knicks = [105.59, 114.58, 13.26, 13.68, "knicks", 0, 2]
nets = [119.20, 112.97, 12, 12.53, "nets", 0, 2]
sixers = [107.86, 104.8, 11.57, 11.7, "sixers", 0, 2]
celtics = [107.29, 105.5, 11.89, 10.89, "celtics", 0, 2]
raptors = [108.43, 103.47, 12.59, 10.9, "raptors", 0, 2]

teams = [
    lakers, clippers, warriors, suns, kings, thunder, nuggets, timberwolves,
    blazers, jazz, spurs, mavericks, rockets, grizzlies, pelicans, bulls, cavs,
    pistons, pacers, bucks, magic, heat, hawks, hornets, wizards, knicks, nets,
    sixers, celtics, raptors
]
games = list(com(teams, 2))

num_teams = 30
# this is number of games if every teams played every other team just once (adjusted for repeats yields 1080 total games)
num_games = 435


def game(t1, t2):
    t1s = ((rnd.gauss(t1[0], t1[2]) + rnd.gauss(t2[1], t2[3])) / 2)
    t2s = ((rnd.gauss(t2[0], t2[2]) + rnd.gauss(t1[1], t1[3])) / 2)
    if t1s > t2s:
        t1[5] = t1[5] + 1

    else:
        t2[5] = t2[5] + 1
コード例 #26
0
ファイル: rod.py プロジェクト: John-Almardeny/pyod
def rod_nD(X, parallel, gm, data_scaler, angles_scalers1, angles_scalers2):
    """
    Find ROD overall scores when Data is higher than 3D:
      # scale dataset using Robust Scaler
      # decompose the full space into a combinations of 3D subspaces,
      # Apply ROD on each combination,
      # squish scores per subspace, so we compare apples to apples,
      # calculate average of ROD scores of all subspaces per observation.
    Note that if gm, data_scaler, angles_scalers1, angles_scalers2 are None,
    that means it is a `fit()` process and they will be calculated and returned
    to the class to be saved for future prediction. Otherwise, if they are not None,
    then it is a prediction process.

    Parameters
    ----------
    X : array-like, data points
    parallel: bool, True runs the algorithm in parallel
    gm: list, the geometric median
    data_scaler: obj, RobustScaler of data
    angles_scalers1: list, MinMaxScalers of Angles group 1
    angles_scalers2: list, MinMaxScalers of Angles group 2

    Returns
    -------
    ROD decision scores, gm, data_scaler, angles_scalers1, angles_scalers2
    """
    if data_scaler is None:  # for fitting
        data_scaler = RobustScaler()
        X = data_scaler.fit_transform(X)
    else:  # for prediction
        X = data_scaler.transform(X)
    dim = X.shape[1]
    all_subspaces = [X[:, _com] for _com in com(range(dim), 3)]
    all_gms = [None] * len(all_subspaces) if gm is None else gm
    all_angles_scalers1 = [None] * len(
        all_subspaces) if angles_scalers1 is None else angles_scalers1
    all_angles_scalers2 = [None] * len(
        all_subspaces) if angles_scalers2 is None else angles_scalers2
    if parallel:
        p = Pool(multiprocessing.cpu_count())
        args = [[a, b, c, d] for a, b, c, d in zip(
            all_subspaces, all_gms, all_angles_scalers1, all_angles_scalers2)]
        results = p.starmap(process_sub, args)
        subspaces_scores, gm, angles_scalers1, angles_scalers2 = [], [], [], []
        for res in results:
            subspaces_scores.append(list(res[0]))
            gm.append(res[1])
            angles_scalers1.append(res[2])
            angles_scalers2.append(res[3])
        scores = np.average(np.array(subspaces_scores).T, axis=1).reshape(-1)
        p.close()
        p.join()
        return scores, gm, data_scaler, angles_scalers1, angles_scalers2
    subspaces_scores, gm, angles_scalers1, angles_scalers2 = [], [], [], []
    for subspace, _gm, ang_s1, ang_s2 in zip(all_subspaces, all_gms,
                                             all_angles_scalers1,
                                             all_angles_scalers2):
        scores_, gm_, ang_s1_, ang_s2_ = process_sub(subspace, _gm, ang_s1,
                                                     ang_s2)
        subspaces_scores.append(scores_)
        gm.append(gm_)
        angles_scalers1.append(ang_s1_)
        angles_scalers2.append(ang_s2_)
    scores = np.average(np.array(subspaces_scores).T, axis=1).reshape(-1)
    return scores, gm, data_scaler, angles_scalers1, angles_scalers2
コード例 #27
0
def comp10001go_play(discard_history, player_no, hand):
    '''This function identifies the best card from a player to discard from 
    their hand (based on the discard pile) to get the highest score possilbe'''
    # turn counting variables
    n_turns = len(discard_history)
    hand_turn = len(discard_history) % 4
    # READD NEXT TURN IF EXPERIMENT FAILS
    '''if hand_turn == 3:
        next_turn = 0
    else:
        next_turn = hand_turn + 1'''
    # removing cards from dict after discard
    for i in hand_dict:
        for card_set in discard_history:
            for card in card_set:
                try:
                    hand_dict[i].remove(card)
                except ValueError:
                    pass
    # collects all hands info in hand dict and combinations of opponents cards
    hand_dict[hand_turn] = hand
    temp_hand_dict = {key: hand_dict[key] for key in hand_dict.keys() - 
                      {hand_turn}}  # add next_turn if code too long
    opponent_cards = [temp_hand_dict[x] for x in temp_hand_dict]
    opponent_comb_list = list(prod(*opponent_cards))
    # returns a random card if first turn (with priority of higher cards)
    if n_turns == 0:
        high_hand = [x for x in hand if not x[0].isdigit() and x[0] != 'A']
        if high_hand:
            return ran(high_hand)
        else:
            return ran(hand)
    # creates playeres deck
    player_deck = [x[player_no] for x in discard_history]
    # print(f'Player {player_no+1}\'s Deck: {player_deck}')
    potential_decks_list = []
    # finds the potential score for each card added
    for card in hand:
        for card_sets in opponent_comb_list:
            # gets sublist of all discarded cards + potential discard
            # program considers potential future cards when scoring
            temp_deck = [x for x in player_deck]
            temp_deck.append(card)
            for pot_card in card_sets:
                temp_deck.append(pot_card)
            card_sublist = []
            for i in range(1, len(temp_deck) + 1):
                card_sublist += [x for x in com(temp_deck, i)]
            score_list = []
            for sublist in card_sublist:
                # EXPERIMENTAL CODE
                if sublist in score_dict:
                    score = score_dict[sublist]
                else:
                    score_dict[sublist] = comp10001go_score_group(sublist)
                    score = score_dict[sublist]
                # EXPERIMENTAL CODE
                if score:
                    score_list.append((score, sublist))
            # calculates which card would lead to the highest increase in score
            potential_decks_list.append((max_score(score_list), card))
    return max(potential_decks_list)[1]
コード例 #28
0
from itertools import combinations as com

s, n = input().split()

for i in range(1, int(n) + 1):
    for j in com(sorted(s), i):
        print(''.join(j))
コード例 #29
0
import math
from itertools import combinations as com

k = int(input())
num = [i for i in range(1, k + 1)]
cnt = sum(num)

for a, b in com(num, 2):
    cnt += 6 * math.gcd(a, b)

for a, b, c in com(num, 3):
    cnt += 6 * math.gcd(c, math.gcd(a, b))

print(cnt)
コード例 #30
0
    print(i)

# or

x = 'abc'
y = 'def'
z = 'ghi'
arr = [x, y, z]
for i in chain.from_iterable(arr):
    print(i)

#itertools combinations method -USING this u can write all combinations that can be
# done using this method
from itertools import combinations as com
letter = 'ABCDEF'
x = com(letter, 3)
y = [''.join(i) for i in x]
y

# Accumulate function
import operator
from itertools import accumulate
x = list(range(5))
y = list(accumulate(x, operator.add))
y

# counters are subclass of dictionary
#There are 3 ways to initialize counters

from collections import Counter
#with sequence of itemns containing repeated values