I tried myself on this Google Codejam Africa (the competition is already over, I just did it to improve my programming skills).
Problem:
You have a party with G guests and note that there is an odd number of guests! When planning a party, you intentionally invited only couples and gave each pair a unique C number for their invitation. You would like to highlight the one who came alone asking all the guests for their invitation numbers.
Input:
The first line of input gives the number of cases N. Next, N test cases follow. For each test case there will be:
- One line containing the value of G, number of guests.
- One line containing a space-separated list of integers G. Each integer C indicates the guest’s invitation code. Output
For each test case, output one line containing "Case No.x:", followed by the guest number C, which is one.
Limits:
- 1 ≤ N ≤ 50
- 0 <C ≤ 2147483647
Small data set
3 ≤ G <100
Large data set
3 ≤ G <1000
Input Example:
3
3
1 2147483647 2147483647
5
3 4 7 4 3
5
2 10 2 10 5
Output result:
Case
Case
Case
This is the solution I came across:
with open('A-large-practice.in') as f:
lines = f.readlines()
with open('A-large-practice.out', 'w') as output:
N = int(lines[0])
for testcase, i in enumerate(range(1,2*N,2)):
G = int(lines[i])
for guest in range(G):
codes = map(int, lines[i+1].split(' '))
alone = (c for c in codes if codes.count(c)==1)
output.write("Case #%d: %d\n" % (testcase+1, alone.next()))
It starts in 12 seconds on my machine with a lot of input .
Now, to my question, is it possible to improve this solution in Python to work for shorter time or use less memory? analyzing the problem gives some guidance on how to do this in Java and C ++, but I cannot translate these solutions back to Python.
Edit:
Alex Martelli IVlad . , 0.079s:
with open('A-large-practice.in') as f:
lines = f.readlines()
with open('A-large-practice.out', 'w') as output:
N = int(lines[0])
for testcase, i in enumerate(range(1,2*N,2)):
codes = map(int, lines[i+1].split(' '))
alone = 0
for c in codes: alone ^= c
output.write("Case #%d: %d" % (testcase+1, alone))