I'm attempting to solve the problem "Synchronizing Lists" on Kattis.com.
In a nutshell, the problem involves being given two lists: the lists are then to be sorted smallest-to-largest, correspondingly indexed elements paired together, then the second list is output, in the original order of the corresponding elements of the first list.
While functional, my code runs afoul of the time limit when pitted against the second test case, after I submit it.
import sys
class Correspondence():
def __init__(self, num1, num2, ID):
self.num1 = num1
self.num2 = num2
self.ID = ID
def SynchronizeLists(case_size):
list1 = []
list2 = []
correspondences = []
results = []
for i in range(case_size):
list1.append(int(sys.stdin.readline()))
for i in range(case_size):
list2.append(int(sys.stdin.readline()))
sorted_list1 = list1[:]
sorted_list1.sort()
sorted_list2 = list2[:]
sorted_list2.sort()
for i in range(len(sorted_list1)):
correspondence = Correspondence(sorted_list1[i], sorted_list2[i], i)
correspondences.append(correspondence)
for i in list1:
results.append([correspondence.num2 for correspondence in correspondences if correspondence.num1 == i][0])
return results
output = []
case_size = int(sys.stdin.readline())
while case_size != 0:
output.extend(SynchronizeLists(case_size))
output.append('')
case_size = int(sys.stdin.readline())
del output[-1]
for i in output:
print(i)
cProfile tells me this:
126 function calls in 1.270 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
2 0.000 0.000 0.000 0.000 <string>:11(SynchronizeLists)
1 0.000 0.000 1.269 1.269 <string>:3(<module>)
11 0.000 0.000 0.000 0.000 <string>:33(<listcomp>)
1 0.000 0.000 0.000 0.000 <string>:5(Correspondence)
11 0.000 0.000 0.000 0.000 <string>:6(__init__)
2 0.000 0.000 0.000 0.000 codecs.py:318(decode)
2 0.000 0.000 0.000 0.000 codecs.py:330(getstate)
2 0.000 0.000 0.000 0.000 {built-in method _codecs.utf_8_decode}
1 0.000 0.000 0.000 0.000 {built-in method builtins.__build_class__}
1 0.001 0.001 1.270 1.270 {built-in method builtins.exec}
2 0.000 0.000 0.000 0.000 {built-in method builtins.len}
12 0.000 0.000 0.000 0.000 {built-in method builtins.print}
46 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
2 0.000 0.000 0.000 0.000 {method 'extend' of 'list' objects}
25 1.269 0.051 1.269 0.051 {method 'readline' of '_io.TextIOWrapper' objects}
4 0.000 0.000 0.000 0.000 {method 'sort' of 'list' objects}
I'm not worried about exec
, as I suspect that's simply a consequence of how I'm using cProfile. It seems like my biggest time sink involves input: readline()
, to be precise.
I've already tried swapping out all calls to readline()
for calls to input()
, but the results barely changed.
How can I speed this up?