Блог пользователя DDieter

Автор DDieter, 13 лет назад, По-английски

I'm pretty new to CodeForces and I recently participated in my first contest. I code in python and I kept having problems with performance issues (my solutions were too slow).

For problem 381B I changed the code and resubmitted it and now it was fast enough but I was wondering why my first solution was so slow? How can I make programs faster in python / Which functions and methods are slow?

First (slow) code:

M = int(raw_input())
up = []
down = []

for i in map(int, raw_input().split()):
    if i not in down:
        down.append(i)
    else:
        up.append(i)

down.sort(reverse=True)
up.sort()

if len(up) > 0 and down[0] == up[-1]:
    del up[-1]

up.extend(down)

print len(up)
print ' '.join(map(str,up))

Second (fast) code:

M = int(raw_input())
cards = map(int, raw_input().split())
cards.sort()

stair = [cards.pop(-1)]
index = len(cards) - 1
prevDown = stair[0]
prevUp = stair[0]

while index >= 0:
    if cards[index] != prevDown:
        prevDown = cards[index]
        stair.append(cards.pop(index))
        index -= 1
    elif cards[index] != prevUp:
        prevUp = cards[index]
        stair.insert(0,cards.pop(index))
        index -= 1
    else:
        index -= 1

print len(stair)    
print ' '.join(map(str, stair))
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
13 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Actually The first solution wouldn't have passed in any other language.

The runtime was O(m^2) Because this statement "i not in down" ... makes a linear scan through the list down to decide whether number (i) is in the list or not.

The second solution was only O(m), So it passed.

Btw, Large input and output in python causes your program to be slow. So try using these lines for fast input and output

import sys
x=sys.stdin.readline() #for input
sys.stdout.write(str(x)) #for output