![]() |
Code optimization - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Code optimization (/thread-31138.html) |
Code optimization - Vidar567 - Nov-24-2020 Hello guys, Have you got any sugesstions how to optimize my code? I would like to use maybe other solution to compile faster. Thank you for any sugesstions def countit(numericals=[1, 1, 2, 2, 3, 3], h=1): pol = 0 sort = list(dict.fromkeys(numericals)) for x in sort: dodaj = x + h for y in sort: if dodaj == y: pol = 1 + pol else: pass return pol print(countit()) RE: Code optimization - deanhystad - Nov-24-2020 Use combinations to reduce the number of pairs you have to test. You'll have to change the test to check for +/-h. Using list.count() and a list comprehension should speed things up too. def countit2(values, h=1): return [abs(a-b) for a, b in itertools.combinations(set(values), r=2)].count(h) RE: Code optimization - Vidar567 - Nov-24-2020 It is funny but it works the same, Thank you anyway!:) |