Exemple #1
0
def draw_lines(im, pts1, pts2, colors = None, width = 0):
  ut.check(len(pts1) == len(pts2), 'Line endpoints different sizes')
  colors = colors_from_input(colors, None, len(pts1))
  def f(draw):
    for p1, p2, c in itl.izip(pts1, pts2, colors):
      draw.line(ut.int_tuple(p1) + ut.int_tuple(p2), fill = c, width = width)
  return draw_on(f, im)
Exemple #2
0
def draw_lines(im, pts1, pts2, colors = None, width = 0):
  ut.check(len(pts1) == len(pts2), 'Line endpoints different sizes')
  colors = colors_from_input(colors, None, len(pts1))
  def f(draw):
    for p1, p2, c in itl.izip(pts1, pts2, colors):
      draw.line(ut.int_tuple(p1) + ut.int_tuple(p2), fill = c, width = width)
  return draw_on(f, im)
Exemple #3
0
def vl_sift(im,
            frames=None,
            orientations=False,
            peak_thresh=None,
            edge_thresh=None):
    """ Compute SIFT keypoints and descriptors using VLFeat binary.
  Should be thread-safe. """
    ut.check(frames is None or frames.shape[1] == 4)
    # frame_fname = '../tmp/vl_frames.frame'
    # im_fname1 = '../tmp/vl_im.png'
    # im_fname2 = '../tmp/vl_im.pgm'
    # out_fname = '../tmp/vl_out.sift'
    frame_fname = ut.make_temp('.frame')
    im_fname1 = ut.make_temp('.png')
    im_fname2 = ut.make_temp('.pgm')
    out_fname = ut.make_temp('.sift')
    #ut.write_lines(frame_fname, ('%f %f %f 0 0 %f' % (pt[0], pt[1], s, s) for pt in pts for s in scales))
    ig.save(im_fname1, im)
    os.system('convert %s %s' % (im_fname1, im_fname2))
    frame_opt = ''
    if frames is not None:
        ut.write_lines(frame_fname, ('%f %f %f %f' % tuple(f) for f in frames))
        frame_opt = '--read-frames %s' % frame_fname
    orientation_opt = '--orientations' if orientations else ''
    peak_opt = '--peak-thresh %f' % peak_thresh if peak_thresh is not None else ''
    edge_opt = '--edge-thresh %f' % edge_thresh if edge_thresh is not None else ''
    ut.sys_check("%s %s %s %s -o %s %s %s" %
                 (SiftPath, im_fname2, frame_opt, orientation_opt, out_fname,
                  peak_opt, edge_opt))
    sift = read_sift(out_fname)
    os.system('rm %s %s %s' % (im_fname1, im_fname2, out_fname))
    return sift
def draw_text(im, texts, pts, colors, font_size=None, bold=False):
    im = rgb_from_gray(im)
    # todo: add fonts, call from draw_rects
    ut.check(len(pts) == len(texts))
    #ut.check((colors is None) or len(colors) == len(texts))
    colors = colors_from_input(colors, (0, 0, 0), len(texts))

    def f(draw):
        if font_size is None:
            font = None
        else:
            #font_name = '/usr/share/fonts/truetype/ttf-liberation/LiberationMono-Regular.ttf'
            font_choices = [
                '/usr/share/fonts/truetype/freefont/FreeMono%s.ttf' %
                ('Bold' if bold else ''), '/Library/Fonts/PTMono.ttc'
            ]
            for font_name in font_choices:
                if os.path.exists(font_name):
                    break
            else:
                raise RuntimeError(
                    'could not find a suitable font on this machine (please edit paths in img.py)'
                )

            font = ImageFont.truetype(font_name, size=font_size)

        for pt, text, color in itl.izip(pts, texts, colors):
            draw.text(ut.int_tuple(pt), text, fill=color, font=font)

    return draw_on(f, im)
Exemple #5
0
    def __init__(self, transitions, reward, discount, alpha, epsilon = 0.5, 
                 decay = 1.0, n_iter=10000, skip_check=False):
        # Initialise a Q-learning MDP.

        # The following check won't be done in MDP()'s initialisation, so let's
        # do it here
        self.max_iter = int(n_iter)
        #assert self.max_iter >= 10000, "'n_iter' should be greater than 10000."

        if not skip_check:
            # We don't want to send this to MDP because _computePR should not
            #  be run on it, so check that it defines an MDP
            _util.check(transitions, reward)

        # Store P, S, and A
        self.S, self.A = _computeDimensions(transitions)
        self.P = self._computeTransition(transitions)

        self.R = reward
        self.discount = discount
        
        self.alpha = alpha
        self.epsilon = epsilon
        self.decay = decay

        # Initialisations
        self.Q = _np.zeros((self.S, self.A))
        self.mean_discrepancy = []
    def __init__(self,
                 transitions,
                 reward,
                 discount,
                 epsilon,
                 max_iter,
                 skip_check=False):
        # Initialise a MDP based on the input parameters.

        # if the discount is None then the algorithm is assumed to not use it
        # in its computations
        if discount is not None:
            self.discount = float(discount)
            assert 0.0 < self.discount <= 1.0, (
                "Discount rate must be in ]0; 1]")
            if self.discount == 1:
                print("WARNING: check conditions of convergence. With no "
                      "discount, convergence can not be assumed.")

        # if the max_iter is None then the algorithm is assumed to not use it
        # in its computations
        if max_iter is not None:
            self.max_iter = int(max_iter)
            assert self.max_iter > 0, (
                "The maximum number of iterations must be greater than 0.")

        # check that epsilon is something sane
        if epsilon is not None:
            self.epsilon = float(epsilon)
            assert self.epsilon > 0, "Epsilon must be greater than 0."

        if not skip_check:
            # We run a check on P and R to make sure they are describing an
            # MDP. If an exception isn't raised then they are assumed to be
            # correct.
            _util.check(transitions, reward)

        self.S, self.A = _computeDimensions(transitions)
        self.P = self._computeTransition(transitions)
        self.R = self._computeReward(reward, transitions)

        # the verbosity is by default turned off
        self.verbose = False
        # Initially the time taken to perform the computations is set to None
        self.time = None
        # set the initial iteration count to zero
        self.iter = 0
        # V should be stored as a vector ie shape of (S,) or (1, S)
        self.V = None
        # policy can also be stored as a vector
        self.policy = None
Exemple #7
0
    def playout(self, board, move, depth):
        def check_winner(board, player):
            for row in range(15):
                for col in range(15):
                    if board[row, col] == renju.Player.NONE:
                        board[row, col] = player
                        if util.check(board, (row, col)):
                            return 1
                        board[row, col] = renju.Player.NONE
            return 0

        cur_player = -board[util.to_mtx_coords(move)]
        while depth < self._max_depth:
            if check_winner(board, cur_player):
                return cur_player

            if np.count_nonzero(board == renju.Player.NONE) == 0:
                return renju.Player.NONE

            probs = self._rollout.make_pred(board)
            move = np.random.choice(225, p=probs)
            board[util.to_mtx_coords(move)] = cur_player
            if util.check(board, util.to_mtx_coords(move)):
                return cur_player

            depth += 1
            cur_player = -cur_player

        return renju.Player.NONE
Exemple #8
0
        def rollout(board,
                    temp_high,
                    color,
                    checking_pos,
                    sum_logs,
                    max_high=self._high,
                    gamma=self._gamma,
                    fine=self._fine,
                    bonus=self._bonus):

            temp_predictions = 0
            if color == 'black':
                with self._black_graph.as_default():
                    temp_predictions = self._black_model.predict(board.reshape(
                        1, 15, 15, 1),
                                                                 batch_size=1,
                                                                 verbose=0)[0]
            else:
                with self._white_graph.as_default():
                    temp_predictions = self._white_model.predict(board.reshape(
                        1, 15, 15, 1),
                                                                 batch_size=1,
                                                                 verbose=0)[0]

            temp_pos = numpy.random.choice(225, p=temp_predictions)
            temp_parsed_pos = numpy.unravel_index(temp_pos, (15, 15))

            if (board[temp_parsed_pos] != 0):
                if (temp_high % 2 == 0):
                    res[checking_pos] += fine * gamma**(temp_high - 1)
                else:
                    res[checking_pos] -= bonus * gamma**(temp_high - 1)
                return

            board[temp_parsed_pos] = 1
            next_color = 'white'
            if color == 'white':
                next_color = 'black'
                board[temp_parsed_pos] = -1

            if (util.check(board, temp_parsed_pos)):
                if (temp_high % 2 == 0):
                    res[checking_pos] -= fine * gamma**(temp_high - 1)
                else:
                    res[checking_pos] += bonus * gamma**(temp_high - 1)
                return

            if (temp_high < max_high):
                rollout(board, temp_high + 1, next_color, checking_pos,
                        sum_logs + numpy.log(temp_predictions[temp_pos]))
            else:
                if logs[checking_pos]:
                    logs[checking_pos] = max(
                        logs[checking_pos],
                        sum_logs + numpy.log(temp_predictions[temp_pos]))
                else:
                    logs[checking_pos] = sum_logs + numpy.log(
                        temp_predictions[temp_pos])
            return
Exemple #9
0
def login2():
    user = request.form['username']
    password = request.form['password']
    button = request.form['button']
    if util.check(user,password):
        if 'n' not in session:
            session['n'] = "logged"
    return render_template("login.html")
Exemple #10
0
def login2():
    user = request.form['username']
    password = request.form['password']
    button = request.form['button']
    if util.check(user, password):
        if 'n' not in session:
            session['n'] = "logged"
    return render_template("login.html")
Exemple #11
0
 def check_winner(board, player):
     for row in range(15):
         for col in range(15):
             if board[row, col] == renju.Player.NONE:
                 board[row, col] = player
                 if util.check(board, (row, col)):
                     return 1
                 board[row, col] = renju.Player.NONE
     return 0
Exemple #12
0
def draw_text(im, texts, pts, colors, font_size = None):
  im = rgb_from_gray(im)
  # todo: add fonts, call from draw_rects
  ut.check(len(pts) == len(texts))
  #ut.check((colors is None) or len(colors) == len(texts))
  colors = colors_from_input(colors, (0, 0, 0), len(texts))
  def f(draw):
    if font_size is None:
      font = None
    else:
      #font_name = '/usr/share/fonts/truetype/ttf-liberation/LiberationMono-Regular.ttf'
      font_name = '/usr/share/fonts/truetype/freefont/FreeMono.ttf'
      if not os.path.exists(font_name):
        raise RuntimeError('need to change hard-coded font path to make this work on other machines')
      font = ImageFont.truetype(font_name, size = font_size)  

    for pt, text, color in itl.izip(pts, texts, colors):
      draw.text(ut.int_tuple(pt), text, fill = color, font = font)
  return draw_on(f, im)
Exemple #13
0
    def process_message(self, message):
        if not check(message):
            logging.info("invalid message received: " + message + " " + description(message))
            return False

        GPIO.output(LED_PIN, True)
        logging.info(message + " " + description(message))
	time.sleep(0.1)
        GPIO.output(LED_PIN, False)
        return True
Exemple #14
0
    def move(self, pos):
        assert self.is_possible_move(pos), f'impossible pos: {pos}'

        self._positions.append(pos)
        self._board[pos] = self._player

        if not self._result and util.check(self._board, pos):
            self._result = self._player
            return

        self._player = self._player.another()
Exemple #15
0
    def listProperties(self):
        test("list props")
        asset = self.ui.assets.currentItem()
        #group, name = asset.text().split('\\')
        group = self.ui.groups.currentItem().text()
        name = self.ui.assets.currentItem().text()

        # load assets xml file
        self.ui.statusbar.showMessage("Properties of " + group + " " + name)
        dir = os.path.dirname(os.path.abspath(self.path))
        if (group == "objects"):
            group = group[:-1]
            assetPath = os.path.join(dir, group+"s", name+"."+group+".gmx")
            assetFile = open(assetPath)
            self.soup = BeautifulSoup(assetFile, 'lxml')
        elif (group == "scripts"):
            group = group[:-1]
            assetPath = os.path.join(dir, group+"s", name)
            assetFile = open(assetPath)

        # show properties and events
        if (group == "object"):

            self.ui.events.clear()
            for tag in self.soup.find_all("event"):
                self.ui.events.addItem(gmx.eventNumber[tag['eventtype']]) #tag>eventtype lookedup in gmx dictionary
           
            self.ui.objSprite.clear()
            self.ui.objSprite.addItem(self.soup.find("spritename").contents[0])

            self.ui.objMask.clear()
            self.ui.objMask.addItem(self.soup.find("maskname").contents[0])

            self.ui.objParent.clear()
            self.ui.objParent.addItem(self.soup.find("parentname").contents[0])

            util.check(self.ui.objSolid, self.soup.find("solid").contents[0])
            util.check(self.ui.objPhysics, self.soup.find("physicsobject").contents[0])
            util.check(self.ui.objVisible, self.soup.find("visible").contents[0])
            util.check(self.ui.objPersistent, self.soup.find("persistent").contents[0])

            #self.ui.objChildren.clear()
            #for child in gmx.children():
            #    self.ui.objChildren.addItem(child)

        elif (group == "script"):
            self.ui.code.setText(assetFile.read())

        # clean
        try: assetFile.close()
        finally: test("Closed")
Exemple #16
0
def generalize_single_token(grammar, start, k, q, r, command, blacklist):
    # first we replace the token with a temporary key
    gk = GK
    # was there a previous widened char? and if ther wase,
    # do we belong to it?
    char = grammar[k][q][r]
    if r > 0 and grammar[k][q][r - 1][-1] == '+':
        # remove the +
        last_char = grammar[k][q][r - 1][0:-1]
        if last_char in ASCII_MAP and char in ASCII_MAP[last_char]:
            #we are part of the last.
            grammar[k][q][r] = last_char + '+'
            return grammar

    g_ = copy.deepcopy(grammar)
    g_[k][q][r] = gk
    g_[gk] = [[char]]
    #reachable_keys = grammartools.reachable_dict(g_)
    # now, we need a path to reach this.
    fg = grammartools.get_focused_grammar(g_, (gk, []))
    fuzzer = F.LimitFuzzer(fg)
    #skel_tree = find_path_key(g_, start, gk, reachable_keys, fuzzer)
    tree = None
    check = 0
    while tree is None:
        #tree = flush_tree(skel_tree, fuzzer, gk, char)
        #tree = fuzzer.gen_key(grammartools.focused_key(start), depth=0, max_depth=1)
        tree = fuzzer.iter_gen_key(grammartools.focused_key(start),
                                   max_depth=1)
        val = util.check(char, char,
                         '<__CHECK__(%d/%d)>' % (check, MAX_CHECKS), tree,
                         command, char, char)
        check += 1
        if not val:
            tree = None
        if check > MAX_CHECKS:
            print("Exhausted limit for key:%s, rule:%d, token:%d, char:%s" %
                  (k, q, r, char),
                  file=sys.stderr)
            blacklist.append((k, q, r, char))
            #raise "Exhausted limit for key:%s, rule:%d, token:%d, char:%s" % (k, q, r, char)
            return grammar
        # now we need to make sure that this works.

    gen_token = find_max_generalized(tree, char, gk, command)
    if gen_token != char:
        # try widening
        gen_token = find_max_widened(tree, gen_token, gk, command)
    del g_[gk]
    g_[k][q][r] = gen_token
    # preserve the order
    grammar[k][q][r] = gen_token
    return grammar
Exemple #17
0
    def move(self, pos):
        assert self.is_possible_move(pos), 'impossible pos: {pos}'.format(
            pos=pos)

        self._positions.append(pos)
        self._board[pos] = self._player

        if not self._result and util.check(self._board, pos, self.line_length,
                                           self.width, self.height):
            self._result = self._player
            return

        self._player = self._player.another()
Exemple #18
0
    def move(self, pos):
        assert self.is_possible_move(pos), 'impossible pos: {pos}'.format(
            pos=pos)

        #self._positions.append(pos)
        self._board[pos] = self._player

        if not self._result and util.check(self._board, pos):
            self._result = self._player
            return

        self.turn_number += 1
        self._player = self._player.another()
def test_check():
    from util import check
    assert 1 == check("abcde",1,'a') 
    assert 0 == check("abcde",3,'a')
    assert 0 == check("cdefg",1,'b')
    assert 0 == check("cdefg",3,'b')
    assert 1 == check("ccccccccc",2,'c')
    assert 1 == check("ccccccccc",9,'c')
Exemple #20
0
    def policy(self, game):
        from time import time
        if (self._color == 'black' and len(
                util.list_positions(game.board(), renju.Player.NONE)) == 225):
            res = numpy.zeros((225, 1))
            res[112] = 1
            return res.reshape((1, 225))

        board = numpy.copy(-game.board())
        available = numpy.zeros(225)
        checker = numpy.zeros(225)

        for parsed_pos in util.list_positions(game.board(), renju.Player.NONE):
            pos = parsed_pos[0] * 15 + parsed_pos[1]
            parsed_pos = tuple(parsed_pos)

            board[parsed_pos] = 1
            if (util.check(board, parsed_pos)):
                checker[pos] += 1
            board[parsed_pos] = -1
            if (util.check(board, parsed_pos)):
                checker[pos] += 1

            board[parsed_pos] = 0
            available[pos] = 1

        start = time()
        with self._graph.as_default():
            predictions = self._model.predict(board.reshape(1, 15, 15, 1))[0]

        arr = (predictions * available) * (1 + checker)

        code_move = numpy.argmax(arr)
        if (self._verbose):
            print(self._name + ':',
                  util.to_move([code_move // 15, code_move % 15]),
                  time() - start)
        return arr.reshape(1, 225)
Exemple #21
0
def draw_text(im, texts, pts, colors, font_size=None):
    im = rgb_from_gray(im)
    # todo: add fonts, call from draw_rects
    ut.check(len(pts) == len(texts))
    #ut.check((colors is None) or len(colors) == len(texts))
    colors = colors_from_input(colors, (0, 0, 0), len(texts))

    def f(draw):
        if font_size is None:
            font = None
        else:
            #font_name = '/usr/share/fonts/truetype/ttf-liberation/LiberationMono-Regular.ttf'
            font_name = '/usr/share/fonts/truetype/freefont/FreeMono.ttf'
            if not os.path.exists(font_name):
                raise RuntimeError(
                    'need to change hard-coded font path to make this work on other machines'
                )
            font = ImageFont.truetype(font_name, size=font_size)

        for pt, text, color in itl.izip(pts, texts, colors):
            draw.text(ut.int_tuple(pt), text, fill=color, font=font)

    return draw_on(f, im)
Exemple #22
0
	def play(self):
		while True:
			player = self.players[self.turn]
			self.turn = (self.turn + 1) % 2
			opponent = self.players[self.turn]
			with indent(player.indentation):
				puts("Player %s's Turn" % player.player_num)
				guess = player.guess()
				b,c = util.check(opponent.num,guess)
				player.guess_response(guess,b,c)
				if b == 4:
					print "Player %s Won in %s chances..." % (player.player_num,player.chance)
					print "Player %s's Number is %s" % (player.player_num ,player.num)
					break
Exemple #23
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        fname = request.form["fname"]
        lname = request.form["lname"]
        password = request.form["password"]
        sub = request.form["sub"]
        if sub == "Cancel":
            return render_template("login.html")
        if util.check(password) != 0:
            page = "<h1>Logged in</h1>\n"
            page += '<button><a href="/profile/'
            page += fname
            page += "/" + lname
            if util.check(password) == 1:
                page += "/Cats"
            else:
                page += "/Dogs"
            page += '">View Your Profile</a></button>'
            return page
        else:
            error = "Your password did not contain 'cat' or 'dog'."
            return render_template("login.html", error=error)
Exemple #24
0
def login():
    if request.method=="GET":
        return render_template("login.html")
    else:
        fname = request.form["fname"]
        lname = request.form["lname"]
        password = request.form["password"]
        sub = request.form["sub"]
        if sub=="Cancel":
            return render_template("login.html")
        if util.check(password)!=0:
            page = "<h1>Logged in</h1>\n"
            page += '<button><a href="/profile/'
            page += fname
            page += "/" + lname
            if util.check(password)==1:
                page += "/Cats"
            else:
                page += "/Dogs"
            page += '">View Your Profile</a></button>'
            return page
        else:
            error = "Your password did not contain 'cat' or 'dog'."
            return render_template("login.html",error=error)
Exemple #25
0
def check_key(g, gk, start, command):
    fg = G.get_focused_grammar(g, (gk, []))
    fuzzer = F.LimitFuzzer(fg)
    tree = None
    check = 0
    while tree is None:
        tree = fuzzer.iter_gen_key(G.focused_key(start), max_depth=0)
        val = util.check('', '',
                         '<__MINE_CHECK__(%d/%d)>' % (check, MAX_CHECKS), tree,
                         command, '', '')
        check += 1
        if not val:
            tree = None
        if check > MAX_CHECKS:
            print("Exhausted limit for key:%s" % gk, file=sys.stderr)
            return
Exemple #26
0
def _verify_proxy_useful(proxy):
    """
    如果可用: 保留
       不可用: 放入 raw
    :param proxy:
    :return:
    """
    if not redis.hexists(REDIS_KEY_USEFUL, proxy):
        return

    available = check(proxy)
    if available is True:
        pass
    else:
        redis.hdel(REDIS_KEY_USEFUL, proxy)
        redis.hset(REDIS_KEY_RAW, proxy, '1')
Exemple #27
0
    def playout(self, board, temp_high, color):
        gamma = self._gamma

        if (len(util.list_positions(board, renju.Player.NONE)) == 0):
            return 0

        temp_predictions = 0
        if color == 'black':
            with self._black_graph.as_default():
                temp_predictions = self._black_model.predict(board.reshape(
                    1, 15, 15, 1),
                                                             batch_size=1,
                                                             verbose=0)[0]
        else:
            with self._white_graph.as_default():
                temp_predictions = self._white_model.predict(board.reshape(
                    1, 15, 15, 1),
                                                             batch_size=1,
                                                             verbose=0)[0]

        temp_pos = numpy.random.choice(225, p=temp_predictions)
        temp_parsed_pos = numpy.unravel_index(temp_pos, (15, 15))

        if (board[temp_parsed_pos] != 0):
            if (temp_high % 2):
                return gamma**(temp_high - 1)
            else:
                return -gamma**(temp_high - 1)

        board[temp_parsed_pos] = 1
        next_color = 'white'
        if color == 'white':
            next_color = 'black'
            board[temp_parsed_pos] = -1

        if (util.check(board, temp_parsed_pos)):
            if (temp_high % 2):
                return -gamma**(temp_high - 1)
            else:
                return gamma**(temp_high - 1)

        if (temp_high < self._high):
            return self.playout(board, temp_high + 1, next_color)
        return 0
Exemple #28
0
    def simulate_game(self):
        flag = 0
        board, leaf, path, depth = self.selection(flag)

        if flag:
            return path, leaf._player

        if depth >= self._max_depth:
            return path, renju.Player.NONE

        leaf._policy = self._policy.make_pred(board)
        move = np.random.choice(225, p=leaf._policy)
        board[util.to_mtx_coords(move)] = leaf._player
        path.append(move)
        leaf.expand(move)

        if util.check(board, util.to_mtx_coords(move)):
            return path, leaf._player

        return path, self.playout(board, move, depth)
Exemple #29
0
    def selection(self, flag):
        path = []
        depth = 0
        node = self._root
        board = np.copy(self._board)
        while depth < self._max_depth:
            if node.is_leaf():
                return board, node, path, depth

            node._visit_n += 1
            move = self.select(board, node)
            path.append(move)
            if not node._children[move]:
                node.expand(move)
            board[util.to_mtx_coords(move)] = node._player
            if util.check(board, util.to_mtx_coords(move)):
                flag = 1
                return board, node, path, depth

            node = node._children[move]
            depth += 1

        return board, node, path, depth
Exemple #30
0
        def check_state_black(board, pos, checking_pos, temp_prob, temp_high,
                              results):
            # print(board, pos)
            # global max_sum_log, best_move
            temp_high += 1
            parsed_pos = numpy.unravel_index(pos, (15, 15))
            #if (util.check(-board, parsed_pos)):
            #    if self._color == 'black':
            #checking_pos = -1
            #return
            #results[0] = checking_pos
            #results[1] = 0
            #return

            if (temp_high > self._high):
                if (checking_pos not in danger):
                    if (results[checking_pos] < temp_prob):
                        results[checking_pos] = temp_prob
                return

            board[parsed_pos] = -1
            black_predict = 0
            with self._black_graph.as_default():
                black_predict = self._black_model.predict(
                    board.reshape(1, 15, 15, 1))[0]
            top_args_black = numpy.argsort(black_predict)[::-1][:self._width]

            for pos in top_args_black:
                if (util.check(-board, parsed_pos)):
                    if (self._color == 'white'):
                        danger.add(checking_pos)
                        continue
                if checking_pos not in danger:
                    check_state_white(
                        numpy.copy(board), pos, checking_pos,
                        temp_prob + numpy.log(black_predict[pos]), temp_high,
                        results)
Exemple #31
0
                self.visit_neighbours((x, y - 1), m, n, grid)

        if y + 1 <= m - 1:
            if grid[x][y + 1] == '1':
                grid[x][y + 1] = 2
                self.visit_neighbours((x, y + 1), m, n, grid)

    def numIslands(self, grid) -> int:
        m = len(grid)
        if m > 0:
            n = len(grid[0])
        else:
            return 0
        count = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    count = count + 1
                    self.visit_neighbours((i, j), n, m, grid)
        return count


sol = Solution()
check([[["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"],
        ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"]]], [1],
      sol.numIslands)

check([[["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"],
        ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"]]], [3],
      sol.numIslands)
        # loop for all words in para
        for x in re.split("[!?',;. ]", paragraph):
            if not x == '':
                # convert word to lower case
                x = x.lower()

                # remove punch from words Punc - !?',;.
                #x=re.sub("[!?',;.]","",x)

                # add to dict with counter
                if x in count.keys():
                    count[x] += 1
                else:
                    count[x] = 1

        # find max
        max_count = 0
        max_str = ""
        for k in count.keys():
            v = count[k]
            # check against set
            if k not in s:
                if v > max_count:
                    max_count = v
                    max_str = k
        return max_str


sol = Solution()
check(['Bob hit a ball, the hit BALL flew far after it was hit.', ['hit']],
      ['ball'], sol.mostCommonWord)
Exemple #33
0
                if len(a) > 1:
                    # make splits and create new arrays
                    for position in range(1, len(a)):
                        sub1, sub2 = a[0:position], a[position:]
                        di_new = di_old + max(sub1) + max(sub2) - max(a)
                        if di_new < min_possib:
                            n = e.copy()
                            n.remove(a)
                            n.extend([sub1, sub2])
                            q.append((n, di_new))

        return -1 if min_possib == math.inf else min_possib


sol = Solution()
check([[6, 5, 4, 3, 2, 1], 2], [7], sol.minDifficulty_stack)
check([[9, 9, 9], 4], [-1], sol.minDifficulty_stack)
check([[1, 1, 1], 3], [3], sol.minDifficulty_stack)
check([[7, 1, 7, 1, 7, 1], 3], [15], sol.minDifficulty_stack)
check([[11, 111, 22, 222, 33, 333, 44, 444], 6], [843],
      sol.minDifficulty_stack)
check([[3], 1], [3], sol.minDifficulty_stack)
check([[
    143, 446, 351, 170, 117, 963, 785, 76, 139, 772, 452, 743, 23, 767, 564,
    872, 922, 532, 957, 945, 203, 615, 843, 909, 458, 320, 290, 235, 174, 814,
    414, 669, 422, 769, 781, 721, 523, 94, 100, 464, 484, 562, 941
], 5], [1839], sol.minDifficulty_stack)
check([[
    186, 398, 479, 206, 885, 423, 805, 112, 925, 656, 16, 932, 740, 292, 671,
    360
], 4], [1803], sol.minDifficulty_stack)
Exemple #34
0
from util import check

class Solution:
    def findComplement(self, num: int) -> int:
        x=1
        while x-1<num:
            x=x*2
        xor_with=x-1
        return xor_with^num

sol=Solution()
check([5],2,sol.findComplement)
check([1],0,sol.findComplement)
check([20],0,sol.findComplement)
check([1],0,sol.findComplement)
check([1],0,sol.findComplement)
check([1],0,sol.findComplement)
check([1],0,sol.findComplement)
                            min_length = len(path)
                        if child not in traversed:
                            traversed[child] = depth + 1
                            allow = True
                        elif traversed[child] == depth + 1:
                            allow = True
                        if allow:
                            if depth + 1 <= min_length:
                                new_path = path.copy()
                                new_path[child] = True
                                s.append((depth + 1, child, new_path))
        return result


sol = Solution()
check(["hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]], [5],
      sol.findLadders)
check(["hit", "cog", ["hot", "dot", "dog", "lot", "log"]], [[]],
      sol.findLadders)
check([
    "cet", "ism",
    [
        "kid", "tag", "pup", "ail", "tun", "woo", "erg", "luz", "brr", "gay",
        "sip", "kay", "per", "val", "mes", "ohs", "now", "boa", "cet", "pal",
        "bar", "die", "war", "hay", "eco", "pub", "lob", "rue", "fry", "lit",
        "rex", "jan", "cot", "bid", "ali", "pay", "col", "gum", "ger", "row",
        "won", "dan", "rum", "fad", "tut", "sag", "yip", "sui", "ark", "has",
        "zip", "fez", "own", "ump", "dis", "ads", "max", "jaw", "out", "btu",
        "ana", "gap", "cry", "led", "abe", "box", "ore", "pig", "fie", "toy",
        "fat", "cal", "lie", "noh", "sew", "ono", "tam", "flu", "mgm", "ply",
        "awe", "pry", "tit", "tie", "yet", "too", "tax", "jim", "san", "pan",
        "map", "ski", "ova", "wed", "non", "wac", "nut", "why", "bye", "lye",
                emap[x] = True
                continue
            if x in emap:  #and x not in tmap:
                rmap[x] = True
                continue
            '''
            if x in rmap:
                rmap.pop(x)
                tmap[x] = True
                continue
            '''
        return list(rmap)


sol = Solution()
check([[]], [[]], sol.findDuplicates)
check([[4, 3, 2, 7, 8, 2, 3, 1]], [[2, 3], [3, 2]], sol.findDuplicates)
check([[
    1,
    2,
    3,
    4,
    5,
    6,
    21,
    22,
    9,
    10,
    11,
    12,
    13,
    def subsets(self, nums):
        stack=[]
        result=[]
        stack.append([])
        while len(stack)>0:
            item=stack.pop()
            #if item not in result:
            result.append(item)
            not_present=[x for x in nums if x not in item]
            for element in not_present:
                new_list=list(item.copy())
                new_list.append(element)
                new_list.sort()
                new_list=frozenset(new_list)
                stack.append(new_list)
        return result
'''

class Solution:
    def subsets(self, nums):
        output = [[]]
        for num in nums:
            output += [curr + [num] for curr in output]

        return output

sol=Solution()
#check([[1,2,3]],[[3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]], sol.subsets)
#check([[]],[[]], sol.subsets)
check([[1,2,3,4,5,6,7,8,10,0]],[[]], sol.subsets)
Exemple #38
0
 def check_size(x, s): ut.check(x is None or len(x) == len(rects), "%s different size from rects" % s)
 check_size(outlines, 'outlines')