当前位置: 首页>>代码示例>>Python>>正文


Python tqdm.trange函数代码示例

本文整理汇总了Python中tqdm.trange函数的典型用法代码示例。如果您正苦于以下问题:Python trange函数的具体用法?Python trange怎么用?Python trange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了trange函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

def main():
    """Main program."""
    answer = 0

    start = time.time()
    max_period = 0
    for index in tqdm.trange(1, 1000):
        period = calculate_period_length(index)
        if period > max_period:
            max_period = period
            answer = index
    end = time.time()
    print("The answer is %d" % answer)
    print("%f seconds elapsed" % (end - start))

    start = time.time()
    max_period = 0
    for index in tqdm.trange(1, 1000):
        period = lambda_decimal_period(index)
        if period > max_period:
            max_period = period
            answer = index
    end = time.time()
    print("The answer is %d" % answer)
    print("%f seconds elapsed" % (end - start))

    import pyperclip
    pyperclip.copy(str(answer))
    print("The answer has been placed in the clipboard.")
开发者ID:jramaswami,项目名称:euler,代码行数:29,代码来源:problem026.py

示例2: trees_are_random

def trees_are_random(filename):
    res_file = filename.replace('_0', '_processed')
    with np.load(filename) as f:
        res, gold = f['res'], f['gold']
    num_trees, num_order, _ = res.shape
    all_trees = list(range(num_trees))
    all_order = list(range(num_order))
    all_pred = np.arange(len(gold))
    nrep = 100
    rate = np.zeros((num_trees//2+1, [j//13-1 for j in range(13, num_order, 13)][-1]+1, 2))
    frac = 1.3
    dropped = []
    for i in trange(1, num_trees+1, 2):
        for j in trange(13, num_order, 13):
            tmp_res = []
            for k in range(nrep):
                trees = random.sample(all_trees, i)
                orders = random.sample(all_order, j-1 if j % 2 == 0 else j)
                if i == 1:
                    vals = res[trees, orders, :]
                else:
                    vals = res[np.ix_(trees, orders, all_pred)].sum(0)
                tmp_res.append(mistakes(vals))
            thre = frac*np.median(tmp_res)
            good = tmp_res < thre
            bad = np.logical_not(good)
            dropped.append((i, j, bad.sum()/nrep))
            rate[(i-1)//2, j//13-1, :] = np.mean(tmp_res), np.std(tmp_res)
            np.savez_compressed(res_file, rate=rate)
开发者ID:daureg,项目名称:magnet,代码行数:29,代码来源:get_error_rate.py

示例3: download

def download(left, right, top, bottom, zoom, filename, maptype="default"):

    for x in trange(left, right + 1):
        for y in trange(top, bottom + 1):
            path = './tiles/%s/%i/%i/%i.png' % (filename, zoom, x, y)
            if not os.path.exists(path):
                _download(x, y, zoom,filename,maptype)
开发者ID:brandonxiang,项目名称:pyMap,代码行数:7,代码来源:pyMap.py

示例4: main

def main():
    bar = trange(60*25)
    bar.write("Working time...")
    for t in bar:
        time.sleep(1)
    bar = trange(60*5)
    bar.write("Break time...")
    for t in bar:
        time.sleep(1)
开发者ID:gngdb,项目名称:pythondoro,代码行数:9,代码来源:start.py

示例5: process_tilenum

def process_tilenum(left, right, top, bottom, zoom, output='output/mosaic.png'):
    """
    download and mosaic by tile number 
    """
    for x in trange(left, right + 1):
        for y in trange(top, bottom + 1):
            path = './tiles/%i/%i/%i.png' % (zoom, x, y)
            if not os.path.exists(path):
                _download(x, y, zoom)
    _mosaic(left, right, top, bottom, zoom, output)
开发者ID:brandonxiang,项目名称:pyMap_GFW,代码行数:10,代码来源:pyMap.py

示例6: test_trange

def test_trange():
    """ Test trange """
    with closing(StringIO()) as our_file:
        for _ in trange(3, file=our_file, leave=True):
            pass
        our_file.seek(0)
        assert '| 3/3 ' in our_file.read()

    with closing(StringIO()) as our_file2:
        for _ in trange(3, file=our_file2, leave=False):
            pass
        our_file2.seek(0)
        assert '| 3/3 ' not in our_file2.read()
开发者ID:CrazyPython,项目名称:tqdm,代码行数:13,代码来源:tests_tqdm.py

示例7: ensemble

def ensemble(validation_base_path, validation_folder, validation_predicted_folder):
    pkl_files = []
    weights = []
    #weight_file = './file_weight_128.csv'
    #weight_file = './file_weight_128_144models.csv'
    #weight_file = './file_weight_128_144_updated models.csv'
    #weight_file = './file_weight_128_144_3rd version models.csv'
    weight_file = './10 best models weights for task 1.csv'
    #weight_file = './5 best models weights for task 1.csv'
    #weight_file = './20 best models weights for task 1.csv'

    with open(weight_file, 'rb') as f:
        rows = csv.reader(f, delimiter=',')
        #next(rows, None)
        for row in rows:
            if '.pkl' in row[0]:
                pkl_files.append(validation_base_path + row[0])
            else:
                pkl_files.append(validation_base_path + row[0] + '.pkl')
            weights.append(float(row[1]))

    print (len(pkl_files))
    print weights
    print np.sum(weights)

    mask_pred_challenge_list = []
    for i in trange(len(pkl_files)):
        mask_pred_challenge = pkl.load(open(pkl_files[i], 'rb'))
        mask_pred_challenge_list.append(mask_pred_challenge)
    mask_pred_challenge_list = np.array(mask_pred_challenge_list)
    print mask_pred_challenge_list.shape
    weights = np.array(weights)

    mask_pred_challenge = np.dot(mask_pred_challenge_list.transpose(1,2,3,0), weights)
    print mask_pred_challenge.shape

    if not os.path.exists(validation_predicted_folder):
        os.makedirs(validation_predicted_folder)

    cutoff = 0.5
    mask_pred_challenge_b = (np.where(mask_pred_challenge>=cutoff, 1, 0) * 255).astype(np.uint8)
    challenge_list = ISIC.list_from_folder(validation_folder)

    for i in trange(len(challenge_list)):
        _, _ = ISIC.show_images_full_sized(challenge_list,
                                           img_mask_pred_array=mask_pred_challenge_b,
                                           image_folder=validation_folder,
                                           mask_folder=None,
                                           index=i,
                                           output_folder=validation_predicted_folder,
                                           plot=False)
开发者ID:minxueric,项目名称:ISIC2018,代码行数:51,代码来源:task1_ensemble_weight.py

示例8: test_trange

def test_trange():
    our_file = StringIO()
    for i in trange(3, file=our_file, leave=True):
        pass
    our_file.seek(0)
    assert '| 3/3 ' in our_file.read()
    our_file.close()

    our_file2 = StringIO()
    for i in trange(3, file=our_file2, leave=False):
        pass
    our_file2.seek(0)
    assert '| 3/3 ' not in our_file2.read()
    our_file2.close()
开发者ID:gcmcom,项目名称:pyFileFixity,代码行数:14,代码来源:tests_tqdm.py

示例9: _mosaic

def _mosaic(left, right, top, bottom, zoom, output='output/mosaic.png'):
    size_x = (right - left + 1) * 256
    size_y = (bottom - top + 1) * 256
    output_im = Image.new("RGBA", (size_x, size_y))

    for x in trange(left, right + 1):
        for y in trange(top, bottom + 1):
            path = './tiles/%i/%i/%i.png' % (zoom, x, y)
            target_im = Image.open(path)
            output_im.paste(target_im, (256 * (x - left), 256 * (y - top)))
    output_path = os.path.split(output)
    if len(output_path) > 1 and len(output_path) != 0:
        if not os.path.isdir(output_path[0]):
            os.makedirs(output_path[0])
    output_im.save(output)
开发者ID:vtronxy,项目名称:pyMap,代码行数:15,代码来源:pyMap.py

示例10: test_iter_overhead_simplebar_hard

def test_iter_overhead_simplebar_hard():
    """Test overhead of iteration based tqdm vs simple progress bar (hard)"""

    total = int(1e4)

    with closing(MockIO()) as our_file:
        a = 0
        with trange(total, file=our_file, leave=True, miniters=1,
                    mininterval=0, maxinterval=0) as t:
            with relative_timer() as time_tqdm:
                for i in t:
                    a += i
        assert a == (total * total - total) / 2.0

        a = 0
        s = simple_progress(_range(total), file=our_file, leave=True,
                            miniters=1, mininterval=0)
        with relative_timer() as time_bench:
            for i in s:
                a += i

    # Compute relative overhead of tqdm against native range()
    try:
        assert time_tqdm() < 2.5 * time_bench()
    except AssertionError:
        raise AssertionError('trange(%g): %f, simple_progress(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
开发者ID:marscher,项目名称:progress_reporter,代码行数:27,代码来源:tests_perf.py

示例11: test_iter_overhead_hard

def test_iter_overhead_hard():
    """Test overhead of iteration based tqdm (hard)"""

    total = int(1e5)

    with closing(MockIO()) as our_file:
        a = 0
        with trange(total, file=our_file, leave=True, miniters=1,
                    mininterval=0, maxinterval=0) as t:
            with relative_timer() as time_tqdm:
                for i in t:
                    a += i
        assert a == (total * total - total) / 2.0

        a = 0
        with relative_timer() as time_bench:
            for i in _range(total):
                a += i
                our_file.write(("%i" % a) * 40)

    # Compute relative overhead of tqdm against native range()
    try:
        assert time_tqdm() < 60 * time_bench()
    except AssertionError:
        raise AssertionError('trange(%g): %f, range(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
开发者ID:marscher,项目名称:progress_reporter,代码行数:26,代码来源:tests_perf.py

示例12: _maybe_generate_and_save

  def _maybe_generate_and_save(self, except_list=[]):
    self.data = {}

    for name, num in self.data_num.items():
      if name in except_list:
        tf.logging.info("Skip creating {} because of given except_list {}".format(name, except_list))
        continue
      path = self.get_path(name)

      if not os.path.exists(path):
        tf.logging.info("Creating {} for [{}]".format(path, self.task))

        x = np.zeros([num, self.max_length, 2], dtype=np.float32)
        y = np.zeros([num, self.max_length], dtype=np.int32)

        for idx in trange(num, desc="Create {} data".format(name)):
          n_nodes = self.rng.randint(self.min_length, self.max_length+ 1)
          nodes, res = generate_one_example(n_nodes, self.rng)
          x[idx,:len(nodes)] = nodes
          y[idx,:len(res)] = res

        np.savez(path, x=x, y=y)
        self.data[name] = TSP(x=x, y=y, name=name)
      else:
        tf.logging.info("Skip creating {} for [{}]".format(path, self.task))
        tmp = np.load(path)
        self.data[name] = TSP(x=tmp['x'], y=tmp['y'], name=name)
开发者ID:huyuxiang,项目名称:tensorflow_practice,代码行数:27,代码来源:data_loader.py

示例13: __init__

    def __init__(self, cache=None, **kwargs):
        super(GTZAN, self).__init__(**kwargs)
        if kwargs.get('conf') is not None:
            conf = kwargs['conf']
            cache = conf.get('cache', None)
        data_set_path = osp.join(DEFAULT_IMAGEST_BASE, self.data_set)
        self.data_set_path = data_set_path
        self.cache = cache
        X, y = parse_anno_file(data_set_path)
        if cache == 'raw':
            import librosa
            from tqdm import trange
            X_new = np.zeros((len(X), 1, 661500, 1))
            for i in trange(len(X)):
                x,_ = librosa.load(osp.join(DEFAULT_DATA_BASE, X[i]))
                x_len = min(661500, len(x))
                X_new[i,:,:x_len,0] = x[:x_len]
        if cache is not None and cache != 'raw':
            X = self.load_cache_X(X, cache)
            if cache == 'mfcc':
                X_new = np.zeros((len(X), X[0].shape[0], 1280, 1))
                for i, x in enumerate(X):
                    x_len = min(x.shape[1], 1280)
                    X_new[i,:,:x_len,0] = x[:,:x_len]
                X = X_new

        # layout_X
        if self.layout_x == 'rel_path':
            self.X = X
        else:
            self.X = self.init_layout_X(X)
        # layout_y
        self.y = self.init_layout_y(y)
开发者ID:randxie,项目名称:gcForest,代码行数:33,代码来源:gtzan.py

示例14: main

def main():
    """Main program."""
    answer = 0

    start_time = time.time()

    # Find next sequence after 1487, 4817, 8147
    for number_1 in tqdm.trange(1488, 9998):
        for index in range(1, (9999 - number_1) / 2):
            number_2 = number_1 + index
            number_3 = number_1 + (2 * index)
            if all([sorted(str(n)) == sorted(str(number_1)) \
                    for n in [number_2, number_3]]) \
            and all([sympy.ntheory.primetest.isprime(n) \
                     for n in [number_1, number_2, number_3]]):
                answer = int(str(number_1) + str(number_2) + str(number_3))
                break

        if answer > 0:
            break

    end_time = time.time()
    print("The answer is %d" % answer)
    print("%f seconds elapsed." % (end_time - start_time))

    import pyperclip
    pyperclip.copy(str(answer))
    print("The answer has been placed in the clipboard.")
开发者ID:jramaswami,项目名称:euler,代码行数:28,代码来源:problem049.py

示例15: adev_at_tau_wrapper

 def adev_at_tau_wrapper(idxs):
   if idxs[0] == 0:
     for i in trange(len(idxs)):
       adev_at_tau(idxs[i])
   else:
     for i in idxs:
       adev_at_tau(i)
开发者ID:ozymandium,项目名称:adic,代码行数:7,代码来源:adev.py


注:本文中的tqdm.trange函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。