To count number of quadruplets with sum = 0

n00m n00m at narod.ru
Sat Mar 17 23:46:06 EDT 2007


bearophileH!

I gave to your "oil" svrl runs ("z in dict" instd of "dict.has_key"
saved only ~0.4 sec).
The result is (and I'm completely lost in all these
*optimizations* :)):


>>> ================================ RESTART ===
>>>
0
34.78 secs (bearophileH)
>>> ================================ RESTART ===
>>>
0
34.77 secs (bearophileH)
>>> ================================ RESTART ===
>>>
0
34.76 secs (bearophileH)
>>> ================================ RESTART ===
>>>
0
27.2460938471 secs (n00m)
>>> ================================ RESTART ===
>>>
0
27.2953596058 secs (n00m)
>>> ================================ RESTART ===
>>>
0
27.3709929614 secs (n00m)
>>>



In the name of exactness this is the tested codes:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
from collections import defaultdict
import time, psyco


def main():
    sch = 0
    q,w,e,r = [],[],[],[]
    h = defaultdict(int)


    datafile = file("D:/m4000.txt")
    datafile.next()
    xrows = (map(int, line.split()) for line in datafile)
    q, w, e, r = zip(*xrows)


    for x in q:
        for y in w:
            h[x+y] += 1


    for x in e:
        for y in r:
            if -x-y in h:
                sch += h[-x-y]


    print sch


t = time.clock()
psyco.full()
main()
print round(time.clock() - t, 2), "secs (bearophileH)"
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import psyco, time

def main():
  q,w,e,r,sch,h = [],[],[],[],0,{}
  f = open("D:/m4000.txt","rt")
  for o in range(int(f.readline())):
    row = map(int, f.readline().split())
    q.append(row[0])
    w.append(row[1])
    e.append(row[2])
    r.append(row[3])
  f.close()

  for x in q:
    for y in w:
      if (x+y) in h:
        h[x+y] += 1
      else:
        h[x+y] = 1

  for x in e:
    for y in r:
      if -(x+y) in h:
        sch += h[-(x+y)]

  q,w,e,r,h = None,None,None,None,None
  print sch

t = time.clock()
psyco.full()
main()
print time.clock() - t,"secs (n00m)"
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

PS Both Python & Psyco of 2.5 ver.




More information about the Python-list mailing list