-
Notifications
You must be signed in to change notification settings - Fork 0
/
royer_closest_product.py
427 lines (322 loc) · 11.8 KB
/
royer_closest_product.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# coding: utf-8
# # Closest Product Python Twitter Challenge
#
# https://twitter.com/loicaroyer/status/1146173537658404864
#
# 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)
# ## Setup
# In[1]:
import numpy as np
import itertools as it
# In[2]:
# Setup inputs
# Use same inputs as randomly generated by @james_t_webber
# https://twitter.com/james_t_webber/status/1146203142079410178
m = 20
N = 797
u = np.array([5,9,19,22,25,27,28,31,33,34,36,43,44,68,72,81,86,92,96,98])
print('N: ',N)
print('u: ',u)
# ## Brute Force Method
# Calculate all the products and select the closest one. This takes on the order of seconds.
# In[3]:
# Brute Force code by @james_t_webber adapted into a function
# This version computes the products of all combinations of u
# without repetition. Changed m = u.size
# https://twitter.com/james_t_webber/status/1146210405368266752
def closest_product_brute_force(N,u):
i = min(
map(np.array, it.product([False, True],repeat=u.size)),
key=lambda i:np.abs(N-u[i].prod())
)
i = np.nonzero(i)[0]
return i
# In[4]:
get_ipython().magic('timeit closest_product_brute_force(N,u)')
i = closest_product_brute_force(N,u)
print('i: ',i)
print('u[i]: ',u[i])
print('u[i].prod(): ',u[i].prod())
# ## Speed-up Using Short Circuiting and Divisors
# Rather than computing all the product of all the combinations, we just need to compute the products of the integers closest to N. Once we find such a product we can stop.
#
# To do this, we iterate over the integers closest to N starting from N working outwards.
# * Call each integer M.
# * Figure out which elements of u are divisors of M.
# * Compute the possible combinations of those divisors.
# * Compute the product of those divisor combinations.
# * Stop (short-circuit) if the product equals M
# * Choose M one step farther from N
#
# To implement this we will use a special type of iterable called a generator. Generators use lazy evaluation which defers evaluation until the next element of the iterable is needed. This will help us define the iteration without having to actually compute anything until we need it.
#
# This takes 100s of microseconds, a 10^4 speed-up over the brute force method for the given input.
# In[5]:
def closest_product_no_repetition(N,u):
# Setup generator for product targets "M"
Mg = it.chain.from_iterable(
(
(N-y,N+y) if y != 0 else (N,)
for y in range(min(abs(N-u))+1)
)
)
# For each M construct a list of divisors
# Each generated element is a tuple: (divisors,M)
divisors = filter(
lambda f: f[0].size > 0,
(
(u[M % u == 0],M) for M in Mg
)
)
# For each tuple of (divisors,M),
# generate combinations of divisors
divisor_combinations = it.chain.from_iterable(zip(
it.chain.from_iterable(
(it.combinations(d,r+1) for r in range(d.size))
),
it.repeat(M)
) for d,M in divisors)
# We want to use it.takewhile, but we need info on the divisor combination that met the condition
# Use tee to duplicate the iterator and advance it by one
g = it.tee(divisor_combinations)
u_i = next(g[1])
g = zip(*g)
# Up to this point no products have been calculated, we have just set up iterators
# Now, start iterating through M, divisors, and divisior_combinations
# until the product equals M
out = list(it.takewhile(lambda a: np.array(a[0][0]).prod() != a[0][1],g))
if len(out) > 0:
u_i = out[-1][1][0]
else:
u_i = list(u_i)[0]
u_i = np.array(u_i)
u_i = u_i[u_i != 1]
i = list(map(lambda ui: np.where(u == ui)[0][0],u_i))
return i
# In[6]:
get_ipython().magic('timeit i = closest_product_no_repetition(N,u)')
i = closest_product_no_repetition(N,u)
print('i: ',i)
print('u[i]: ',u[i])
print('u[i].prod(): ',u[i].prod())
# ## Repetition
# It is not clear from the original problem description if elements of u can be repeated. This is easily addressed by just taking all the combinations with repetition.
# In[7]:
def closest_product_with_repetition(N,u):
# Setup generator for product targets "M"
Mg = it.chain.from_iterable(
(
(N-y,N+y) if y != 0 else (N,)
for y in range(min(abs(N-u))+1)
)
)
# For each M construct a list of divisors
# Each generated element is a tuple: (divisors,M)
divisors = filter(
lambda f: f[0].size > 1,
(
# Append 1 to the list of divisors so that we can use a fixed combination size
(np.append(u[M % u == 0],1),M) for M in Mg
)
)
# For each tuple of (divisors,M),
# generate combinations of divisors with replacement
divisor_combinations = it.chain.from_iterable(zip(
it.combinations_with_replacement(
d,
# Since we allow for replacement,
# set combination length such that a power of the smallest divisor exceeds M
int(np.ceil(np.log(M)/np.log(min(d[d > 1]))))
),
it.repeat(M)
) for d,M in divisors)
# We want to use it.takewhile, but we need info on the divisor combination that met the condition
# Use tee to duplicate the iterator and advance it by one
g = it.tee(divisor_combinations)
u_i = next(g[1])
g = zip(*g)
# Up to this point no products have been calculated, we have just set up iterators
# Now, start iterating through M, divisors, and divisior_combinations
# until the product equals M
out = list(it.takewhile(lambda a: np.array(a[0][0]).prod() != a[0][1],g))
if len(out) > 0:
u_i = out[-1][1][0]
else:
u_i = list(u_i)[0]
u_i = np.array(u_i)
u_i = u_i[u_i != 1]
i = list(map(lambda ui: np.where(u == ui)[0][0],u_i))
return i
# In[8]:
get_ipython().magic('timeit i = closest_product_with_repetition(N,u)')
i = closest_product_with_repetition(N,u)
print('i: ',i)
print('u[i]: ',u[i])
print('u[i].prod(): ',u[i].prod())
# ## Breakdown of the method
#
# First we define a helper function, peek_with_label to help take a look at some of the generators used.
# In[9]:
def peek_with_label(iterable,num=10,label=''):
iterable = it.tee(iterable)
print(label)
for x in it.islice(iterable[0],num):
print(x)
return iterable[1]
# In[10]:
# Setup generator for product targets "M"
Mg = it.chain.from_iterable(
(
(N-y,N+y) if y != 0 else (N,)
for y in range(min(abs(N-u))+1)
)
)
Mg = peek_with_label(Mg,10,'M generator:')
# In[11]:
# For each M construct a list of divisors
# Each generated element is a tuple: (divisors,M)
divisors = filter(
lambda f: f[0].size > 1,
(
# Append 1 to the list of divisors so that we can use a fixed combination size
(np.append(u[M % u == 0],1),M) for M in Mg
)
)
divisors = peek_with_label(divisors,10,'Divisors: ')
# In[12]:
# For each tuple of (divisors,M),
# generate combinations of divisors with replacement
divisor_combinations = it.chain.from_iterable(zip(
it.combinations_with_replacement(
d,
# Since we allow for replacement,
# set combination length such that a power of the smallest divisor exceeds M
int(np.ceil(np.log(M)/np.log(min(d[d > 1]))))
),
it.repeat(M)
) for d,M in divisors)
divisor_combinations = peek_with_label(divisor_combinations,240,'Divisor combinations with repetition: ')
# In[13]:
# We want to use it.takewhile, but we need info on the divisor combination that met the condition
# Use tee to duplicate the iterator and advance it by one
g = it.tee(divisor_combinations)
u_i = next(g[1])
g = zip(*g)
g = peek_with_label(g,10,'Paired divisor combinations:')
# In[14]:
# Up to this point no products have been calculated, we have just set up iterators
# Now, start iterating through M, divisors, and divisior_combinations
# until the product equals M
out = list(it.takewhile(lambda a: np.array(a[0][0]).prod() != a[0][1],g))
for x in out[-10:]:
print(x)
# In[15]:
if len(out) > 0:
u_i = out[-1][1][0]
else:
u_i = list(u_i)[0]
u_i = np.array(u_i)
u_i = u_i[u_i != 1]
i = list(map(lambda ui: np.where(u == ui)[0][0],u_i))
# In[16]:
print('i: ',i)
print('u[i]: ',u[i])
print('u[i].prod(): ',u[i].prod())
# ## Unified Function with or without repetition
# In[17]:
def closest_product(N,u,repetition=False):
# Process input
u = np.array(u)
# Setup generator for product targets "M"
Mg = it.chain.from_iterable(
(
(N-y,N+y) if y != 0 else (N,)
for y in range(min(abs(N-u))+1)
)
)
if repetition:
# For each M construct a list of divisors
# Each generated element is a tuple: (divisors,M)
divisors = filter(
lambda f: f[0].size > 1,
(
# Append 1 to the list of divisors so that we can use a fixed combination size
(np.append(u[M % u == 0],1),M) for M in Mg
)
)
# For each tuple of (divisors,M),
# generate combinations of divisors with replacement
divisor_combinations = it.chain.from_iterable(zip(
it.combinations_with_replacement(
d,
# Since we allow for replacement,
# set combination length such that a power of the smallest divisor exceeds M
int(np.ceil(np.log(M)/np.log(min(d[d > 1]))))
),
it.repeat(M)
) for d,M in divisors)
else:
# For each M construct a list of divisors
# Each generated element is a tuple: (divisors,M)
divisors = filter(
lambda f: f[0].size > 0,
(
(u[M % u == 0],M) for M in Mg
)
)
# For each tuple of (divisors,M),
# generate combinations of divisors
divisor_combinations = it.chain.from_iterable(zip(
it.chain.from_iterable(
(it.combinations(d,r+1) for r in range(d.size))
),
it.repeat(M)
) for d,M in divisors)
# We want to use it.takewhile, but we need info on the divisor combination that met the condition
# Use tee to duplicate the iterator and advance it by one
g = it.tee(divisor_combinations)
u_i = next(g[1])
g = zip(*g)
# Up to this point no products have been calculated, we have just set up iterators
# Now, start iterating through M, divisors, and divisior_combinations
# until the product equals M
out = list(it.takewhile(lambda a: np.array(a[0][0]).prod() != a[0][1],g))
if len(out) > 0:
u_i = out[-1][1][0]
else:
u_i = list(u_i)[0]
u_i = np.array(u_i)
u_i = u_i[u_i != 1]
i = list(map(lambda ui: np.where(u == ui)[0][0],u_i))
return i
# ### Unified Function testing
# In[18]:
closest_product(8,[2,3],repetition=False)
# In[19]:
closest_product(8,np.array([2,3]),repetition=True)
# In[20]:
closest_product(8,[8],repetition=False)
# In[21]:
closest_product(8,[8],repetition=True)
# In[22]:
closest_product(N,u,repetition=False)
# In[23]:
closest_product(N,u,repetition=True)
# ## Create a random challenging case, with m = 100
#
# If we create a random challenging case, executing time is in the milliseconds
# In[24]:
challenging_N = np.random.randint(101,2**20)
challenging_u = np.random.choice(range(2,1010),100,False)
print('challenging_N: ',challenging_N)
print('challenging_u: ',challenging_u)
# In[25]:
get_ipython().magic('time i = closest_product(challenging_N,challenging_u,repetition=False)')
i = closest_product(challenging_N,challenging_u,repetition=False)
print('i: ',i)
print('u[i]: ',challenging_u[i])
print('u[i].prod(): ',challenging_u[i].prod())