Time limit exceeded
When a solution is too slow, it's typically because the algorithm is one or more orders of magnitude worse than intended for the challenges. So take a hard look at the time complexity of the implementation.
In your implementation, it all comes down to this expression:
sorted(set(x+"%d"%(k.count(x)) for x in k))
k.count(x)
: the centerpiece of the expression, to find the count of some value in a list. Thecount
function does this by iterating over all elementsk
, and checking each for equality withx
. Time complexity: \$O(N)\$, where N is the number of items ink
... for x in k
: do something for each item ink
. Again, \$O(N)\$, where N is the number of items ink
set(...)
: probably \$O(N)\$sorted(...)
: probably \$O(N\log(N))\$
In total that gives: \$O(N^2) + O(N) + O(N\log(N))\$
Can this be better?
You need to sort, that's for sure. That's fast enough.
Do you really need a set? You used a set because the previous operations generate a list with duplicates. Using a set to remove duplicates is fine, but I would question why are duplicates at all in the first place.
The previous two items actually don't even matter. It's the slowest operation in the \$O(N^2) + O(N) + O(N\log(N))\$ that will drag everything down, the \$O(N^2)\$, so that's what you really need to optimize.
Instead of iterating over every account number for each account number, you could iterate only once, building a dictionary with counts along the way:
def print_sorted_with_count(accounts):
counts = {}
for account in accounts:
counts[account] = counts.get(account, 0) + 1
for account, count in sorted(counts.items()):
print('{} {}'.format(account, count))
This implementation reduces the time complexity from \$O(N^2)\$ to \$O(N)\$, and also gets rid of an \$O(N)\$ operation (no more need for the set.)
UPDATE
As @abarnert@abarnert pointed out,
the dictionary of counts can be created with a single expression using collections.Counter
, so the above code can become simply:
from collections import Counter
def print_sorted_with_count(accounts):
counts = Counter(accounts)
for account, count in sorted(counts.items()):
print('{} {}'.format(account, count))
Naming
The variable names in the posted code are horrible, and it makes it very hard to read. Avoid single-letter variable names, try to use descriptive names.
Coding style
I suggest to follow the recommendations of PEP8.