Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Use combinations to count pairs

Count unordered pairs with a target sum using itertools.combinations. Practice enumerating unique index pairs.

Python practice10 minModules & Standard LibraryBeginnerLast updated March 23, 2026

Problem statement

Given a list of numbers and a target value, count how many unique unordered pairs (i < j) of elements sum exactly to the target. Use itertools.combinations to iterate over index pairs or element pairs to ensure each unordered pair is considered exactly once. Return the count as an integer.

Task

Implement a function that counts how many unique unordered pairs of elements sum to a target, using itertools.combinations.

Examples

Duplicate values forming pairs

Input

count_pairs_with_sum([1, 2, 3, 2], 4)

Output

2

Pairs: 1+3 and 2+2 (the two different 2s form one pair).

Input format

A list of numbers and an integer/number target passed as count_pairs_with_sum(nums, target).

Output format

An integer count of unique unordered pairs whose sum equals the target.

Constraints

Use itertools.combinations to avoid double-counting. The list length may be up to a few thousand; an O(n^2) approach will be fine for beginner-sized inputs, but be mindful of performance.

Samples

Sample 1

Input

count_pairs_with_sum([2, 2, 2], 4)

Output

3

Three unordered pairs can be formed from three 2s: choose any two of them.