I'm trying to answer a competitive programming question on kattis that can be found here My algorithm is correct, however there is one of the test cases that has a lot of inputs and my code times out. Is there a more optimized way to do IO in python?
from sys import stdin, stdout
import atexit, io, sys
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write():
sys.__stdout__.write(buffer.getvalue())
def main():
teque = []
for i in range(int(stdin.readline())):
l = stdin.readline().split()
if l[0] == 'push_back':
teque.append(int(l[1]))
if l[0] == 'push_front':
teque.insert(0, int(l[1]))
if l[0] == 'push_middle':
if len(teque)%2==0:
mid = len(teque)/2
else:
mid = (len(teque)+1)/2
teque.insert(int(mid), int(l[1]))
if l[0] == 'get':
stdout.write(str(teque[int(l[1])])+'\n')
if __name__ == "__main__":
main()
So as I learned in the comments, I wasn't actually doing the program in O(1) time for insert, I fixed invoking 2 queues. This solution still isn't fast enough for python 3 run time, however it passes the python 2 run time.
from sys import stdin, stdout
from collections import deque
class Teque:
def __init__(self):
self._teque1 = deque()
self._teque2 = deque()
def push_back(self, x):
self._teque2.append(x)
if len(self._teque2) > len(self._teque1):
self._teque1.append((self._teque2.popleft()))
def push_front(self, x):
self._teque1.appendleft(x)
if len(self._teque1) > len(self._teque2):
self._teque2.appendleft((self._teque1.pop()))
def push_middle(self, x):
if len(self._teque2) > len(self._teque1):
self._teque1.append(self._teque2.popleft())
self._teque2.appendleft(x)
def get(self, i):
if i >= len(self._teque1):
return self._teque2[i-len(self._teque1)]
return self._teque1[i]
def main():
teque = Teque()
for i in range(int(stdin.readline())):
l = stdin.readline().split()
if l[0] == 'push_back':
teque.push_back(int(l[1]))
elif l[0] == 'push_front':
teque.push_front(int(l[1]))
elif l[0] == 'push_middle':
teque.push_middle(int(l[1]))
else:
stdout.write(str(teque.get(int(l[1])))+'\n')
if __name__ == "__main__":
main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.