Domanda

My code works, but I need it to run in under 1 second. How do I do that?

For this summation

import math
import time

t=time.time()
line = input().split(' ')
Alen = int(line[0])
Blen = int(line[1])

A = input().split(' ')
B = input().split(' ')

total=0
for i, Ai in enumerate(A):
    for j, Bj in enumerate(B):
       total+= abs((int(Ai)-int(Bj)))*(int(i)-int(j))

print(total)#, time.time()-t)
È stato utile?

Soluzione

This should be a bit faster; no way of telling how much without some sample data.

import time

def get_ints(s):
    return [int(i) for i in s.split()]

t = time.time()

Alen, Blen = get_ints(input())
A = get_ints(input())
B = get_ints(input())

total = sum(abs(Ai - Bj) * (i - j) for i,Ai in enumerate(A) for j,Bj in enumerate(B))

print(total)#, time.time()-t)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top