Problem 142328 · easy · Level 01 Prerequisites & Setup

Quiz Partners on Target

nested loops · lists · indexing

For the buzzer round of a quiz, players team up in twos, and a pair qualifies when their two scores add up to exactly target (penalties can push a score below zero). The scores are in nums. Write a function count_pairs(nums, target) that returns how many qualifying pairs can be formed.

A pair is two different positions i and j with i < j, so each pair is counted once, never once in each order, and nobody pairs with themselves. Two players who happen to have the same score are still two different players.

Examples

Input:  nums = [1, 2, 3, 4], target = 5
Output: 2
Explanation: 1 + 4 and 2 + 3.
Input:  nums = [1, 1, 1], target = 2
Output: 3
Explanation: Positions (0,1), (0,2) and (1,2) are three different pairs.
Input:  nums = [1, 2, 3], target = 10
Output: 0

Constraints

  • 0 <= len(nums) <= 50
  • -100 <= nums[i], target <= 100

Goals

  • Write one loop inside another and reason about which runs when
  • Use range(len(nums)) to loop over positions rather than values
  • Avoid counting the same pair twice by starting the inner loop after the outer index
Starting Python…