使用简单算法
假设序列只包含0和1.
from collections import Counter
def reorder_4_1(seq):
c = Counter(seq)
q1, r1 = divmod(c[1], 4)
diff = q1 - c[0]
if diff > 0:
return [1,1,1,1,0] * c[0] + [1] * (diff + r1)
else:
return [1,1,1,1,0] * q1 + [1] * r1 + [0] * (-diff)
print( reorder_4_1([1,1,1,1,1,1,1,0,0,0]) )
# [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
Using module itertools
使用the itertools
documentation中的配方roundrobin
:
假设有两组元素交错4:1
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
def interleave_4_1(a, b):
a = iter(a)
b = iter(b)
return roundrobin(a, a, a, a, b)
print(list( interleave_4_1([1,1,1,1,1,1,1],[0,0,0]) ))
# [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
假设序列保证为1和0的列表
from collections import Counter
from itertools import repeat
# def roundrobin...
def reorder_4_1(seq):
c = Counter(seq)
a = repeat(1, c[1])
b = repeat(0, c[0])
return roundrobin(a, a, a, a, b)
print(list( reorder_4_1([1,1,1,1,1,1,1,0,0,0]) ))
# [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]