fork download
  1. from timeit import timeit
  2.  
  3. def ping(n):
  4. 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]
  5.  
  6. def koala(n):
  7. 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)
  8.  
  9. def slow_koala(n):
  10. 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)
  11.  
  12. def koala_explained(n):
  13. max_divisor = int(n**.5)
  14. divisors = []
  15. for divisor in range(1,max_divisor+1):
  16. if n % divisor == 0:
  17. divisors.append(divisor)
  18. divisors.append(n//divisor)
  19.  
  20. def digit_sum(x):
  21. return sum(int(digit) for digit in str(x))
  22.  
  23. def magnitude(x):
  24. return digit_sum(x)+1/x
  25.  
  26. return max(divisors,key=magnitude)
  27.  
  28. def test(func):
  29. for i in range(1,1000):
  30. func(i)
  31.  
  32. for func in ['ping','koala','slow_koala','koala_explained']:
  33. print(func+':'+str(timeit('from __main__ import test,'+func+';test('+func+')', number=10)))
  34.  
Success #stdin #stdout 0.95s 28384KB
stdin
Standard input is empty
stdout
ping:0.3396789399998852
koala:0.09837708800023393
slow_koala:0.3968827300000157
koala_explained:0.09954419199993936