TLE always happen in SBANK SPOJ using python. In order to solve it, i have to sort dict(), though dict() has huge number of KEYS(maximum–100000). Use sorted() function in my code takes no effect. Is there any fast solution? Thanks for your help.
My code below:
for j in range(n): # n is the number of keys
account = sys.stdin.readline().rstrip()
dic.setdefault(account, 0)
dic[account] += 1
sorted(dic) # **this sort take a lot of time**
EDIT1:According to Justin Peel’s tips, i update my code below, but return still TLE. How can i do?
import sys
import psyco # import psyco module to speed up
psyco.full()
nCase = int(sys.stdin.readline().split()[0])
for i in range(nCase):
n = int(sys.stdin.readline().split()[0])
dic = dict()
lst = list()
for j in range(n):
account = sys.stdin.readline().rstrip()
dic.setdefault(account, 0)
dic[account] += 1
sys.stdin.readline()
lst = dic.keys() # store keys in list
lst.sort()
for account in lst:
sys.stdout.write('%s %s\n' % (account, dic[account]))
I was able to solve this problem. Here are some tips:
keys = mydict.keys(); keys.sort()because it is the fastest way to go about it.