【问题标题】:Is there a pythonic way to count the pairs that total up to whole minutes有没有一种pythonic方法来计算总计长达整分钟的对
【发布时间】:2020-04-21 11:00:48
【问题描述】:

我正在尝试查找时长总计为整分钟的歌曲对。给定歌曲长度 [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()

【问题讨论】:

  • 你的“一整分钟”检查是这里的诀窍——你熟悉检查一个数字是否能被另一个数字整除的过程吗?
  • 您正在测试总和为 60,而不是“整分钟”。
  • 检查(songs[i] +songs[j]) % k == 0...
  • 你的意思是sum(1 for c in itertools.combinations(songs, 2) if sum(c) % k == 0) 吗?
  • 对于[10, 50, 50][20, 40, 20, 40],您希望得到什么答案?

标签: python-3.x counting


【解决方案1】:

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

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

【讨论】:

  • 打败我。我打算建议使用Counter,然后将n(k - n) 的存储桶相乘
  • @MadPhysicist 我假设@Levia 只想使用每首“歌曲”一次,这就是为什么min 调用而不是乘法。如果他们想要可能的组合数量,那么乘法将是解决方案。
  • 有道理。
【解决方案2】:

我会将itertools.combinationsmodulo 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

【讨论】:

  • 问题是这个有O(n^2)的复杂性,而它可以在O(n)中完成。
【解决方案3】:

您只需更改一行并从函数定义中删除 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()

当我使用不同的输入运行代码时,这对我来说可以正常工作。

【讨论】:

    猜你喜欢
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    相关资源
    最近更新 更多