QryLu
QryLu

Reputation: 11

How can i optimize the following code as it is very slow

What are some of the ways to optimize the following code?

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())

The code checks if there are any "pairs" in the list with my additional variable in that case h = 1. So h + any element from the list = any element from the list it's a pair.

Upvotes: 0

Views: 36

Answers (2)

James Delaney
James Delaney

Reputation: 35

You should be able to use a dictionary. Something like the following should work if I am understanding the question correctly.

def countit(numericals=[1, 1, 2, 2, 3, 3], h=1):
    count = 0
    d = {number:1 for number in numericals}
    
    for key in d.keys():
        count += d.get(key+h, 0)
    
    return count

The dict stores all the elements in numericals. Then you can loop through all the values and add h, check if it's also in the dict (default to 0 if not so we can sum) and the sum should be the count of every time you had an element x in numericals where x+h is also there.

Should run in O(n) time where n is the number of elements in the numericals list as the dictionary accessing should be O(1)

Upvotes: 1

dimay
dimay

Reputation: 2804

Try this:

def countit(numericals=[1, 1, 2, 2, 3, 3], h=1):
     
    sort = set(numericals)
    return sum(1 for x in sort for y in sort if x+h==y )
    
print(countit())

Upvotes: 0

Related Questions