本文整理匯總了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
示例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()
示例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
示例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)
示例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)
示例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])
)
示例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 -------------------
示例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])
示例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
示例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))))
示例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))
示例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])
示例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))
示例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]
示例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()