Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- from itertools import combinations
- from functools import reduce
- from operator import mul
- from sys import exit
- # Given a whole number > 0 for TARGET, and a set of whole numbers > 0 that are divisors of TARGET. Is there a combination of divisors in SET that have a total product equivalent to TARGET?
- TARGET = int(input('enter target product: ' ))
- SET = input('Enter numbers: ').split(',')
- SET = list(set([int(a) for a in SET]))
- # Using two-sum solution for two-product
- two_prod_dict = {}
- for a in range(0, len(SET)):
- if TARGET//int(SET[a]) in two_prod_dict:
- print('YES')
- exit(0)
- else:
- two_prod_dict[int(SET[a])] = a
- # creating a set of all whole number divisors
- divisors = set()
- for i in SET:
- if TARGET % i == 0:
- divisors.add(i)
- # Divisors are sorted in ascending order.
- # so that max_combo can correctly select
- # the largest possible combination size.
- divisors = sorted(divisors)
- if TARGET in divisors:
- print('YES')
- exit(0)
- # finds the maximum combination size
- # Simply multiplies each I in divisors
- # until reaches the closest
- # value without going over.
- # A combination's total product cannot be larger
- # than the TARGET.
- max_combo = []
- for a in divisors:
- max_combo.append(a)
- if reduce(mul,max_combo) >= TARGET:
- if reduce(mul,max_combo) > TARGET:
- max_combo.pop()
- break
- else:
- break
- # Using any other divisor will go over TARGET.
- # To save running time, do it only one time.
- for X in combinations(divisors, len(max_combo)):
- if reduce(mul, X) == TARGET:
- print('YES')
- exit(0)
- else:
- break
- # I'm hoping that smaller solutions
- # are more likely than larger solutions so start
- # with the smallest and work your way up.
- for A in range(3, len(max_combo) + 1):
- for X in combinations(divisors, A):
- if reduce(mul, X) == TARGET:
- print('YES',X)
- exit(0)
- print('NO')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement