0

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.

3
  • This is about as fast as it gets. How slow is it on your system? Commented Nov 24, 2020 at 21:55
  • Feed the "numericals" list to a "collections.Counter", create a second list where to each item "h" is added, feed it into another Counter and get the intersection of the counters. Commented Nov 24, 2020 at 22:04
  • 1
    Are you looking for code that is faster for larger arrays? The current algorithm is fast for small arrays (i.e. ~2 us). Commented Nov 24, 2020 at 22:45

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.