To count number of quadruplets with sum = 0
Steven Bethard
steven.bethard at gmail.com
Thu Mar 15 22:19:16 EDT 2007
n00m wrote:
> http://www.spoj.pl/problems/SUMFOUR/
>
> 3
> 0 0 0 0
> 0 0 0 0
> -1 -1 1 1
> Answer for this input data is 33.
>
> My solution for the problem is
> ======================================================================
>
> import time
> t = time.clock()
>
> q,w,e,r,sch,h = [],[],[],[],0,{}
>
> f = open("D:/m4000.txt","rt")
>
> n = int(f.readline())
>
> for o in range(n):
> row = map(long, 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 h.has_key(x+y):
> h[x+y] += 1
> else:
> h[x+y] = 1
This won't help much, but you can rewrite the above as::
x_y = x + y
h[x_y] = h.get(x_y, 1)
Or if you're using Python 2.5, try::
h = collections.defaultdict(itertools.repeat(0).next)
...
for x in q:
for y in w:
h[x + y] += 1
...
Not likely to get you an order of magnitude though.
> for x in e:
> for y in r:
> sch += h.get(-(x+y),0)
If you use the collections.defaultdict approach above, this becomes::
for x in e:
for y in r:
sch += h[-(x + y)]
Note that you should also probably put all your code into a function --
looking up function locals is quicker than looking up module globals.
STeVe
More information about the Python-list
mailing list