简体   繁体   中英

Time limit exceeded for contest code written in Python

I wrote some code for a contest in python. The test case limit is 1 <= n <= 10^9.

n=input("")
sum=0
for i in range(0,n):
   s=input("")
   sum=sum^s
print sum

It shows an error of time limit exceeded, but when I did the same in C, it worked fine. My C code is:

#include<stdio.h>
int main()
{
long long int a;
int ex=0,n;
scanf("%d",&n);
for(int i=0;i<n;i++)
 {
 scanf("%lld",&a);
 ex=ex^a;
  }
printf("%d\n",ex);
  return 0;
}

Can someone explain this difference?

Python is a very simple and powerful language, but it is slow as compared to C language for a variety of reasons like: 1.It is dynamically typed 2.It is interpreted rather than compiled 3.Some of its memory access models are inefficient.

So some of the Python programs may be as slow as 20 times than a similar C program.

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