2 回答

TA貢獻1804條經(jīng)驗 獲得超2個贊
您實際上是在嘗試將您的數(shù)字列表分組到塊中,其中每個k數(shù)字與該塊中另一個數(shù)字的距離小于。因為我不擅長解釋事情,讓我們看一個例子:
bacteria = [101, 53, 42, 102, 101, 55, 54]
K = 1
首先,我們要對該列表進行排序,以便數(shù)字按大小排列:
[102, 101, 101, 55, 54, 53, 42]
現(xiàn)在我們遍歷列表并在每次較大的細菌無法吞下較小的細菌時創(chuàng)建一個新的數(shù)字塊:
[[102, 101, 101], [55, 54, 53], [42]]
最后我們計算chunk的數(shù)量,從而得到想要的結果:3。
代碼:
def micro_world(bacteria, k):
# sort the list descendingly
bacteria = sorted(bacteria, reverse=True)
# loop over the list but skip all the "swallowed" bacteria
i = 0
result = 0
while i < len(bacteria):
bacterium_size = bacteria[i]
# while the difference between the numbers is <= k, the smaller
# bacterium is swallowed
bigger_bacterium_exists = False
while i+1 < len(bacteria):
difference = bacterium_size - bacteria[i+1]
# if the difference is too big, it can't be swallowed
if difference > k:
break
# if there are two bacteria of the same size, they can't swallow
# each other. But if a bigger bacterium exists, it can swallow
# them both
if difference == 0 and not bigger_bacterium_exists:
break
# all conditions are met, the bacterium is swallowed
bacterium_size = bacteria[i+1]
i += 1
bigger_bacterium_exists = True
# at this point, the bacterium has swallowed everything it can.
# Increment the result counter and move on to the next bacterium.
result += 1
i += 1
return result

TA貢獻1825條經(jīng)驗 獲得超4個贊
這是一個使用的解決方案numpy:
import numpy as np
def micro_world(bacteria, K):
# convert bacteria list to a numpy array:
bacteria = np.asarray(bacteria)
# sort array and remember the indices used for sorting:
sarg = np.argsort(bacteria)
sortedbac = bacteria[sarg]
# compute differences between adjacent elements:
diff = np.ediff1d(sortedbac, K + 1)
# throw away elements that are too close to neighbors
# (find indices of the elements to keep):
idx = np.flatnonzero(diff > K)
# create a new list that meets selection criteria:
return bacteria[np.sort(sarg[idx])]
這是一個“純”的 Python 實現(xiàn):
def micro_world(bacteria, K):
# sort array and remember the indices used for sorting:
sarg = [i[0] for i in sorted(enumerate(bacteria), key=lambda x: x[1])]
sortedbac = [bacteria[i] for i in sarg]
# compute differences between adjacent elements:
diff = [j - i for i, j in zip(sortedbac[:-1], sortedbac[1:])] + [K + 1]
# throw away elements that are too close to neighbors
# (find indices of the elements to keep):
idx = [i for i, v in enumerate(diff) if v > K]
# create a new list that meets selection criteria:
return [bacteria[i] for i in sorted([sarg[i] for i in idx])]
如果你只對元素的數(shù)量感興趣,而不對元素本身感興趣,那么你可以修改 ie 第二個版本,如下所示:
def micro_world(bacteria, K):
sortedbac = sorted(bacteria)
diff = [j - i for i, j in zip(sortedbac[:-1], sortedbac[1:])] + [K + 1]
return sum(1 for v in diff if v > K)
在numpy隨后的版本將成為:
def micro_world(bacteria, K):
return np.sum(np.ediff1d(np.sort(bacteria), K + 1) > K)
添加回答
舉報