Пример #1
0
 def start(self):
     self.game_over = False
     self.puzzle = []
     for i in xrange(9):
         self.puzzle.append([])
         for j in xrange(9):
             self.puzzle[i].append(self.start_puzzle[i][j])
Пример #2
0
 def __check_square(self,row,column):
         return self.__check_block(
             [
                 self.puzzle[r][c]
                 for r in xrange(row*3,(row+1)*3)
                 for c in xrange(column*3,(column+1)*3)
             ]
         )
Пример #3
0
 def view_boardH(self):
     print("\n Solution Steps: \t Initial State -> Goal\n")
     for i in xrange(len(self.tree_data) - 1, 0, -1):
         print(str(self.tree_data[i][0]) + "\t", end="")
     print(str([1, 2, 3]))
     for i in xrange(len(self.tree_data) - 1, 0, -1):
         print(str(self.tree_data[i][1]) + "\t", end="")
     print(str([8, 0, 4]))
     for i in xrange(len(self.tree_data) - 1, 0, -1):
         print(str(self.tree_data[i][2]) + "\t", end="")
     print(str([7, 6, 5]))
Пример #4
0
 def check_win(self):
         for row in xrange(9):
             if not self.__check_row(row):
                 return False
         for column in xrange(9):
             if not self.__check_column(column):
                 return False
         for row in xrange(3):
             for column in xrange(3):
                 if not self.__check_square(row,column):
                     return False
         self.game_over = True
         return True
Пример #5
0
 def __draw_puzzle(self):
         self.canvas.delete("numbers")
         for i in xrange(9):
             for j in xrange(9):
                 answer = self.game.puzzle[i][j]
                 if answer != 0:
                     x = MARGIN + j * SIDE + SIDE / 2
                     y = MARGIN + i * SIDE + SIDE / 2
                     original = self.game.start_puzzle[i][j]
                     color = "black" if answer == original else "sea green"
                     self.canvas.create_text(
                         x,y, text=answer, tags="numbers", fill=color
                     )
Пример #6
0
def tarjan_edges(graph):
    global expl,comp
    size = len(graph)

    for vertex in xrange(0, size):
        expl.append(0)
        comp.append(0)

    for vertex in xrange(0, size):
        if expl[vertex] == 0:
            dfs_edges(graph, vertex)

    print("edges = ", edges)
    return edges
Пример #7
0
def tarjan_edges(graph):
    global expl, comp
    size = len(graph)

    for vertex in xrange(0, size):
        expl.append(0)
        comp.append(0)

    for vertex in xrange(0, size):
        if expl[vertex] == 0:
            dfs_edges(graph, vertex)

    print("edges = ", edges)
    return edges
Пример #8
0
def kcn(k, c, s):
    if k == 1:
        return 1

    if c == 1:
        if k > s:
            return 'IMPOSSIBLE'
        else:
            return ' '.join(str(i) for i in xrange(1, k+1))

    if s <= k - 2:
        return 'IMPOSSIBLE'
    else:
        return ' '.join(str(i) for i in xrange(2, k + 1))
Пример #9
0
def tarjan_coloring(graph):
    global expl3
    topological_sort = []
    size = len(graph)

    for vertex in xrange(0, size):
        expl3.append(0)

    for vertex in xrange(0, size):
        if expl3[vertex] == 0:
            if dfs_coloring(graph, vertex, 2) == 0:
                print('ERROR COLORING')
                return 0  #ERROR
    print('SUCCESS COLOR')
    return 1  #SUCCESS
def matrix_chain(n):
    global N, T
    for i in n:
        N[i, i].append(0)  # subproblemas triviais
    for b in xrange(1, n):  # tamanho dos subproblemas
        for i in xrange(0, n - b):
            j = i + b  # novo intervalo para o subproblema
            N[i, j].append(int("inf"))  # valor provisorio para a solucao
            T[i, j].append(i)  # valor provisorio para a solucao
            for k in xrange(i, j):  # equacao de calculo
                x = N[i, k] + N[k + 1, j] + d[i] * d[k + 1] * d[j + 1]
                if N[i, j] > x:
                    N[i, j].append(x)
                    T[i, j].append(k)
    return N[0, n - 1]
def make_change(moedas, troco):
    # moedas -  vetor de moedas disponiveis (menor e de 1 centavo)
    quant = [0]
    ultima = [0]
    for cents in xrange(1, troco):
        quantProv = cents  # solucao provisoria: todas de 1 centavo
        ultProv = 1  # ultima moeda dessa solucao
        for j in xrange(0, len(moedas)):
            if moedas[j] > cents:
                continue  # essa moeda nao serve
            if quant[cents - moedas[j]] + 1 < quantProv:
                quantProv = quant[cents - moedas[j]] + 1
                ultProv = moedas[j]
        quant[cents] = quantProv  # solucao para troco=cents
        ultima[cents] = ultProv  # ultima moeda dessa solucao
Пример #12
0
def tarjan_coloring(graph):
    global expl3
    topological_sort = []
    size = len(graph)

    for vertex in xrange(0, size):
        expl3.append(0)

    for vertex in xrange(0, size):
        if expl3[vertex] == 0:
            if dfs_coloring(graph, vertex, 2) == 0:
                print('ERROR COLORING')
                return 0 #ERROR
    print('SUCCESS COLOR')
    return 1 #SUCCESS
Пример #13
0
def matrix_chain(n):
    global N, T
    for i in n:
        N[i, i].append(0)  # subproblemas triviais
    for b in xrange(1, n):  #tamanho dos subproblemas
        for i in xrange(0, n - b):
            j = i + b  #novo intervalo para o subproblema
            N[i, j].append(int('inf'))  # valor provisorio para a solucao
            T[i, j].append(i)  #valor provisorio para a solucao
            for k in xrange(i, j):  #equacao de calculo
                x = N[i, k] + N[k + 1, j] + d[i] * d[k + 1] * d[j + 1]
                if N[i, j] > x:
                    N[i, j].append(x)
                    T[i, j].append(k)
    return N[0, n - 1]
Пример #14
0
def make_change(moedas, troco):
    #moedas -  vetor de moedas disponiveis (menor e de 1 centavo)
    quant = [0]
    ultima = [0]
    for cents in xrange(1, troco):
        quantProv = cents  # solucao provisoria: todas de 1 centavo
        ultProv = 1  # ultima moeda dessa solucao
        for j in xrange(0, len(moedas)):
            if moedas[j] > cents:
                continue  # essa moeda nao serve
            if quant[cents - moedas[j]] + 1 < quantProv:
                quantProv = quant[cents - moedas[j]] + 1
                ultProv = moedas[j]
        quant[cents] = quantProv  #solucao para troco=cents
        ultima[cents] = ultProv  #ultima moeda dessa solucao
def knapsack(item, maxweight):
    #
    # """
    # Solve the knapsack problem by finding the most valuable
    # subsequence of `items` subject that weighs no more than
    # `maxweight`.
    #
    # `items` is a sequence of pairs `(value, weight)`, where `value` is
    # a number and `weight` is a non-negative integer.
    #
    # `maxweight` is a non-negative integer.
    #
    # Return a pair whose first element is the sum of values in the most
    # valuable subsequence, and whose second element is the subsequence.
    #
    # #>>> items = [(4, 12), (2, 1), (6, 4), (1, 1), (2, 2)]
    # #>>> knapsack(items, 15)
    # (11, [(2, 1), (6, 4), (1, 1), (2, 2)])
    # """
    global items
    items = item
    j = maxweight
    result = []
    for i in xrange(len(items), 0, -1):
        if knapsack_bestvalue(i, j) != knapsack_bestvalue(i - 1, j):
            result.append(items[i - 1])
            j -= items[i - 1][1]
    result.reverse()
    return knapsack_bestvalue(len(items), maxweight), result
Пример #16
0
def miller_rabin(n, k=10):
    if n == 2:
        return True
    if not n & 1:
        return False

    def check(a, s, d, n):
        x = pow(a, d, n)
        if x == 1:
            return True
        for i in xrange(s - 1):
            if x == n - 1:
                return True
            x = pow(x, 2, n)
        return x == n - 1

    s = 0
    d = n - 1

    while d % 2 == 0:
        d >>= 1
        s += 1

    for i in xrange(k):
        a = randrange(2, n - 1)
        if not check(a, s, d, n):
            return False
    return True
Пример #17
0
def write_navigation(carousal_name, item_page_count):
    f.write("<div id=\"pageMarker\">")
    f.write("<ol class=\"carousel-indicators\">")
    for x in xrange(item_page_count):
        if x == 0:
            f.write("<li data-target=\"#" + carousal_name +
                    "\" data-slide-to=\"0\" class=\"active\"></li>")
        elif x == itemPageCount:
            f.write("<li data-target=\"#" + carousal_name +
                    "\" data-slide-to=\"" + str((item_page_count + 1)) +
                    "\"></li>")
        else:
            f.write("<li data-target=\"#" + carousal_name +
                    "\" data-slide-to=\"" + str(x) + "\"></li>")
    f.write("</ol>")
    f.write("</div>")

    # Arrow Keys
    f.write("""<a class='left carousel-control' href='#""" + carousal_name +
            """' data-slide='prev'>
            <span class='glyphicon glyphicon-chevron-left'></span>
            <span class='sr-only'\>Previous</span>
            </a>
            <a class='right carousel-control' href='#""" + carousal_name +
            """' data-slide=\"next\">
            <span class='glyphicon glyphicon-chevron-right'></span>
            <span class='sr-only'>Next</span>
            </a>
            </div>""")
Пример #18
0
def tarjan_scc(graph):
    global stack, ce4, expl4,scc
    stack = []

    size = len(graph)

    for vertex in xrange (0,size):
        expl4.append(0)
        scc.append(0)

    for vertex in xrange(0, size):
        if expl4[vertex] == 0:
            dfs_scc(graph, vertex)

    print('ssc = ', scc)
    return scc
Пример #19
0
 def remove_node(self, node):
     """Removes `node` from the hash ring and its replicas.
     """
     for i in xrange(0, self.replicas):
         key = self.gen_key('%s:%s' % (node, i))
         del self.ring[key]
         self._sorted_keys.remove(key)
Пример #20
0
def tarjan_scc(graph):
    global stack, ce4, expl4, scc
    stack = []

    size = len(graph)

    for vertex in xrange(0, size):
        expl4.append(0)
        scc.append(0)

    for vertex in xrange(0, size):
        if expl4[vertex] == 0:
            dfs_scc(graph, vertex)

    print('ssc = ', scc)
    return scc
Пример #21
0
    def longestPalindrome(self, s):
        if len(s) == 0:
            return 0
        maxLen = 1
        start = 0
        for i in xrange(len(s)):
            print("-------------")
            print("i=%d" % i)
            print("not yet=%s" % s[i - maxLen:i + 1])
            print("i-maxLen=%d" % (i - maxLen))
            if i - maxLen >= 1 and s[i - maxLen - 1:i + 1] == s[
                    i - maxLen - 1:i +
                    1][::-1]:  #s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]判斷迴文
                print(">=1,%s" % s[i - maxLen:i + 1])
                start = i - maxLen - 1
                maxLen += 2
                print("start=%d" % start)
                print("maxLen=%d" % maxLen)
                print("thing_return=%s" % s[start:start + maxLen])
                continue

            if i - maxLen >= 0 and s[i - maxLen:i + 1] == s[i - maxLen:i +
                                                            1][::-1]:
                print(">=0,%s" % s[i - maxLen:i + 1])
                start = i - maxLen
                maxLen += 1
            print("start=%d" % start)
            print("maxLen=%d" % maxLen)
            print("thing_return=%s" % s[start:start + maxLen])
        return s[start:start + maxLen]
Пример #22
0
def knapsack(item, maxweight):
    #
    # """
    # Solve the knapsack problem by finding the most valuable
    # subsequence of `items` subject that weighs no more than
    # `maxweight`.
    #
    # `items` is a sequence of pairs `(value, weight)`, where `value` is
    # a number and `weight` is a non-negative integer.
    #
    # `maxweight` is a non-negative integer.
    #
    # Return a pair whose first element is the sum of values in the most
    # valuable subsequence, and whose second element is the subsequence.
    #
    # #>>> items = [(4, 12), (2, 1), (6, 4), (1, 1), (2, 2)]
    # #>>> knapsack(items, 15)
    # (11, [(2, 1), (6, 4), (1, 1), (2, 2)])
    # """
    global items
    items = item
    j = maxweight
    result = []
    for i in xrange(len(items), 0, -1):
        if knapsack_bestvalue(i, j) != knapsack_bestvalue(i - 1, j):
            result.append(items[i - 1])
            j -= items[i - 1][1]
    result.reverse()
    return knapsack_bestvalue(len(items), maxweight), result
def kr(text, word, q):
    M = len(word)
    N = len(text)
    i = 0
    j = 0
    p = 0  # hash value for pattern
    t = 0  # hash value for txt
    h = 1

    # The value of h would be "pow(d, M-1)%q"
    for i in xrange(M - 1):
        h = (h * d) % q

    # Calculate the hash value of pattern and first window
    # of text
    for i in xrange(M):
        p = (d * p + ord(word[i])) % q
        t = (d * t + ord(text[i])) % q

    # Slide the pattern over text one by one
    for i in xrange(N - M + 1):
        # Check the hash values of current window of text and
        # pattern if the hash values match then only check
        # for characters on by one
        if p == t:
            # Check for characters one by one
            for j in xrange(M):
                if text[i + j] != word[j]:
                    break

            j += 1
            # if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
            if j == M:
                print("Pattern found at index " + str(i))

        # Calculate hash value for next window of text: Remove
        # leading digit, add trailing digit
        if i < N - M:
            t = (d * (t - ord(text[i]) * h) + ord(text[i + M])) % q

            # We might get negative values of t, converting it to
            # positive
            if t < 0:
                t = t + q


    # This code is contributed by Bhavya Jain
Пример #24
0
def tarjan_cycles(graph):
    global points, marked_stack, marked
    size = len(graph)

    for i in xrange(0,size):
        marked.append(False)

    for i in xrange(0,size):
        points = []
        #print("i = ", i)
        dfs_cycles(graph,i,i, False)
        while (len(marked_stack) > 0):
            u = marked_stack.pop()
            marked[u] = False
        print('SAIU')

    print('points = ', points)
Пример #25
0
 def add_node(self, node):
     """Adds a `node` to the hash ring (including a number of replicas).
     """
     for i in xrange(0, self.replicas):
         key = self.gen_key('%s:%s' % (node, i))
         self.ring[key] = node
         self._sorted_keys.append(key)
     self._sorted_keys.sort()
Пример #26
0
def tarjan_cycles(graph):
    global points, marked_stack, marked
    size = len(graph)

    for i in xrange(0, size):
        marked.append(False)

    for i in xrange(0, size):
        points = []
        #print("i = ", i)
        dfs_cycles(graph, i, i, False)
        while (len(marked_stack) > 0):
            u = marked_stack.pop()
            marked[u] = False
        print('SAIU')

    print('points = ', points)
Пример #27
0
def main(argv=None):
    vowels = "aeiou"
   # alphabetString = "abcdefghijklmnopqrstuvwxyz"
    vowelCount, niceStrings, badCombos = 0, 0, 0
    doubleLetter = False
    filename = "SampleText.txt"
    validName = False   #check if file exists
    while validName == False:
        if not os.path.isfile(filename):
            print ("File ", filename, " does not exist")
        else:
            validName = True
    #Open a file and read in the lines
    fh = open(filename, "r")
    for line in fh:
        for i in xrange(0, len(vowels)):
            vowelCount += line.count(vowels[i])
        #end for loop
        if line.find("ab") or line.find("cd") or line.find("pq") or line.find("xy"):
            print("badCombos ", line)
            badCombos = 1
        for i in xrange(0, len(line)-1):
            print ("line[i] ", line[i], "line[i+1] ", line[i+1])
            print("line[i] == line[i+1]", line[i] == line[i+1])
            if line[i] == line[i+1]:
                print("line ", line)
                doubleLetter = True
                break
            #end if
        #end for
        #end if statement
        #Re-initialise Variables
        if vowelCount >= 3 and badCombos == 0 and doubleLetter:
            niceStrings +=1
        #end if
        vowelCount, badCombos  = 0, 0
        doubleLetter = False
    fh.close()  #close the file
    
    #write to file
    print ("Analytic data for ", filename)
    print ("There are ", niceStrings, " nice strings in the file")
    print()
    
    print ("Thank you for using my program")
def is_prime(num):
    if num > 1:
        for i in xrange(2,num):
            if num%i == 0:
                return False
        else:
            return True
    else:
        return False
Пример #29
0
    def view_board(self):
        print("\n Solution Steps: \n")
        for i in xrange(len(self.tree_data) - 1, 0, -1):

            print(
                str(self.tree_data[i][0]) + "\n" + str(self.tree_data[i][1]) +
                "\n" + str(self.tree_data[i][2]) + "\n\t⬇")

        print(str([1, 2, 3]) + "\n" + str([8, 0, 4]) + "\n" + str([7, 6, 5]))
Пример #30
0
 def check(a, s, d, n):
     x = pow(a, d, n)
     if x == 1:
         return True
     for i in xrange(s - 1):
         if x == n - 1:
             return True
         x = pow(x, 2, n)
     return x == n - 1
Пример #31
0
def tarjan_topological_sort(graph):
    global cc2,ce2,expl2,comp2,sort_stack
    topological_sort = []
    size = len(graph)

    for vertex in xrange(0, size):
        expl2.append(0)
        comp2.append(0)

    for vertex in xrange(0, size):
        if expl2[vertex] == 0:
            dfs_topological_sort(graph, vertex)

    for vertex in xrange(0,size):
        topological_sort.append(sort_stack.pop())
        #ord.append(size-comp2[vertex]+1)
    print('topological_sort = ', topological_sort)
    return topological_sort
Пример #32
0
def tarjan_topological_sort(graph):
    global cc2, ce2, expl2, comp2, sort_stack
    topological_sort = []
    size = len(graph)

    for vertex in xrange(0, size):
        expl2.append(0)
        comp2.append(0)

    for vertex in xrange(0, size):
        if expl2[vertex] == 0:
            dfs_topological_sort(graph, vertex)

    for vertex in xrange(0, size):
        topological_sort.append(sort_stack.pop())
        #ord.append(size-comp2[vertex]+1)
    print('topological_sort = ', topological_sort)
    return topological_sort
Пример #33
0
def kr(text, word, q):
    M = len(word)
    N = len(text)
    i = 0
    j = 0
    p = 0  # hash value for pattern
    t = 0  # hash value for txt
    h = 1

    # The value of h would be "pow(d, M-1)%q"
    for i in xrange(M - 1):
        h = (h * d) % q

    # Calculate the hash value of pattern and first window
    # of text
    for i in xrange(M):
        p = (d * p + ord(word[i])) % q
        t = (d * t + ord(text[i])) % q

    # Slide the pattern over text one by one
    for i in xrange(N - M + 1):
        # Check the hash values of current window of text and
        # pattern if the hash values match then only check
        # for characters on by one
        if p == t:
            # Check for characters one by one
            for j in xrange(M):
                if text[i + j] != word[j]:
                    break

            j += 1
            # if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
            if j == M:
                print("Pattern found at index " + str(i))

        # Calculate hash value for next window of text: Remove
        # leading digit, add trailing digit
        if i < N - M:
            t = (d * (t - ord(text[i]) * h) + ord(text[i + M])) % q

            # We might get negative values of t, converting it to
            # positive
            if t < 0:
                t = t + q
Пример #34
0
    def predict(self, X):
        num_test = X.shape[0]
        Ypre = np.zeros(num_test, dtype=self.ytr.dtype)

        from pip._vendor.requests.packages.urllib3.connectionpool import xrange
        for i in xrange(num_test):
            distances = np.sum(np.abs(self.Xtr - X[i, :], axis=1))
            min_index = np.argmin(distances)
            Ypred[i] = self.ytr[min_index]
        return Ypred
Пример #35
0
def knapsack(c, n):
    global B, w, p
    for i in c:
        B[0, i].append(0)  # nenhum item e considerado
    for k in xrange(1, n):  #incremetno nos itens
        for i in c:  #incremento na capacidade
            if w[k] > i:
                B[k, i].append(B[k - 1, i])
            else:
                B[k, i].append(max(B[k - 1, i], B[k - 1, i - w[k]] + p[k]))
    return B[n, c]
Пример #36
0
def vetorx(c, n):
    global B, X
    r = c  #peso disponivel na mochila
    s = B[n, c]  #lucro corrente
    for i in xrange(n, 0, -1):
        if B[i - 1, r] == s:
            X[i].append(0)  # item i nao entrou
        else:
            X[i].append(1)  #item i entrou
            s -= p[i]
            r -= w[i]
Пример #37
0
def tarjan_cut_edge(graph, start):
    global ce6, dad6, expl6, m6

    size = len(graph)

    for i in xrange(0, size):
        expl6.append(0)
        dad6.append(None)
        m6.append(0)

    return dfs_cut_edge(graph, start)
def vetorx(c, n):
    global B, X
    r = c  # peso disponivel na mochila
    s = B[n, c]  # lucro corrente
    for i in xrange(n, 0, -1):
        if B[i - 1, r] == s:
            X[i].append(0)  # item i nao entrou
        else:
            X[i].append(1)  # item i entrou
            s -= p[i]
            r -= w[i]
Пример #39
0
def tarjan_cut_edge(graph, start):
    global ce6, dad6, expl6, m6

    size = len(graph)

    for i in xrange(0,size):
        expl6.append(0)
        dad6.append(None)
        m6.append(0)

    return dfs_cut_edge(graph, start)
def knapsack(c, n):
    global B, w, p
    for i in c:
        B[0, i].append(0)  # nenhum item e considerado
    for k in xrange(1, n):  # incremetno nos itens
        for i in c:  # incremento na capacidade
            if w[k] > i:
                B[k, i].append(B[k - 1, i])
            else:
                B[k, i].append(max(B[k - 1, i], B[k - 1, i - w[k]] + p[k]))
    return B[n, c]
def primes_sieve_list(limit):
    sieve = [True] * limit
    '''
    print(sys.getsizeof(sieve))
    '''
    sieve[0] = sieve[1] = False
    
    for (i, isPrime) in enumerate(sieve):
        if isPrime:
            yield i
            for n in xrange(i * i, limit, i):
                sieve[n] = False
def refresh_news():
    mas = []
    d = feedparser.parse(constants.rsslink)
    news_count = len(d['entries'])
    for numb1 in xrange(news_count):
        title1 = d['entries'][numb1]['title']
        mas.append(title1)
    ##cur.execute('CREATE TABLE rss (id INTEGER PRIMARY KEY, title VARCHAR(300), link VARCHAR(300), date VARCHAR(35) ) ')
    ##con.commit()
    for numb in xrange(news_count):
        title_local = mas[numb]
        cur.execute('SELECT * FROM rss WHERE title LIKE ?', [title_local])
        if cur.fetchone() == None :
            print("новости нету. добавляем в базу:")
            bot.send_message(constants.ch_name, title_local+"\n"+ (d['entries'][numb]['link']) )
            cur.execute('INSERT INTO rss (id, title, link, date) VALUES(NULL, ?, ?, ?)', (title_local, d['entries'][numb]['link'], d['entries'][numb].published))
            con.commit()
            sleep(2)
            print("В базу добавлено:"+title_local)
        else:
            print("такая новость уже есть:" + "  " + title_local)
def partition2(left, right):
    x = v[right]
    i = left - 1
    for j in xrange(left, right):
        if v[j] <= x:
            i += 1
            aux = v[i]
            v[i] = v[j]
            v[j] = aux
    aux = v[i+1]
    v[i+1] = v[right]
    v[right] = aux
    return i+1
def heapsort():
    print("==== build heap ====")
    build()
    print(v)
    print("==== heapsort ====")
    for i in xrange((len(v)-1), -1, -1):
        aux = v[i]
        v[i] = v[0]
        v[0] = aux
        print("ISOLA O MAIOR - ", v[i] )
        print("sift for - 0, ", i-1)
        sift_iterativo(0, i-1)
        print("HEAP MAX - ", v)
def heapsort():
    print("==== build heap ====")
    build()
    print(v)
    print("==== heapsort ====")
    for i in xrange((len(v) - 1), -1, -1):
        aux = v[i]
        v[i] = v[0]
        v[0] = aux
        print("ISOLA O MAIOR - ", v[i])
        print("sift for - 0, ", i - 1)
        sift_iterativo(0, i - 1)
        print("HEAP MAX - ", v)
def partition2(left, right):
    x = v[right]
    i = left - 1
    for j in xrange(left, right):
        if v[j] <= x:
            i += 1
            aux = v[i]
            v[i] = v[j]
            v[j] = aux
    aux = v[i + 1]
    v[i + 1] = v[right]
    v[right] = aux
    return i + 1
Пример #47
0
	def test_cached_function(self):
		self.num_of_calls = 0
		numbers_count = 7
		numbers = [random.randint(-10, 10) for i in xrange(numbers_count)]
		self._sum(numbers)
		self.assertEqual(self._sum(numbers), sum(numbers))
		self.assertEqual(self.num_of_calls, 1)
		self.assertEqual(self._sum(numbers), self._sum(numbers))
		self.assertEqual(self._sum(numbers), sum(numbers))
		self.assertEqual(self.num_of_calls, 1)
		self.assertNotEqual(self._sum(numbers[:-1]),
		                    self._sum(numbers))
		self.assertEqual(self.num_of_calls, 2)
Пример #48
0
def make_random_automaton(n):
    """
    builds an n states x k inputs automation
    with a random transition table
    :param n:
    :return: Automation
    """
    seed = random.randrange(n)
    table = []
    for i in range(0, n):
        trans = random.sample(xrange(n), n)
        table = table + [trans]
    return Automaton(seed, 0, table, seed)
Пример #49
0
 def get_node_pos(self, string_key):
     """Given a string key a corresponding node in the hash ring is returned
     along with it¡®s position in the ring.
     If the hash ring is empty, (`None`, `None`) is returned.
     """
     if not self.ring:
         return None, None
     key = self.gen_key(string_key)
     nodes = self._sorted_keys
     for i in xrange(0, len(nodes)):
         node = nodes[i]
         if key <= node:
             return self.ring[node], i
     return self.ring[nodes[0]], 0
Пример #50
0
def tarjan_cut_vertex(graph, start):
    global ce5, expl5, dad, n_kids, cut_vertex
    size = len(graph)

    for i in xrange(0, size):
        expl5.append(0)
        dad.append(0)
        n_kids.append(0)
        cut_vertex.append(False)
        m.append(0)

    dfs_cut_vertex(graph, start)
    cut_vertex[start] = (n_kids[start] > 1)

    for vertex in xrange(0, size):
        if vertex not in graph[start]:
            print(dad, dad[vertex])
            p = dad[vertex]
            cut_vertex[p] = cut_vertex[p] or (m[vertex] >= expl5[p])

    for vertex in xrange(0, size):
        if cut_vertex[vertex]:
            print('cut = ', vertex)
Пример #51
0
def tarjan_cut_vertex(graph, start):
    global ce5, expl5, dad, n_kids, cut_vertex
    size = len(graph)

    for i in xrange (0,size):
        expl5.append(0)
        dad.append(0)
        n_kids.append(0)
        cut_vertex.append(False)
        m.append(0)

    dfs_cut_vertex(graph, start)
    cut_vertex[start] = (n_kids[start] > 1)

    for vertex in xrange(0,size):
        if vertex not in graph[start]:
            print(dad, dad[vertex])
            p = dad[vertex]
            cut_vertex[p] = cut_vertex[p] or (m[vertex]>=expl5[p])

    for vertex in xrange(0,size):
        if cut_vertex[vertex]:
            print('cut = ', vertex)
Пример #52
0
    def __draw_grid(self):
            for i in xrange(10):
                color = "blue" if i % 3 == 0 else "gray"

                x0 = MARGIN + i * SIDE
                y0 = MARGIN
                x1 = MARGIN + i * SIDE
                y1 = HEIGHT - MARGIN
                self.canvas.create_line(x0,y0,x1,y1,fill=color)

                x0 = MARGIN
                y0 = MARGIN + i * SIDE
                x1 = WIDTH - MARGIN
                y1 = MARGIN + i * SIDE
                self.canvas.create_line(x0,y0,x1,y1,fill=color)
Пример #53
0
def search(page):
    search1 = "http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E5%8C%97%E4%BA%AC&kw=java&sm=0&sf=10001&st=15000&we=0103&isfilter=1&fl=530&isadv=0&sg=c38460ed2e6c4041994dc4eaabf942ce&p="
    search2 = page
    search_url = search1 + str(search2)
    print(search_url)
    data = urllib.request.urlopen(search_url).read()
    soup = BeautifulSoup(data, "html.parser")
    soup.decode('UTF-8')
    strs = soup.findAll(name='td', attrs={"class":"gsmc"})
    count = len(strs)
    file = open("result.txt", 'a')
    for x in xrange(count):
        companyName = strs[x].string
        if companyName == None:
            companyName = '123'
        file.write(companyName + '\n')
    while(page ==3):
        break
        file.close()
def merge(i, m, f):
    i1 = i
    i2 = i
    i3 = m+1
    while i2 <= m and i3 <= f:
        if v[i2] < v[i3]:
            i1+= 1
            i2+= 1
            aux[i1] = v[i2]
        else:
            i1 += 1
            i3 += 1
            aux[i1] = v[i3]
    while i2 <= m:
        i1+=1
        i2+=1
        aux[i1] = v[i2]
    while i3 <= f:
        i1 += 1
        i3 += 1
        aux[i1] = v[i3]
    for j in xrange(i, f):
        v[j] = aux[j]
def primes_sieve_set(limit):
    multiples = set()
    for i in xrange(2, limit + 1):
        if i not in multiples:
            yield i
            multiples.update(range(i * i, limit + 1, i))
def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
Пример #57
0
	def create_sequance(self, _range):
		with open('numbers', 'w') as f:
			f.writelines(' {}\n'.format(random.randint(-1000000, 1000000)) for _ in xrange(_range))
 test_cases = get_tc()
 arr =[]
 if test_cases == 1:
     numbers = raw_input()
     array = numbers.split()
     
     if len(arr) == 1:
         num1 = 1
         num2 = int(num1)
     else:
         num1 = int(array[0])
         num2 = int(array[1])
         arr.append([num1, num2]) 
     
 else:
     for tc in xrange(0,test_cases):
         numbers = raw_input()
         array = numbers.split()
         
         if len(array) == 1:
             num1 = 1
             num2 = int(num1)
         else:
             num1 = int(array[0])
             num2 = int(array[1]) 
         arr.append([num1, num2])   
         
 for ar in arr:
     num1 = ar[0]
     num2 = ar[1]
     count = 0
def build():
    for i in xrange(int(floor(len(v)/2)-1), -1, -1):
        print("FOR - ", i)
        sift(i,len(v)-1)
Пример #60
0
from pip._vendor.requests.packages.urllib3.connectionpool import xrange

a = [i for i in xrange(50, 100, 5) ]

a = str(a)

print(a)

f=open('text.txt', 'a')
f.write(a)
f.close()