Пример #1
0
def calc_distances(seqs,words):
#     if(path.isfile('distmat')):
#         f = open('distmat','r')
#         distmat = numpy.load(f)
#         f.close()
#         return distmat
    words = dict(words)
    if(path.isfile('distdict')):
        distlist = file2list('distdict')
        return distlist
    d = {}
    for seq in seqs:
        s = list(seq)
        w = s.pop(N/2)
        s = tuple(s)
        if s not in d:
            d[s] = {}
        if w not in d[s]:
            d[s][w] = 0
        d[s][w] += 1
#     distmat = numpy.zeros(shape=(len(words),len(words)))
    distdict={}
    print(len(d)) 
    for s in d:
        pairs = itertools.permutations(d[s],2)
        for (w1,w2) in pairs:
            w = [w1,w2]
            c = [words[w1],words[w2]]
            w = tuple([x for (y,x) in sorted(zip(c,w))])
#                 dist = float(d[s][w[0]])+float(d[s][w[1]])
            dist = (float(d[s][w[0]])/c[0])*(float(d[s][w[1]])/c[1])
#             if w1 not in distdict:
#                 distdict[w1] = {}
#             if w2 not in distdict[w1]:
#                 distdict[w1][w2] = 0
#             distdict[w1][w2] += dist 
#             if w2 not in distdict:
#                 distdict[w2] = {}
#             if w1 not in distdict[w2]:
#                 distdict[w2][w1] = 0
            if w not in distdict:
                distdict[w] = 0
            distdict[w] += dist 
#                 distmat[i][j] += dist
#                 distmat[j][i] += dist
#     f = open('distmat', 'w')
#     numpy.save(f, distmat)
#     f.close()
    distlist = sorted(distdict.iteritems(), key = operator.itemgetter(1), reverse=True)
    list2file(distlist, 'distdict')
#     d = sorted(d.iteritems(), key = operator.itemgetter(1), reverse=True)
#     list2file(d, 'd')
    return distlist
Пример #2
0
def faster_solve(formula):
    """ Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
    Input formula is a string; output is a digit-filled-in string or None.
    This version precompiles the formula; only one eval per formula. """
    f, letters = compile_formula(formula)
    for digits in itertools.permutations((1,2,3,4,5,6,7,8,9,0), len(letters)): 
        try:
            if f(*digits) is True:
                table = string.maketrans(letters, ''.join(map(str, digits)))
                return formula.translate(table)
        except ArithmeticError: 
            pass  
def dup(sen):
    result = []
    for p in sen :
        p =  innerDup(p)
        if p not in result:
            duplicates = list(itertools.permutations(p, len(p)))
            duplicatesList = [list(elem) for elem in duplicates]
            flag = True
            for dup in duplicatesList:
                if dup in result:
                    flag = False
                    break
            if flag:
                result += [p]
    return result
Пример #4
0
def UPGMA(Data,n):
    gen = n
    
    Clusters = {i:[i] for i in range(n)}
    all_Clusters = {i:[i] for i in range(n)}
    T = {i:[] for i in range(n)}
    
    distCache = {(i,j):Data[i][j] for i in range(n) for j in range(n)}
    
    Age = {i:0 for i in range(n)}
    
    def dist(clust1,clust2):
        if (clust1,clust2) in distCache:
            return distCache[(clust1,clust2)]
        else:
            dd = sum([ sum([ Data[i][j] for j in Clusters[clust2]]) for i in Clusters[clust1]])/(len(Clusters[clust1])*len(Clusters[clust2]))
            distCache[(clust1,clust2)] = dd
            distCache[(clust2,clust1)] = dd
            return dd 
    
    while len(Clusters)>1:
        permuts = itertools.permutations(Clusters.keys(),2)
        closest = min(permuts,key = lambda x:dist(x[0],x[1]))
        Clusters[gen] = Clusters[closest[0]]+Clusters[closest[1]]
        
        T[gen] = [closest[0],closest[1]]
        Age[gen] = dist(closest[0],closest[1])/2
        
        all_Clusters[gen] = Clusters[closest[0]]+Clusters[closest[1]]
        
        del Clusters[closest[0]]
        del Clusters[closest[1]]
        
        for c in Clusters:
            dist(gen,c)
        gen = gen+1
    
    
    TA = {}
    
    for (k,vv) in T.items():
        if len(vv)>0:
            TA[k] = {}
            for v in vv:
                TA[k][v] = Age[k]-Age[v]
    
    return TA
Пример #5
0
 def test_排序單元試驗(self):
     毋著四 = 拆文分析器.對齊組物件('我有一張椅仔', 'ngoo2 iu2 it4 tiong1 i2 a2')
     毋著三 = 拆文分析器.對齊組物件('我有一張椅仔', 'ngoo2 u7 it4 tiong1 i2 a2')
     毋著二 = 拆文分析器.對齊組物件('我有一張椅仔', 'ngoo2 u7 tsit8 tiong1 i2 a2')
     毋著一 = 拆文分析器.對齊組物件('我有一張椅仔', 'ngoo2 u7 tsit8 tiunn1 i2 a2')
     無毋著 = 拆文分析器.對齊組物件('我有一張椅仔', 'gua2 u7 tsit8 tiunn1 i2 a2')
     無毋著.分數 = 90
     毋著一.分數 = 80
     毋著二.分數 = 70
     毋著三.分數 = 60
     毋著四.分數 = 50
     答案集 = 集()
     答案集.內底組 = [無毋著, 毋著一, 毋著二, 毋著三, 毋著四, ]
     for 組陣列 in itertools.permutations([毋著四, 毋著三, 毋著二, 毋著一, 無毋著]):
         集物件 = 集()
         集物件.內底組 = 組陣列
         self.assertEqual(集內組照排.排(lambda 組物件: -組物件.分數, 集物件), 答案集)
Пример #6
0
def hier_clustering(Data,n):
    gen = n
    
    Clusters = {i:[i] for i in range(n)}
    all_Clusters = {i:[i] for i in range(n)}
    
    T = {i:[] for i in range(n)}
    while len(Clusters)>1:
        permuts = itertools.permutations(Clusters.keys(),2)
        closest = min(permuts,key = lambda x:dist(Clusters[x[0]],Clusters[x[1]],Data))
        Clusters[gen] = Clusters[closest[0]]+Clusters[closest[1]]
        T[gen] = [closest[0],closest[1]]
        all_Clusters[gen] = Clusters[closest[0]]+Clusters[closest[1]]
        print ' '.join([str(c+1) for c in Clusters[closest[0]]])+" "+' '.join([str(c+1) for c in Clusters[closest[1]]])
        del Clusters[closest[0]]
        del Clusters[closest[1]]
        gen = gen+1
    return T,all_Clusters
def hier_clustering(Data,n):
    gen = n
    
    Clusters = {i:[i] for i in range(n)}
    all_Clusters = {i:[i] for i in range(n)}
    
    T = {i:[] for i in range(n)}
    while len(Clusters)>1:
        permuts = itertools.permutations(Clusters.keys(),2)
        closest = min(permuts,key = lambda x:dist(Clusters[x[0]],Clusters[x[1]],Data))
        Clusters[gen] = Clusters[closest[0]]+Clusters[closest[1]]
        T[gen] = [closest[0],closest[1]]
        all_Clusters[gen] = Clusters[closest[0]]+Clusters[closest[1]]
        print (' '.join([str(c+1) for c in Clusters[closest[0]]])+" "+' '.join([str(c+1) for c in Clusters[closest[1]]]))
        del Clusters[closest[0]]
        del Clusters[closest[1]]
        gen = gen+1
    return T,all_Clusters
Пример #8
0
def createPermutationFile(filePath, nodeIdList, nrPlayers):
    """Create all permutations for nodes in nodeIdList and write them in a file for future use"""
    myFile = open(filePath, "w+")
    # write header
    myFile.write("permutations for nodes: %s\n" % (", ".join([str(x) for x in nodeIdList])))
    # get list of all permutations and write it in file
    rez = itertools.permutations(nodeIdList, nrPlayers * 2)
    if nrPlayers < 5:
        combList = transform(list(rez))
        for elem in combList:
            myFile.write("\t".join([str(x) for x in elem]))
            myFile.write("\n")
    else:
        # listaTuple = list(rez)
        # write permutations to file
        for item in rez:
            aux = list(item)
            myFile.write("\t".join([str(x) for x in aux]))
            myFile.write("\n")
    myFile.close()
Пример #9
0
 def check_group(orig_group, new_group, coord_permuts):
     smallest_error = None
     orig_group.sort()
     new_group.sort()
     pc = 0
     permut = itertools.permutations(new_group)
     for p in permut:
         pc += 1
         self.assertEqual(len(orig_group), len(p),
                          "Not equal amount of coordinate groups.")
         check, err = check_permut(orig_group, p, coord_permuts)
         if check:
             print("Found match after considering", pc, "permutations.")
             #print(orig_group)
             #print(p)
             #print("------------------------------------------------")
             return True, None
         else:
             if smallest_error is None or err[0] < smallest_error[0]:
                 smallest_error = err
     return False, smallest_error
Пример #10
0
# -*- coding:utf-8 -*-
# 给一个没有重复数字的数组,求所有的排列组合。
from timeit import itertools

# dfs


def permute(nums):
    res = []
    dfs(nums, [], res)
    return res


def dfs(nums, path, res):

    if not nums:
        res.append(path)

    for i in range(len(nums)):
        dfs(nums[:i] + nums[i + 1:], path + [nums[i]], res)


print(permute([1, 2, 3]))
#直接用python中的itertools.permutations函数。
print(map(list, itertools.permutations([1, 2, 3])))
Пример #11
0
     dictb= {}
     for item in a:
         dicta[item] = 1
     print dicta
     for item in b:
         if (v-item) in dicta: 
             return True
     return False

 import itertools
'''
Method 2
'''
 list1=['a','b','c']
 list2=[1,2]
 zip(x,list2) for x in itertools.permutations(list1,len(list2))]



def sumOfTwo(a, b, v):
	'''
	Method 3
	'''
    combined = [zip(i,a) for i in itertools.permutations(b,len(a))]
    cc = map(sum,itertools.chain(*combined))
    if v in cc:
        return True
    else:
        return False

Пример #12
0
    def assert_numeric_data(self, orig, new):
        group = 0
        midgroup = 0
        subgroup = 0
        line = -1
        sizes = []
        emptylinecount = 0
        orig_set = [[]]
        new_set = [[]]
        orig_basis = [[]]
        new_basis = [[]]
        #message = ''.join(difflib.ndiff(orig.splitlines(True),new.splitlines(True)))
        message = ''

        for orig_line, new_line in zip_longest(orig.splitlines(),
                                               new.splitlines()):
            if orig_line == "" and new_line == "":
                emptylinecount += 1
                if emptylinecount == 2:
                    if group == 2:
                        del orig_basis[-1]
                        del new_basis[-1]
                    group += 1
                    subgroup = 0
                    midgroup = 0
                    line = -1
                    orig_set = [[[]]]
                    new_set = [[[]]]
                    continue
                subgroup += 1
                if group == 2:
                    orig_basis.append([])
                    new_basis.append([])
                elif group == 3:
                    orig_set[midgroup] += [[]]
                    new_set[midgroup] += [[]]
                continue
            line += 1
            emptylinecount = 0
            self.assertTrue(
                orig_line is not None, "Verification file missing line:" +
                new_line + "\nFull diff:\n" + message)
            self.assertTrue(
                new_line is not None, "New version missing line:" + orig_line +
                "\nFull diff:\n" + message)
            for orig_datum, new_datum in zip_longest(orig_line.split(),
                                                     new_line.split()):
                self.assertTrue(
                    orig_datum is not None,
                    "Verification file missing datum: " + new_datum +
                    "\nFull diff:\n" + message)
                self.assertTrue(
                    new_datum is not None, "New version missing datum:" +
                    orig_datum + "\nFull diff:\n" + message)
                if group == 1:
                    sizes.append(int(orig_datum))
                if group == 2:
                    # Basis vecs can be returned in any order...
                    try:
                        orig_basis[-1].append(float(orig_datum))
                        new_basis[-1].append(float(new_datum))
                    except ValueError as e:
                        self.assertTrue(
                            False,
                            "Coordinate values not floats: misformatted output:"
                            + orig_datum + " vs " + new_datum)
                elif group == 3:
                    # Coordinates can be returned in any order...
                    if len(orig_set[-1]) == sizes[midgroup] + 1:
                        del orig_set[-1][-1]
                        del new_set[-1][-1]
                        midgroup += 1
                        orig_set.append([[]])
                        new_set.append([[]])
                    try:
                        orig_set[-1][-1].append(float(orig_datum))
                        new_set[-1][-1].append(float(new_datum))
                    except ValueError as e:
                        self.assertTrue(
                            False,
                            "Coordinate values not floats: misformatted output:"
                            + orig_datum + " vs " + new_datum)
                else:
                    try:
                        orig_int = int(orig_datum)
                        new_int = int(new_datum)
                    except ValueError as e:
                        try:
                            orig_float = float(orig_datum)
                            new_float = float(new_datum)
                        except ValueError as e:
                            self.assertTrue(
                                orig_datum == new_datum,
                                "Comparing strings:" + orig_datum + " != " +
                                new_datum + "\nFull diff:\n" + message)
                        else:
                            self.assertAlmostEqual(
                                orig_float, new_float, 5,
                                "Comparing floats:" + orig_datum + " != " +
                                new_datum + "\nFull diff:\n" + message)
                    else:
                        self.assertEqual(
                            orig_int, new_int, "Comparing ints:" + orig_datum +
                            " != " + new_datum + "\nFull diff:\n" + message)

        def check_permut(orig_set, new_set, coord_permuts=[0, 1, 2]):
            self.assertEqual(len(orig_set), len(new_set),
                             "Not equal amount of coordinates in this group.")
            for orig_line, new_line in zip(orig_set, new_set):
                self.assertEqual(
                    len(orig_line), len(new_line),
                    "Not equal amount of coordinate values, misformed data.")
                for orig_datum, new_datum in zip(
                        orig_line, [new_line[x] for x in coord_permuts]):
                    if round(abs(orig_datum - new_datum), 4) != 0:
                        return False, (abs(orig_datum - new_datum), orig_datum,
                                       new_datum)
            return True, None

        def check_group(orig_group, new_group, coord_permuts):
            smallest_error = None
            orig_group.sort()
            new_group.sort()
            pc = 0
            permut = itertools.permutations(new_group)
            for p in permut:
                pc += 1
                self.assertEqual(len(orig_group), len(p),
                                 "Not equal amount of coordinate groups.")
                check, err = check_permut(orig_group, p, coord_permuts)
                if check:
                    print("Found match after considering", pc, "permutations.")
                    #print(orig_group)
                    #print(p)
                    #print("------------------------------------------------")
                    return True, None
                else:
                    if smallest_error is None or err[0] < smallest_error[0]:
                        smallest_error = err
            return False, smallest_error

        del orig_set[-1]
        del new_set[-1]

        self.assertEqual(len(orig_basis), len(new_basis),
                         "Unequal amount of basis vectors, misformed output.")
        x_permuts = itertools.permutations(range(len(new_basis)))
        smallest_error = None
        for xp in x_permuts:
            y_permuts = itertools.permutations(range(len(new_basis)))
            for yp in y_permuts:
                check, err = check_permut(orig_basis,
                                          [[new_basis[x][y] for y in yp]
                                           for x in xp])
                if check:
                    coord_x_permuts = xp
                    coord_y_permuts = yp
                    break
                if smallest_error is None or err[0] < smallest_error[0]:
                    smallest_error = err
            else:
                continue
            break
        else:
            self.assertTrue(
                False,
                "Basis vectors not equal (despite considering all permutations)\n"
                + str(orig_basis) + '\nvs\n' + str(new_basis) +
                "\nSmallest error:" + str(smallest_error))
        coord_permuts = [coord_x_permuts[x] for x in coord_y_permuts]

        for orig_group, new_group in zip(orig_set, new_set):
            check, err = check_group(orig_group, new_group, coord_permuts)
            if not check:
                self.assertTrue(
                    False,
                    "Coordinates not equal (despite considering all permutations), smallest error:"
                    + str(err))
                break
Пример #13
0
    return fin.readline().strip().split(' ')
def writeline(value):
    fout.write(str(value))
    fout.write("\n")
def read_integers():
    return [int(x) for x in fin.readline().strip().split(' ')]
def read_integer():
    return int(fin.readline().strip())

def distance(d1,d2):
    if d1>d2:
        return 12+d2-d1
    else:
        return d2-d1

    
notes={'C':0,'C#':1,'D':2,'D#':3,'E':4,'F':5,'F#':6,'G':7,'G#':8,'A':9,'B':10,'H':11}
triad=[notes[x] for x in readstrings()]
for conf in itertools.permutations(triad):
    d1=distance(conf[0], conf[1])
    d2=distance(conf[1], conf[2])
    if d1==4 and d2==3:
        writeline('major')
        sys.exit()
    elif d1==3 and d2==4:
        writeline('minor')
        sys.exit()
writeline('strange')


def getPossibleDuplicates(prop):
    """used to get possible duplicates in the proposition"""
    duplicates = list(itertools.permutations(prop, len(prop)))
    duplicatesList = [list(elem) for elem in duplicates]
    return duplicatesList