Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Last active October 15, 2017 03:07
Show Gist options
  • Select an option

  • Save PM2Ring/f051ab09f9074ab5a378fa30f4141352 to your computer and use it in GitHub Desktop.

Select an option

Save PM2Ring/f051ab09f9074ab5a378fa30f4141352 to your computer and use it in GitHub Desktop.
Find combinations of integers from 3 lists that sum to the items in a target list
#!/usr/bin/env python3
''' Find combinations of integers from 3 lists that sum to the items in a target list
https://gist.github.com/PM2Ring/f051ab09f9074ab5a378fa30f4141352
Written by PM 2Ring 2017.10.15
'''
from itertools import product
from random import seed, sample
seed(42)
# The highest number in the target list
target_high = 18
# Source lists size
size = 6
# The highest number in the source lists
source_high = 10
# Make the target set
target_range = range(1, target_high + 1)
targets = set(target_range)
# Make three random source lists of unique numbers
sources = []
source_range = range(1, source_high + 1)
sources = [sorted(sample(source_range, size)) for _ in range(3)]
sources.sort()
print('Source lists:', *sources, sep='\n', end='\n\n')
# Use the first 2 sources lists to make sums and then pair those sums
# with the numbers in the last sources list to search for target numbers
last = sources[-1]
found = {}
for a, b in product(*sources[:2]):
s = a + b
hi = max(targets)
if s > hi:
continue
# Combine this pair with each item in last
for c in last:
t = s + c
if t > hi:
break
if t in targets:
targets.remove(t)
row = (a, b, c)
found[t] = row
#print(row, t)
for t in target_range:
if t in found:
print(t, found[t])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment