def bfn(m):
    un_data = []
    for l in prange(rnge):
        m1 = []
        m2 = []
        for o in prange(m):
            m1.append(random_three_vector())
        for p in prange(m):
            m2.append(random_three_vector())

        ar1 = list(cmb(m1, 2))
        ar2 = list(cmb(m2, 2))
        ar1 = np.array(ar1)
        ar2 = np.array(ar2)
        bell = []

        for i in prange(len(ar1)):
            u = ar1[i][0]
            v = ar1[i][1]
            for j in prange(len(ar2)):
                x = ar2[j][0]
                y = ar2[j][1]
                bell.append(f1(u, v, x, y))

        for i in prange(len(ar1)):
            u = ar1[i][0]
            v = ar1[i][1]
            for j in prange(len(ar2)):
                x = ar2[j][0]
                y = ar2[j][1]
                bell.append(f2(u, v, x, y))

        for i in prange(len(ar1)):
            u = ar1[i][0]
            v = ar1[i][1]
            for j in prange(len(ar2)):
                x = ar2[j][0]
                y = ar2[j][1]
                bell.append(f3(u, v, x, y))

        for i in prange(len(ar1)):
            u = ar1[i][0]
            v = ar1[i][1]
            for j in prange(len(ar2)):
                x = ar2[j][0]
                y = ar2[j][1]
                bell.append(f4(u, v, x, y))

        t5 = max(bell)
        un_data.append(round(t5, 2))

    un_data.sort()
    mata = un_data
    un_data = np.array(mata)
    return un_data
def Promo_Retailer_NFL(Model, run=True):
    """Enforcing certain promotions not to follow each other."""
    if run:
        Promos_Nos = Globals.Promos_Nos_3
        Model.Promo_Retailer_NFL_Constraints = pyo.ConstraintList()

        from itertools import combinations as cmb

        for Prod in range(len(Promos_Nos)):
            TPF = getattr(GLV.Model, f"TPR_FLAG_PPG_{Prod}")

            for comb in cmb(Promos_Nos[Prod], 2):
                for Promo in range(len(comb) - 1):
                    #
                    for Wk in range(Globals.Tot_Week - 1):
                        Model.Promo_Retailer_NFL_Constraints.add(
                            (
                                TPF[Wk, comb[Promo] - 1]
                                * TPF[Wk + 1, comb[Promo + 1] - 1]
                            )
                            + (
                                TPF[Wk, comb[Promo + 1] - 1]
                                * TPF[Wk + 1, comb[Promo] - 1]
                            )
                            == 0
                        )
示例#3
0
def create_graph(n,p):
	nodes = range(n)
	g = nx.Graph()
	g.add_nodes_from(nodes)
	for u,v in cmb(g,2):
		if rnd.random() < p:
			g.add_edge(u,v)
	return g
def solution(orders, course):
    answer = []
    for c in course:
        tmp = Counter(
            [''.join(sorted(i)) for o in orders for i in list((cmb(o, c)))])
        num = sorted(tmp.values())
        if len(tmp) == 0 or num[-1] < 2: continue
        for k, v in tmp.items():
            if v == num[-1]: answer.append(k)
    return sorted(answer)
    def numTeams(self, rating: List[int]) -> int:
        result = cmb(rating, 3)

        c = 0

        for i in result:
            if ((i[0] < i[1] and i[1] < i[2])
                    or (i[0] > i[1] and i[1] > i[2])):
                c += 1
        return c
示例#6
0
def small(n, k, cakes):
    maxArea = 0
    for c in cmb(cakes, k):
        ht = 0
        rmax = 0
        for cake in c:
            ht += cake[0] * cake[1]
            rmax = max(cake[0], rmax)
        maxArea = max(pi * (ht * 2 + rmax**2), maxArea)
    return maxArea
def solve():
    s = [x for x in input().strip()]
    cnf = []
    pos = []
    for x in range(10):
        if s[x] == "o":
            for y in range(4):
                cnf.append(x)
        if s[x] == "?":
            pos.append(x)
    #print(cnf,pos)
    print(4 * len(pos) * len(set(cmb(cnf, 4))))
示例#8
0
def disperse_energy(syst, temp, timestep, n_types=1):
    """
    This routine moves the particles via gradient descent to a local energy 
    minimium. The parameters f_max, gamma and max_displacement are necessary to
    stop particles shooting off to infinity. The values have been taken from a
    sample script and are used without thought to their justification.
    """

    print("\nDisperse Particles by Minimization of Energy\n")

    syst.time_step = timestep

    # Thermostat
    syst.thermostat.set_langevin(kT=temp, gamma=1.0, seed=123)
    n_part = len(syst.part.select())
    syst.thermostat.suspend()

    types = range(n_types)

    comb = list(cmb(types, 2))
    act_min_dist = np.zeros(len(comb))
    for j in range(len(comb)):
        act_min_dist[j] = syst.analysis.min_dist(p1=[comb[j][0]],
                                                 p2=[comb[j][1]])

    energy = syst.analysis.energy()['non_bonded']

    print("Before Minimization: Energy={:.3e}, Min Dist={}".strip().format(
        energy, act_min_dist))

    # Relax structure
    syst.integrator.set_steepest_descent(f_max=10.,
                                         gamma=0.1,
                                         max_displacement=0.005)
    syst.integrator.run(2000)
    syst.integrator.set_vv()

    # remove force capping
    syst.force_cap = 0

    for j in range(len(comb)):
        act_min_dist[j] = syst.analysis.min_dist(p1=[comb[j][0]],
                                                 p2=[comb[j][1]])

    energy = syst.analysis.energy()['non_bonded']

    print("After Minimization: Energy={:.3e}, Min Dist={}".strip().format(
        energy, act_min_dist))

    # recover thermostat
    syst.thermostat.recover()
    # return min_dist
    pass
示例#9
0
def hand_control(cap):
    if os.path.isfile('last.pt'):
        torch.backends.cudnn.benchmark = True
        device = 'cuda' if torch.cuda.is_available() else 'cpu'
        net = Net().to(device); net.eval(); load_save(net,device,'last.pt')
        i2mod = {1:'s', 2:'f', 3:'c', 4:'p', 5:'m', 9:'g', 10:'h'}

    wh = np.array([cap.get(3),cap.get(4)]); G,S,K,k = 1,4,'',0
    det = mp.solutions.hands; draw = mp.solutions.drawing_utils
    hand = draw.DrawingSpec(color=(255,0,0), thickness=1, circle_radius=3)
    with det.Hands(max_num_hands=1, min_detection_confidence=0.75) as pose:
        while k!=27: # dir(i.landmark)
            _, im = cap.read(); k = cv2.waitKey(5)
            if 48<k<58: S = k-48 # speed=1-9
            elif k==32: GO(Twist()) # Blank=pause
            elif k==13: HM(Int8()); rospy.sleep(2) # Enter

            im = cv2.flip(im,1); res = mp_infer(pose,im)
            if res.multi_hand_landmarks: # find hand
                i = res.multi_hand_landmarks[0]
                p = [(m.x,m.y) for m in i.landmark]*wh

                K = chr(k) if k>0 else K # key->mode
                if k>0 and chr(k) in 'mpc': # trigger
                    p0, r0 = p[9], norm(p[9]-p[13])
                elif 'net' in dir(): # hand->mode
                    x = ((p-p[9])/wh[1]).astype('float32')
                    x = torch.tensor(x).ravel()[None].to(device)
                    x = i2mod.get(net(x)[0].argmax().item(),'')
                    if x in 'mpc' and x!=K: # trigger
                        p0, r0 = p[9], norm(p[9]-p[13])
                    K = x # update mode. # distance -> grip
                elif sum(norm(d[1]-d[0]) for d in cmb(p[6:9],2))/3<norm(p[6]-p[5])/4: K = 'g'
                if K in 'mpc': xyz = get_xyz(im, p, p0, r0, K, S)
                draw.draw_landmarks(im, i, det.HAND_CONNECTIONS, hand, hand)
            else: K = '' # reset mode
            info = f'%s L={S}'%MOD.get(K,'OFF')
            cv2.putText(im, info, (5,20), 4, 0.7, (255,)*3)
            cv2.imshow('Hand', im)

            if K=='h': HM(Int8()); flush(cap) # standby
            elif K=='m': GO(Twist(linear=xyz)) # arm_move
            elif K=='p': GO(Twist(angular=xyz)) # arm_pose
            elif K=='g': G = 1-G; GP(Int8(G)); flush(cap) # grip
            elif K=='f' and S<9: S += 1; flush(cap) # fast
            elif K=='s' and S>1: S -= 1; flush(cap) # slow
            elif K=='c': pass # chasis
        cv2.destroyAllWindows(); HM(Int8())
示例#10
0
def pair_specific_circRNA(in_fn='',
                          min_read_cnt=2,
                          min_iso_cnt=2,
                          spe_out='',
                          all_iso_ratio_out='',
                          tmp_dir=''):
    raw_name_cmb = list(cmb(raw_names, 2))
    with open(spe_out, 'w') as out_fp, open(all_iso_ratio_out,
                                            'w') as ratio_fp:
        out_fp.write('ReadCnt\tIsoCnt\tVar1\tVar2\tCate\tValue\n')

        ratio_fp.write(
            'Tissue1\tTissue2\tReadCnt\tIsoCnt\tCount1\tRatio1\tCount2\tRatio2\n'
        )
        for name in names:
            ratio_fp.write('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(
                name, name, min_read_cnt, min_iso_cnt, 'NA', 'NA', 'NA', 'NA'))
        for raw_name in raw_name_cmb:
            name = [name_dict[raw_name[0]], name_dict[raw_name[1]]]
            tissue_spe_gene_fn = tmp_dir + '/{}_{}.spe.gene'.format(
                name[0], name[1])
            tissue_spe_iso_fn = tmp_dir + '/{}_{}.spe.iso'.format(
                name[0], name[1])
            iso_cnt_fn = tmp_dir + '/{}_{}.spe_iso.cnt'.format(
                name[0], name[1])
            spe_gene_n, spe_iso_n = specific_isoform(min_read_cnt, min_iso_cnt,
                                                     in_fn, raw_name,
                                                     tissue_spe_gene_fn,
                                                     tissue_spe_iso_fn,
                                                     iso_cnt_fn, ratio_fp)
            out_fp.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(
                min_read_cnt, min_iso_cnt, name[0], name[1], 'Gene',
                spe_gene_n))
            out_fp.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(
                min_read_cnt, min_iso_cnt, name[1], name[0], 'Gene',
                spe_gene_n))
            out_fp.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(
                min_read_cnt, min_iso_cnt, name[0], name[1], 'Isoform',
                spe_iso_n))
            out_fp.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(
                min_read_cnt, min_iso_cnt, name[1], name[0], 'Isoform',
                spe_iso_n))
        for name in names:
            out_fp.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(
                min_read_cnt, min_iso_cnt, name, name, 'Gene', 0))
            out_fp.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(
                min_read_cnt, min_iso_cnt, name, name, 'Isoform', 0))
示例#11
0
def solve(vd,cd,i):
    if i==len(guess): return vd
    for correct in cmb(cd[i], guess[i][1]):
        vd_c = deepcopy(vd)
        cd_c = deepcopy(cd)
        cd_c[i] = [y for y in correct]
        for j in xrange(len(vd)):
            v = int(guess[i][0][j])
            if j in correct:
                if v not in vd[j]: break
                vd_c[j] = [v]
            else:
                if v in vd_c[j]:
                    vd_c[j].remove(v)
                    if not vd_c[j]: break
        else:
            if not ac3(vd_c,cd_c): continue
            t = solve(vd_c,cd_c,i+1)
            if t: return t
    return False
示例#12
0
 def __init__(self, val):
     self.__val = val
     self.__allergy_vals = sorted(
         [2**x for x in range(0, len(self.__allergy_lst))])
     self.__max_val = sum(self.__allergy_vals)
     if self.__val > self.__max_val:
         self.__val -= 2**len(self.__allergy_lst)
     self.__allergy_vals = sorted(
         [x for x in self.__allergy_vals if x <= self.__val])  # refine
     if self.__val > 0 and self.__val % 2 == 0:
         self.__allergy_vals = self.__allergy_vals[
             1:]  # to del or not to del, that is the question.
         self.__allergy_lst = self.__allergy_lst[
             1:]  # to del, or not to del, that is the question.
     self.__allergy_tup = zip(self.__allergy_vals, self.__allergy_lst)
     self.list = []
     if self.__val == 0:
         # No allergies.
         self.list = []
     elif self.__val == self.__max_val:
         # All allergies.
         self.list = self.__allergy_lst
     elif self.__val in self.__allergy_vals:
         # Exactly 1 allergy (hackish)
         self.list = [
             x[1] for x in self.__allergy_tup if x[0] == self.__val
         ]
     elif self.__val != self.__max_val:
         # We need to compute which allergies based on a sum
         for x in range(2, len(self.__allergy_tup)):
             tc = cmb(range(0, len(self.__allergy_tup)), x)
             for y in tc:
                 if sum([self.__allergy_tup[x][0]
                         for x in y]) == self.__val:
                     self.list = [self.__allergy_tup[x][1] for x in y]
                     break
             if len(self.list) > 0:
                 break
     else:
         raise Exception("Bad Programmer, go back to school.")
示例#13
0
def evaluate_primes():
    # JSON mode
    data = request.get_json()
    app.logger.info("data sent for evaluation {}".format(data))
    inputValue = data.get("input")
    if inputValue % 2 == 0:
        return jsonify(stackexchange(inputValue))
    else:
        ans = stackexchange(inputValue - 3)
        ans.append(3)
        return jsonify(ans)

    # Args Key Mode
    # data = request.args
    # inputValue = int(data.get('input'))

    end = False
    i = 1
    n = inputValue
    while (i <= 10):
        cnt = i
        ci = iter(cmb(genP(n), cnt))
        while True:
            try:
                c = next(ci)
                if sum(c) == n:
                    print(n, ',', cnt, "->", '+'.join(str(s) for s in c))
                    result = c
                    break
            except:
                print(n, ',', cnt, " -> Not possible")

                break
        i = i + 1

    app.logger.info("My result :{}".format(result))

    return jsonify(result)
from itertools import combinations as cmb
n = int(input())
s = input().strip().split()
k = int(input())
p = 0
for element in s:
    if element == 'a':
        p += 1
if p == 0:
    numerator = len(list(cmb(s,k)))
else:
    numerator = len(list(cmb(s[:-p],k)))
    
print (1-numerator/len(list(cmb(s,k))))
示例#15
0
文件: euler53.py 项目: jokoon/eio
    
    (2,4),
    (3,4),
    
    (2,5),
    (3,5),
    (4,5),
    
    (2,6),
    (3,6),
    (4,6),
    (5,6),
    
    (2,7),
    (3,7),
    (4,7),
    (5,7),
    (6,7),
]:
    a1, a2 = countish(n,r), len([a for a in cmb(range(n),r)])
    print(repr((r,n)),a1 == a2, a1,a2)

res = 0
for n in range(3,101):
    for r in range(2,n):
        val = countish(n,r)
        if val>1e6:
            res+=1

print(res)
示例#16
0
    s = ''
    for i in range(len(perm)):
        s += str(perm[i])
        if not i == len(perm) - 1:
            s += opr[i]
    return s


def sumOfN(n):
    return n * (n + 1) // 2


if __name__ == '__main__':
    digits = list(range(1, 9))
    operators = ['+', '-', '*', '/']
    digits_perm = list(cmb(digits, 4))
    operators_perm = list(product(operators, repeat=3))
    print(len(operators_perm))
    print(len(digits_perm))
    maxS = 0
    maxEval = ''
    for digitL in digits_perm:
        totalEval = set()
        for pdl in list(perm(digitL)):
            for opr in operators_perm:
                expr = getExpr(pdl, opr)
                evalL = evaluateAll(expr, 0, len(expr) - 1)
                evalL = set(
                    filter(lambda x: x > 0 and int(x) == x, list(evalL)))
                totalEval = totalEval.union(evalL)
        if (digitL == (1, 2, 3, 4)):

def isP(n):
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    return all(n % x > 0 for x in range(3, int(n ** 0.5) + 1, 2))

def genP(n):
    p = [2]
    p.extend([x for x in range(3, n + 1, 2) if isP(x)])
    return p

data = [
    (99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24),
    (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3)]

for n, cnt in data:
    ci = iter(cmb(genP(n), cnt))
    while True:
        try:
            c = next(ci)
            if sum(c) == n:
                print(' '.join(
                    [repr((n, cnt)), "->", '+'.join(str(s) for s in c)]
                ))
                break
        except StopIteration:
            print(repr((n, cnt)) + " -> Not possible")
            break
示例#18
0
 def getTransitionPairs(transitions):
     return list(cmb(range(len(transitions)), 2))
示例#19
0

def genP(nInput):

    pArr = [2]
    pArr.extend([xLoop for xLoop in range(3, nInput + 1, 2) if IsPrime(xLoop)])

    return pArr


## dataArr = [(99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3)]
dataArr = [(18, 2), (19, 3)]

for nNum_01, nNum_02 in data:

    nIter = iter(cmb(genP(nNum_01), nNum_02))

    while True:
        try:
            nNextSum = next(nIter)
            if sum(nNextSum) == nNum_01:

                print(" ".join([
                    repr((nNum_01, nNum_02)), "->",
                    " + ".join(str(nSumLoop) for nSumLoop in nNextSum)
                ]))
                break

        except StopIteration:

            print(repr((nNum_01, nNum_02)) + " -> Not possible")
def R(Q):
    return (chain.from_iterable(
        cmb(list(Q), i) for i in range(len(list(Q)) + 1)))
from itertools import combinations as cmb
n = int(input())
s = input().split()
k = int(input())
cm = list(cmb(s,k))
print(round(sum([1 for c in cm if 'a' in c ])/len(cm),3))
示例#22
0
 def largestTriangleArea(self, points: List[List[int]]) -> float:
     return max(self.calc_area(p0, p1, p2) for p0, p1, p2 in cmb(points, 3))
示例#23
0
 def MapPairs (self, key, valueList):
     locPairs = list(cmb(sorted(map(int,valueList)),2))
     for eachPair in locPairs:
         yield eachPair, 1
示例#24
0
from modules.MyMath import getPrimes as pr
from itertools import combinations as cmb


N = 10000
primes = [n for n in pr(N) if n>1000]
nmbrs = []

for i in primes:
    tmp = set()
    for j in primes:
        if i != j and set(str(i)) == set(str(j)):
            tmp.add(i)
            tmp.add(j)
    if tmp != [] and len(tmp) > 2 and tmp not in nmbrs:
        nmbrs.append(tmp)


answer = []

for elements in nmbrs:
    for el in cmb(elements, 3):
        if abs(el[0]-el[1]) == abs(el[1]-el[2]):
            answer.append(el)

print(answer)
示例#25
0
 def __init__(self, characters: str, combinationLength: int):
     self.characters = characters
     self.combinationLength = combinationLength
     self.l = list(cmb(characters, combinationLength))
示例#26
0
from itertools import combinations as cmb
list1_of_people = [
    'Amey', 'Abhisar', 'Kalpaj', 'Bhumika', 'Jayaram SP', 'VH Kustagi'
]
list2_of_people = [
    'Amey', 'Jayaram SP', 'VH Kustagi', 'Radhika Vadiraj', 'Anvita', 'Vaibhav'
]
Result1 = cmb(list1_of_people, 2)
Result2 = cmb(list2_of_people, 2)
for item in Result1:
    print(item[0] + '-->' + item[1])