简体   繁体   中英

How to optimize code to run faster in python?

I wrote some code for solving a problem but unfortunately the problem has time limit (1 sec) and my program cannot solve it within 1 second. Is there anything to do to make it faster? This is a quiz that has some events(q) and some arrays(n). The first input's format is 'nq' to determine n and q. Then we have 'q' other inputs as one of these two formats: 1) '1 f': adds number 'f' to all of the arrays 2) '2 d e': remove the first 'e' numbers of 'd'th array The program's output must be the total of removed numbers for every removing event. When my code is compiled on that website, the message 'Time limit exceeded' will be shown. Maybe there is an other way to answer this question. I'm just curious about it.

def inputs(): 
    x = input() 
    y = x.split() 
    return y

def main(): 
    b = inputs()  # get two numbers with a space between them
    n = int(b[0]) 
    q = int(b[1]) 
    t = [] 
    l = 0
    obj = [[] for j in range(n)]  
    for i in range(q) : 
        b = inputs()  # get two or three numbers
        ib0 = int(b[0])
        ib1 = int(b[1])
        if ib0 == 1 : 
            for j in range(n) :
                obj[j].append(ib1)  
        if ib0 == 2 :
            ib2 = int(b[2]) 
            t.append(0)  
            for k in range(0,ib2) : 
                t[l] += obj[ib1-1][k] 
            l = l + 1
            del obj[ib1-1][:ib2] 
        b.clear()
    for m in range(l): 
        print(t[m])

if __name__ == '__main__' : 
    main() 

I'm not sure this will help, since it doesn't change the time complexity, but here are some constant optimizations (although I didn't test them):

import sys
input = sys.stdin.readline  # faster input

def inputs(): 
    return input().split()

def main(): 
    b = inputs()
    n = int(b[0])
    q = int(b[1])
    l = 0
    obj = [[] for j in range(n)]
    for i in range(q) :
        b = inputs()
        ib0 = int(b[0])
        ib1 = int(b[1])
        if ib0 == 1 : 
            for j in range(n) :
                obj[j].append(ib1)
        if ib0 == 2 :
            ib2 = int(b[2]) 
            print(sum(obj[ib1-1][:ib2])) # built-in sum function + in-place print
            del obj[ib1-1][:ib2] 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM