from timeit import timeit
def ping(n):
return max({sum([int(k) for k in str(n//i)]):n//i for i in range(1, n + 1) if not n%i}.items())[1]
def koala(n):
return max(sum([[d,n//d] for d in range(1,int(n**.5+1)) if n%d==0],[]),key=lambda x:sum(int(d) for d in str(x))+1/x)
def slow_koala(n):
return max([d for d in range(1,n+1) if n%d==0],key=lambda x:sum(int(d) for d in str(x))+1/x)
def koala_explained(n):
max_divisor = int(n**.5)
divisors = []
for divisor in range(1,max_divisor+1):
if n % divisor == 0:
divisors.append(divisor)
divisors.append(n//divisor)
def digit_sum(x):
return sum(int(digit) for digit in str(x))
def magnitude(x):
return digit_sum(x)+1/x
return max(divisors,key=magnitude)
def test(func):
for i in range(1,1000):
func(i)
for func in ['ping','koala','slow_koala','koala_explained']:
print(func+':'+str(timeit('from __main__ import test,'+func+';test('+func+')', number=10)))
ZnJvbSB0aW1laXQgaW1wb3J0IHRpbWVpdAoKZGVmIHBpbmcobik6CiAgICByZXR1cm4gbWF4KHtzdW0oW2ludChrKSBmb3IgayBpbiBzdHIobi8vaSldKTpuLy9pIGZvciBpIGluIHJhbmdlKDEsIG4gKyAxKSBpZiBub3QgbiVpfS5pdGVtcygpKVsxXQogICAgIApkZWYga29hbGEobik6CiAgICByZXR1cm4gbWF4KHN1bShbW2Qsbi8vZF0gZm9yIGQgaW4gcmFuZ2UoMSxpbnQobioqLjUrMSkpIGlmIG4lZD09MF0sW10pLGtleT1sYW1iZGEgeDpzdW0oaW50KGQpIGZvciBkIGluIHN0cih4KSkrMS94KQoKZGVmIHNsb3dfa29hbGEobik6CiAgICByZXR1cm4gbWF4KFtkIGZvciBkIGluIHJhbmdlKDEsbisxKSBpZiBuJWQ9PTBdLGtleT1sYW1iZGEgeDpzdW0oaW50KGQpIGZvciBkIGluIHN0cih4KSkrMS94KQoKZGVmIGtvYWxhX2V4cGxhaW5lZChuKToKICAgIG1heF9kaXZpc29yID0gaW50KG4qKi41KQogICAgZGl2aXNvcnMgPSBbXQogICAgZm9yIGRpdml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