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().sp lit())
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
for x in e:
for y in r:
sch += h.get(-(x+y),0)
q,w,e,r,h = None,None,None, None,None
print sch
print time.clock() - t
=============== =============== =============== =============== ===
Alas it gets "time limit exceeded".
On my home PC (1.6 GHz, 512 MB RAM) and for 4000 input rows it
executes ~1.5 min.
Any ideas to speed it up say 10 times? Or the problem only for C-like
langs? 29 1958
Any ideas to speed it up say 10 times? Or the problem only for C-like
langs?
I dout this will speed it up by a factor of 10, but in your solution
you are mapping the values in the input file to longs. The problem
statement states that the maximum value for any of the numbers is
2**28. I assume the reason for this is precisely to allow you to use
32-bit integers. So, you can safely use int instead, and it _might_
speed up a little.
Your suggestion speeded it up 1.5 times (on my 4000 test input rows)!
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().sp lit())
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.def aultdict(iterto ols.repeat(0).n ext)
...
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.def aultdict 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
"n00m" <n0**@narod.ruw rites:
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.
f = open('input1')
npairs = int(f.readline( ))
quads = [map(int, f.readline().sp lit()) for i in xrange(npairs)]
assert len(quads) == npairs
da = {}
for p in quads:
for q in quads:
z = p[2] + q[3]
da[z] = da.get(z,0) + 1
print sum([da.get(-(p[0]+q[1]), 0) for p in quads for q in quads])
Paul Rubin <http://ph****@NOSPAM.i nvalidwrites:
print sum([da.get(-(p[0]+q[1]), 0) for p in quads for q in quads])
The above should say:
print sum(da.get(-(p[0]+q[1]), 0) for p in quads for q in quads)
I had to use a listcomp instead of a genexp for testing, since I'm
still using python 2.3, and I forgot to patch that before pasting to
the newsgroup. But the listcomp will burn a lot of memory when the
list is large.
I'd be interested in the running time of the above for your large data set.
Note that it still uses potentially O(n**2) space.
Steven, I ran this:
import time, collections, itertools
t = time.clock()
q,w,e,r,sch = [],[],[],[],0
h = collections.def aultdict(iterto ols.repeat(0).n ext)
f = open("D:/m4000.txt","rt" )
for o in range(int(f.rea dline())):
row = map(int, f.readline().sp lit())
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:
h[x+y] += 1
for x in e:
for y in r:
sch += h[-(x + y)]
q,w,e,r,h = None,None,None, None,None
print sch
print time.clock() - t
========= and it almost froze my PC...
=== but it was faster than my code on input file with 1000 rows:
====== 2.00864607094s VS 3.14631077413s
"n00m" <n0**@narod.ruw rites:
h = collections.def aultdict(iterto ols.repeat(0).n ext)
Something wrong with
h = collections.def aultdict(int)
?????
for x in e:
for y in r:
sch += h[-(x + y)]
That scares me a little: I think it makes a new entry in h, for the
cases where -(x+y) is not already in h. You want:
for x in e:
for y in r:
sch += h.get(-(x+y), 0)
"n00m" <n0**@narod.ruw rites:
Two first outputs is of above (your) code; next two - of my code:
Yeah, I see now that we both used the same algorithm. At first glance
I thought you had done something much slower. The 10 second limit
they gave looks like they intended to do it about this way, but with a
compiled language. 68 seconds isn't so bad for 4000 entries in pure
CPython. Next thing to do I think is use psyco or pyrex.
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().sp lit())
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
for x in e:
for y in r:
sch += h.get(-(x+y),0)
q,w,e,r,h = None,None,None, None,None
print sch
print time.clock() - t
=============== =============== =============== =============== ===
Alas it gets "time limit exceeded".
On my home PC (1.6 GHz, 512 MB RAM) and for 4000 input rows it
executes ~1.5 min.
Any ideas to speed it up say 10 times? Or the problem only for C-like
langs?
Perhaps a bit faster using slicing to get the lists and avoiding dict.get:
def sumfour(src):
l = map(int, src.split())
dct={}
s=0
A, B, C, D = l[1::4], l[2::4], l[3::4], l[4::4]
for a in A:
for b in B:
if a+b in dct:
dct[a+b] += 1
else:
dct[a+b] = 1
for c in C:
for d in D:
if -c-d in dct:
s+= dct[-c-d]
return s
if __name__ == '__main__':
import sys
print sumfour(sys.std in.read())
Michael This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ling Lee |
last post by:
Hi all.
I'm trying to write a program that:
1) Ask me what file I want to count number of lines in, and then counts the
lines and writes the answear out.
2) I made the first part like this:
in_file = raw_input("What is the name of the file you want to open: ")
in_file = open("test.txt","r")
|
by: John Furphy |
last post by:
Could someone assist with getting the count function working correctly
in this example please. I know the count function will return all rows
that do not have null values, but in this case I want to count all the
rows except those with a zero sale price, (which are unsold).
The table shows works offered for sale by an artist, with a positive
figure under SalePrice indicating a sale, and I want to count the
number sold by each auction...
|
by: Cro |
last post by:
Hello Access Developers,
I'd like to know if it is possible to perform a count in an expression
that defines a control source.
My report is based on a query. In my report, I want a text box to
display the number of times a certain value appears in a certain field
(i.e. perform a ‘count'). I will be doing this for many values in many
fields so do not wish to have scores of queries to build my report.
|
by: sunilkeswani |
last post by:
Hi
I am still new to access. I want to know how i can build a query which
can display results from 4 different columns/fields
Like.
Field1 Field2 Field3 Field4
1 2 1 0
1 1 0 0
|
by: Martin Joergensen |
last post by:
Hi,
I have some files which has the following content:
0 0 0 0 0 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 0 0 0 0 0
| |
by: Mack |
last post by:
Hi all,
I want to write a program to count number of bits set in a number.
The condition is we should not loop through each bit to find whether
its set or not.
Thanks in advance,
-Mukesh
|
by: waynejr25 |
last post by:
can anyone help me add a function that will count the occurance of each word in an input file. here's the code i have so far it counts the number of characters, words, and lines but i need the occurance of each word.
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
|
by: jlt206 |
last post by:
This code <?php include("counter.php")?> on the webpage produces the count number. (function code below)
I want to place the current number into a variable $MemberNo or into a FormField to be sent via an email function.
But just can't figure it out.
<?
////////////////////////////////////////////////////////////
//
|
by: vikrantt |
last post by:
For example:
3=
2 1
1 2
1 1 1
4=
3 1
1 3
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
| |
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |