I'm trying to solve this problem from Timus Online Judge. To solve this problem you need generate a sequence of 1 000 000 lowercase Latin letters and write it to stdin in 1 second.
It is easy to solve this problem with C++ or Java. I have python solution here:
import os
from random import randint
s = ''.join(chr(97 + randint(0, 25)) for i in range(1000000))
os.write(1, bytes(s, 'utf8'))
It takes 1.7s:
$ time python3.3 1219.py > /dev/null
real 0m1.756s
user 0m1.744s
sys 0m0.008s
And I got "Time limit exceeded" in result. So the question is "How to do it faster?"
UPD1:
Using randint(97, 122)
reduces time at 16ms. Now it is 1.740s
UPD2: Solution by @Martijn Pieters takes 0.979s, but it doesn't pass test either.
UPD3 Martijn Pieters suggested a very good solutions, but it's still slow:
from sys import stdin
from random import choice
from string import ascii_lowercase
s = ''.join([choice(ascii_lowercase) for _ in range(1000000)])
stdout.write(s)
Takes 0.924s
from sys import stdout
from random import choice
from string import ascii_lowercase
for _ in range(1000000):
stdout.write(choice(ascii_lowercase))
Takes 1.173s
from sys import stdout
from random import choice
from string import ascii_lowercase
bal = [c.encode('ascii') for c in ascii_lowercase]
out = stdout.buffer
for _ in range(1000000):
out.write(choice(bal))
Takes 1.155s
from sys import stdout
from random import choice
from string import ascii_lowercase
bal = [c.encode('ascii') for c in ascii_lowercase]
stdout.buffer.write(b''.join([choice(bal) for _ in range(1000000)]))
Takes 0.901s
UPD4
Some guy just solved problem on Timus. I hope he will share his solution :)
UPD5 Thanks to Ashwini Chaudhary for sharing his Python 2.x solution with us:
from random import choice
from string import ascii_lowercase
lis=list(ascii_lowercase)
print ''.join(choice(lis) for _ in xrange(1000000))
It takes 0.527s on my computer and it passes tests on Timus. But problem with Python3.x still remains.
UPD6 Thanks to Markku K. this code:
import os
from random import random
from string import ascii_lowercase
bal = [c.encode('ascii') for c in ascii_lowercase]
os.write(1, b''.join([bal[int(random() * 26)] for _ in range(1000000)]))
Takes 0.445s, but still didn't pass the test