Python Forum

Full Version: Code optimization
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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())
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)
It is funny but it works the same, Thank you anyway!:)