Counting pairs with a sum - fast
Task
Write a function pocet_dvojic(cisla, s) that returns how many pairs of items at different positions of the list cisla add up to s (each pair of positions counts once).
pocet_dvojic([1, 5, 3, 3, 4], 6)returns2(1 + 5 and 3 + 3),pocet_dvojic([2, 2, 2], 4)returns3.
The list may have 100,000 items - comparing every pair is too slow. A dictionary that remembers how many times each number has already appeared helps.
Examples
Call
print(pocet_dvojic([1, 5, 3, 3, 4], 6))
Expected output
2
Call
print(pocet_dvojic([2, 2, 2], 4))
Expected output
3
After you submit, 6 hidden tests will also check your solution: an empty list, an item does not pair with itself, two equal halves, negative numbers and zero, 100,000 different numbers, 100,000 equal numbers.
Python starts the first time you run code.
Ctrl+Enter runs the program. Tab indents. Press Esc, then Tab, to leave the editor.
Input (stdin)
Each line = one call to input().
Output
Hints
Try it yourself first. Each hint reveals a little more - and lowers the reward a little.
Signed out, hints are free - but no XP is awarded either.
Solution
The solution unlocks after the last hint.