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


Python itertools.accumulate方法代码示例

本文整理汇总了Python中itertools.accumulate方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.accumulate方法的具体用法?Python itertools.accumulate怎么用?Python itertools.accumulate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在itertools的用法示例。


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

示例1: counting_sort

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def counting_sort(a: List[int]):
    if len(a) <= 1: return
    
    # a中有counts[i]个数不大于i
    counts = [0] * (max(a) + 1)
    for num in a:
        counts[num] += 1
    counts = list(itertools.accumulate(counts))

    # 临时数组,储存排序之后的结果
    a_sorted = [0] * len(a)
    for num in reversed(a):
        index = counts[num] - 1
        a_sorted[index] = num
        counts[num] -= 1
    
    a[:] = a_sorted 
开发者ID:wangzheng0822,项目名称:algo,代码行数:19,代码来源:counting_sort.py

示例2: _linux

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def _linux(args, uxy_args):
  proc = base.launch(uxy_args, ['netstat', '--inet'] + args[1:])
  # Skip header line.
  proc.readline()
  hdr = proc.readline()
  parts = re.split("(\s+)", hdr)
  pos = [len(p) for p in list(itertools.accumulate(parts))]
  fmt = base.Format("PROTO  RECVQ  SENDQ  LOCAL            REMOTE                      STATE")
  base.writeline(fmt.render())
  for ln in proc:
    fields = []
    fields.append(ln[0:pos[0]].strip())
    fields.append(ln[pos[0]:pos[2]].strip())
    fields.append(ln[pos[2]:pos[4]].strip())
    fields.append(ln[pos[4]:pos[8]].strip())
    fields.append(ln[pos[8]:pos[13]].strip())
    fields.append(ln[pos[13]:].strip())
    fields = [base.encode_field(f) for f in fields]
    base.writeline(fmt.render(fields))
  return proc.wait() 
开发者ID:sustrik,项目名称:uxy,代码行数:22,代码来源:uxy_netstat.py

示例3: is_valid_program

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def is_valid_program(self,p):
        """checks whether program p makes a syntactically valid tree.

        checks that the accumulated program length is always greater than the
        accumulated arities, indicating that the appropriate number of arguments is
        alway present for functions. It then checks that the sum of arties +1
        exactly equals the length of the stack, indicating that there are no
        missing arguments.
        """
        # print("p:",p)
        arities = list(a.arity[a.in_type] for a in p)
        accu_arities = list(accumulate(arities))
        accu_len = list(np.arange(len(p))+1)
        check = list(a < b for a,b in zip(accu_arities,accu_len))
        # print("accu_arities:",accu_arities)
        # print("accu_len:",accu_len)
        # print("accu_arities < accu_len:",accu_arities<accu_len)
        return all(check) and sum(a.arity[a.in_type] for a in p) +1 == len(p) and len(p)>0 
开发者ID:lacava,项目名称:few,代码行数:20,代码来源:variation.py

示例4: column_keymap

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def column_keymap(self):
        """ Returns keymap and keystates used in column mode """
        keystates = set()

        shortcuts = self.cp.items('column_keymap')
        keymap_dict = dict(shortcuts)

        for combo, action in shortcuts:
            # add all possible prefixes to keystates
            combo_as_list = re.split('(<[A-Z].+?>|.)', combo)[1::2]
            if len(combo_as_list) > 1:
                keystates |= set(accumulate(combo_as_list[:-1]))

            if action in ['pri', 'postpone', 'postpone_s']:
                keystates.add(combo)

            if action == 'pri':
                for c in ascii_lowercase:
                    keymap_dict[combo + c] = 'cmd pri {} ' + c

        return (keymap_dict, keystates) 
开发者ID:bram85,项目名称:topydo,代码行数:23,代码来源:Config.py

示例5: test_accumulate

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def test_accumulate():
    if not six.PY3:
        raise SkipTest()
    yield verify_same, accumulate, itertools.accumulate, None, [5, 4, 9]
    yield verify_same, accumulate, itertools.accumulate, None, ['a', 'b', 'c']
    yield (verify_same, accumulate, itertools.accumulate, None,
           [[1], [2], [3, 4]])
    yield (verify_same, accumulate, itertools.accumulate, None, [9, 1, 2],
           sub)
    yield verify_pickle, accumulate, itertools.accumulate, 3, 1, [5, 4, 9]
    yield verify_pickle, accumulate, itertools.accumulate, 3, 0, [5, 4, 9]
    yield (verify_pickle, accumulate, itertools.accumulate, 3, 2,
           ['a', 'b', 'c'])
    yield (verify_pickle, accumulate, itertools.accumulate, 2, 1,
           ['a', 'b', 'c'])
    yield (verify_pickle, accumulate, itertools.accumulate, 3, 1,
           [[1], [2], [3, 4]])
    yield (verify_pickle, accumulate, itertools.accumulate, 2, 1,
           [9, 1, 2], sub) 
开发者ID:mila-iqia,项目名称:picklable-itertools,代码行数:21,代码来源:__init__.py

示例6: fracKnapsack

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def fracKnapsack(vl, wt, W, n):
    """
    >>> fracKnapsack([60, 100, 120], [10, 20, 30], 50, 3)
    240.0
    """

    r = list(sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True))
    vl, wt = [i[0] for i in r], [i[1] for i in r]
    acc = list(accumulate(wt))
    k = bisect(acc, W)
    return (
        0
        if k == 0
        else sum(vl[:k]) + (W - acc[k - 1]) * (vl[k]) / (wt[k])
        if k != n
        else sum(vl[:k])
    ) 
开发者ID:TheAlgorithms,项目名称:Python,代码行数:19,代码来源:fractional_knapsack.py

示例7: choices

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def choices(self, population, weights=None, *, cum_weights=None, k=1):
        """Return a k sized list of population elements chosen with replacement.

        If the relative weights or cumulative weights are not specified,
        the selections are made with equal probability.

        """
        random = self.random
        if cum_weights is None:
            if weights is None:
                _int = int
                total = len(population)
                return [population[_int(random() * total)] for i in range(k)]
            cum_weights = list(_itertools.accumulate(weights))
        elif weights is not None:
            raise TypeError('Cannot specify both weights and cumulative weights')
        if len(cum_weights) != len(population):
            raise ValueError('The number of weights does not match the population')
        bisect = _bisect.bisect
        total = cum_weights[-1]
        return [population[bisect(cum_weights, random() * total)] for i in range(k)]

## -------------------- real-valued distributions  -------------------

## -------------------- uniform distribution ------------------- 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:27,代码来源:random.py

示例8: test_accumulate

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def test_accumulate(self):
        secint = mpc.SecInt()
        r = range(1, 9)
        x = [secint(i) for i in r]
        for acc in itertools.accumulate, mpyc.mpctools.accumulate:
            self.assertEqual(mpc.run(mpc.output(list(acc(x)))),
                             list(itertools.accumulate(r)))
            self.assertEqual(mpc.run(mpc.output(list(acc(x, mpc.mul)))),
                             list(itertools.accumulate(r, operator.mul)))
            self.assertEqual(mpc.run(mpc.output(list(acc(x, mpc.min)))),
                             list(itertools.accumulate(r, min)))
            self.assertEqual(mpc.run(mpc.output(list(acc(x, mpc.max)))),
                             list(itertools.accumulate(r, max)))
        a = secint(10)
        self.assertEqual(mpc.run(mpc.output(list(acc(itertools.repeat(a, 5), mpc.mul, secint(1))))),
                         [1, 10, 10**2, 10**3, 10**4, 10**5]) 
开发者ID:lschoe,项目名称:mpyc,代码行数:18,代码来源:test_mpctools.py

示例9: select

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def select(self, population, fitness):
        ''' Select a pair of parent using FPS algorithm.

        :param population: Population where the selection operation occurs.
        :type population: :obj:`gaft.components.Population`

        :return: Selected parents (a father and a mother)
        :rtype: list of :obj:`gaft.components.IndividualBase`
        '''
        # Normalize fitness values for all individuals.
        fit = population.all_fits(fitness)
        min_fit = min(fit)
        fit = [(i - min_fit) for i in fit]

        # Create roulette wheel.
        sum_fit = sum(fit)
        wheel = list(accumulate([i/sum_fit for i in fit]))

        # Select a father and a mother.
        father_idx = bisect_right(wheel, random())
        father = population[father_idx]
        mother_idx = (father_idx + 1) % len(wheel)
        mother = population[mother_idx]

        return father, mother 
开发者ID:PytLab,项目名称:gaft,代码行数:27,代码来源:roulette_wheel_selection.py

示例10: set_row_heights

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def set_row_heights(self, row_heights = None, canvas_positions = False, reset = False, verify = False):
        if reset:
            self.MT.reset_row_positions()
            return
        if isinstance(row_heights, list):
            qmin = self.MT.min_rh
            if canvas_positions:
                if verify:
                    self.MT.row_positions = list(accumulate(chain([0], (height if qmin < height else qmin
                                                                        for height in [x - z for z, x in zip(islice(row_heights, 0, None),
                                                                                                             islice(row_heights, 1, None))]))))
                else:
                    self.MT.row_positions = row_heights
            else:
                if verify:
                    self.MT.row_positions = [qmin if z < qmin or not isinstance(z, int) or isinstance(z, bool) else z for z in row_heights]
                else:
                    self.MT.row_positions = list(accumulate(chain([0], (height for height in row_heights)))) 
开发者ID:ragardner,项目名称:tksheet,代码行数:20,代码来源:_tksheet.py

示例11: _get_lengths

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def _get_lengths(self) -> List[int]:
        return list(accumulate(len(d) for d in self._datasets)) 
开发者ID:tofunlp,项目名称:lineflow,代码行数:4,代码来源:core.py

示例12: test_supports_random_access_lazily

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def test_supports_random_access_lazily(self):
        self.assertSequenceEqual(self.data, list(self.base) * self.n)
        expected_lengths = list(itertools.accumulate(len(self.base) for _ in range(self.n)))
        self.assertListEqual(self.data._lengths, expected_lengths)
        self.assertListEqual(self.data._offsets, [0] + expected_lengths[:-1]) 
开发者ID:tofunlp,项目名称:lineflow,代码行数:7,代码来源:test_core.py

示例13: random_walk_faster

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def random_walk_faster(n=1000):
    from itertools import accumulate
    # Only available from Python 3.6
    steps = random.choices([-1,+1], k=n)
    return [0]+list(accumulate(steps)) 
开发者ID:ASPP,项目名称:ASPP-2018-numpy,代码行数:7,代码来源:random-walk.py

示例14: min_dist

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def min_dist(weights: List[List[int]]) -> int:
    """Find the minimum weight path from the weights matrix."""
    m, n = len(weights), len(weights[0])
    table = [[0] * n for _ in range(m)]
    # table[i][j] is the minimum distance (weight) when
    # there are i vertical moves and j horizontal moves
    # left.
    table[0] = list(accumulate(reversed(weights[-1])))
    for i, v in enumerate(accumulate(row[-1] for row in reversed(weights))):
        table[i][0] = v
    for i in range(1, m):
        for j in range(1, n):
            table[i][j] = weights[~i][~j] + min(table[i - 1][j], table[i][j - 1])
    return table[-1][-1] 
开发者ID:wangzheng0822,项目名称:algo,代码行数:16,代码来源:min_dist.py

示例15: __init__

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import accumulate [as 别名]
def __init__(self, stage_interval, 
                        dynamic_batch_size, 
                        make_dataset_func, 
                        make_iterator_func, 
                        **kwargs):
        self.stage_interval = stage_interval
        self.dynamic_batch_size = dynamic_batch_size
        self._make_dataset_func = make_dataset_func
        self._make_iterator_func = make_iterator_func

        # Padding to the length + 1 so all calculation (such as self.ratio_in_stage)
        # remains valid when stage = max_stage
        self.dynamic_batch_count = list(map(lambda bs: (stage_interval + bs - 1) // bs, self.dynamic_batch_size)) + [1]
        self.dynamic_batch_count_previous = list(accumulate([0] + self.dynamic_batch_count))

        self.stage_int = 0
        self.counter_batch = 0

        self._iterators = {}
        self._datasets = {}

        self.total_batch = sum(self.dynamic_batch_count)

        if 'debug_start_instance' in kwargs:
            debug_start_instance = kwargs['debug_start_instance']
            while self.total_instance < debug_start_instance:
                self.tick_counter() 
开发者ID:pfnet-research,项目名称:chainer-stylegan,代码行数:29,代码来源:updater.py


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