about summary refs log tree commit diff
path: root/scratch/facebook/moderate/find-pairs-for-sum.py
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2020-11-16T17·12+0000
committerWilliam Carroll <wpcarro@gmail.com>2020-11-16T17·12+0000
commitff08b723dbb66fc9336dffe7fef4c09f55a07a5b (patch)
tree42881d0e8a3c6586dae4236e7f80981d4f47c890 /scratch/facebook/moderate/find-pairs-for-sum.py
parent92ab94943ee51010dbe45b7ae86211dc8a5bd37f (diff)
Solve "find pairs for sum"
I have encountered this problem 3x in the wild thus far:
  1. www.InterviewCake.com
  2. Cracking the Coding Interview
  3. www.Pramp.com
Diffstat (limited to 'scratch/facebook/moderate/find-pairs-for-sum.py')
-rw-r--r--scratch/facebook/moderate/find-pairs-for-sum.py19
1 files changed, 19 insertions, 0 deletions
diff --git a/scratch/facebook/moderate/find-pairs-for-sum.py b/scratch/facebook/moderate/find-pairs-for-sum.py
new file mode 100644
index 000000000000..69c2fc431296
--- /dev/null
+++ b/scratch/facebook/moderate/find-pairs-for-sum.py
@@ -0,0 +1,19 @@
+import random
+
+def find_pairs(xs, n):
+    """
+    Return all pairs of integers in `xs` that sum to `n`.
+    """
+    seeking = set()
+    result = set()
+    for x in xs:
+        if x in seeking:
+            result.add((n - x, x))
+        else:
+            seeking.add(n - x)
+    return result
+
+xs = [random.randint(1, 10) for _ in range(10)]
+n = random.randint(1, 10) + random.randint(1, 10)
+print("Seeking all pairs in {} for {}...".format(xs, n))
+print(find_pairs(xs, n))