有没有一种 pythonic 方法来计算总计长达整分钟的对



我正在尝试找到持续时间加起来整整分钟的歌曲对。示例给定歌曲长度 [10, 50, 90, 30]。计算不同对的总数。我预计返回 2,因为第一对和第二对到 60 秒,第三和第四首歌曲对到 120。但我反而得到了 1 双。

def pair_with_target_sum(songs, k):
n = len(songs)
count = 0
for i in range(0, n):
for j in range(i + 1, n):
if songs[i] + songs[j] == k:
count += 1
return count
def main():
print(pair_with_target_sum([10, 50, 90, 30], 60))
print(pair_with_target_sum([30, 20, 150, 100, 40], 60))
main()

有不同的,但更简单的算法:

  1. 创建包含 60 个存储桶的数组。
  2. 对于列表中的每个value运行counts[value % k] += 1
  3. 总和min(counts[n], counts[(n + k) % k])(奇怪的计算而不是只使用k - n是为了处理特殊情况0(

我会将itertools.combinations与模运算符结合使用:

from itertools import combinations
def f(songs):
count = 0
for pair in combinations(songs, 2):
if sum(pair) % 60 == 0:
count += 1
return count

只需更改一行并从函数定义中删除 k 参数,即可使代码正常工作,如下所示:

def pair_with_target_sum(songs):
n = len(songs)
count = 0
for i in range(0, n):
for j in range(i + 1, n):
if (songs[i] + songs[j]) % 60 == 0:
count += 1
return count
def main():
print(pair_with_target_sum([10, 50, 90, 30]))
print(pair_with_target_sum([30, 20, 150, 100, 40]))
print(pair_with_target_sum([60, 60, 60]))
main()

当我使用不同的输入运行代码时,这对我有用。

最新更新