有没有一种 pythonic 方法来计算总计整分钟的对
Is there a pythonic way to count the pairs that total up to whole minutes
我正在尝试查找时长加起来为整分钟的歌曲对。给定歌曲长度的示例 [10、50、90、30]。计算不同对的总数。我预计 return 为 2,因为第一对和第二对为 60 秒,第三对和第四对为 120 秒。但我得到的是一对。
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()
有不同但更简单的算法:
- 创建包含 60 个桶的数组。
- 对于列表中的每个
value
运行 counts[value % k] += 1
- Sum
min(counts[n], counts[(n + k) % k])
(奇怪的计算而不是仅仅使用 k - n
是为了处理特殊情况 0
)
我会使用 itertools.combinations
in conjunction with the modulo operator:
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()
当我 运行 使用不同输入的代码时,这对我来说是正确的。
我正在尝试查找时长加起来为整分钟的歌曲对。给定歌曲长度的示例 [10、50、90、30]。计算不同对的总数。我预计 return 为 2,因为第一对和第二对为 60 秒,第三对和第四对为 120 秒。但我得到的是一对。
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()
有不同但更简单的算法:
- 创建包含 60 个桶的数组。
- 对于列表中的每个
value
运行counts[value % k] += 1
- Sum
min(counts[n], counts[(n + k) % k])
(奇怪的计算而不是仅仅使用k - n
是为了处理特殊情况0
)
我会使用 itertools.combinations
in conjunction with the modulo operator:
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()
当我 运行 使用不同输入的代码时,这对我来说是正确的。