Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code optimization
#1
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())
Reply
#2
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)
Reply
#3
It is funny but it works the same, Thank you anyway!:)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Portfolio Optimization code error i want to cry FinanceMotta 3 408 Mar-11-2024, 10:24 PM
Last Post: deanhystad
  Multithreading with queues - code optimization h1v3s3c 1 2,655 May-10-2018, 10:40 AM
Last Post: ThiefOfTime

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020