Created
July 3, 2019 07:08
-
-
Save mkitti/c78e738621cd39d0e58e7836d0f6f86e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# https://twitter.com/loicaroyer/status/1146173537658404864 | |
# | |
# #Python Twitter Challenge | |
# Given a list of integers u=[a_0, ..., a_m] | |
# find the set of indices {i_0, ..., i_n} for that list such that the product | |
# u[i_0]* ... *u[i_n] is the closest to a given integer N. | |
# The shortest and most #elegant solution wins. | |
# (standard libs allowed) | |
# | |
# 4:47 PM - 2 Jul 2019 | |
# Mark Kittisopikul, Ph.D. | |
# July 3rd, 2019 | |
# Northwestern University | |
import numpy as np | |
import itertools | |
from functools import reduce | |
def find_closest_product_factors(N,u): | |
factors = u[u != 1] | |
reps = int(np.ceil(np.log(N)//np.log(np.min(factors)))) | |
combinations = reduce(itertools.chain, | |
map(lambda r:itertools.combinations_with_replacement(factors,r+1), | |
range(reps))) | |
u_i = min(combinations, | |
key=lambda c: np.abs(N-np.array(c).prod())) | |
i = list(map(lambda ui: np.where(u == ui)[0][0],u_i)) | |
return i,u_i | |
u = np.array([2,3,5,9,17]) | |
find_closest_product_factors(72,u) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment