Given your explanations and restrictions, there is not much that could by improved; you are already using list.index()
and max()
, taken all the advantage of built-in C implementations.
The only thing that makes a small difference could be the assignment to temp vairables and the call to math.ceil()
; read here for alternatives to ceil()
.
Another possibility is to sort the list in descending order so the search finds elements quicker.
Here is a slightly improved version; f1
is your version, the other is my proposal.
def f1(input_list, repetitions):
input_list = list(input_list)
for _ in range(repetitions):
idx = input_list.index(max(input_list))
new_num = math.ceil(input_list[idx] / 2)
input_list[idx] = new_num
return sum(input_list)
def f2(input_list, repetitions):
input_list = list(input_list)
input_list.sort(reverse=True)
for _ in range(repetitions):
idx = input_list.index(max(input_list))
input_list[idx] = ((input_list[idx] + 1) // 2)
return sum(input_list)
The code to compare durations and assure that the results are the same:
import random
import timeit
for exp_n in range(2, 5):
n = 10**exp_n
numbers = [random.randint(1, 9999) for _ in range(n)]
for exp_k in range(2, 5):
k = 10**exp_k
t1 = timeit.timeit(
'f(numbers, k)', 'from __main__ import numbers, k, f1 as f',
number=10)
t2 = timeit.timeit(
'f(numbers, k)', 'from __main__ import numbers, k, f2 as f',
number=10)
print('n {:10,d} | k {:10,d} | {:10.4f} | {:10.4f} | best f{}'.format(
n, k, t1, t2, '1' if t1 < t2 else '2'))
assert f1(numbers, k) == f2(numbers, k)
The results are (using Python 3.6
on Ubuntu
):
n 100 | k 100 | 0.0027 | 0.0025 | best f2
n 100 | k 1,000 | 0.0280 | 0.0251 | best f2
n 100 | k 10,000 | 0.2097 | 0.1872 | best f2
n 1,000 | k 100 | 0.0232 | 0.0190 | best f2
n 1,000 | k 1,000 | 0.2295 | 0.2009 | best f2
n 1,000 | k 10,000 | 2.2607 | 2.1653 | best f2
n 10,000 | k 100 | 0.2139 | 0.1903 | best f2
n 10,000 | k 1,000 | 2.1379 | 1.6530 | best f2
n 10,000 | k 10,000 | 21.3588 | 18.8767 | best f2
As you can see, the sorting in reverse order does help.