w3resource

Python: Find the number of combinations

Python Basic - 1: Exercise-62 with Solution

Write a Python program to find the number of combinations that satisfy p + q + r + s = n where n is a given number <= 4000 and p, q, r, s are between 0 to 1000.

Sample Solution:

Python Code:

from collections import Counter
print("Input a positive integer: (ctrl+d to exit)") 
pair_dict = Counter()
for i in range(2001):
  pair_dict[i] = min(i, 2000 - i) + 1 
 
while True:
  try:
    n = int(input())
    ans = 0
    for i in range(n + 1):
      ans += pair_dict[i] * pair_dict[n - i]
    print("Number of combinations of a,b,c,d:",ans) 
  except EOFError:
    break

Sample Output:

Input a positive integer: (ctrl+d to exit)
 252
Number of combinations of a,b,c,d: 2731135

Flowchart:

Flowchart: Python - Find the number of combinations

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program that compute the maximum value of the sum of the passing integers.
Next: Write a Python program which adds up columns and rows of given table as shown in the specified figure.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.