Is there a pythonic way to count the pairs that total up to whole minutes

I'm trying to find pairs of songs with durations that add up to whole minutes. Example given song lengths [10, 50, 90, 30]. Calculate the total number of different pairs. I'm expecting a return of 2 since the first and second pair to 60 seconds and the third and fourth songs pair to 120. But I'm instead getting 1 pair.

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()
5

3 Answers

There is different, and much simpler algorithm:

  1. Create array with 60 buckets.
  2. For each value in list run counts[value % k] += 1
  3. Sum min(counts[n], counts[(n + k) % k]) (the weird calculation instead of just using k - n is to handle special case 0)
3

I'd use the 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
1

You can make your code work correctly with only changing a line and deleting the k parameter from your function definiton like this:

 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()

This works correctly for me when I run the code with different inputs.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like