0

I was trying to attempt a simple question on HackerEarth. I code in python usually. My test cases were failing due to time limit in python so I tried to implement the same logic via C programming. And in C it just completed in 0.7 seconds. Mostly the login implementation is same. If its due to input size, could you please suggest something that I should use in python to get similar time as that of C.

The question is not duplicate one as here time taken vastly differs with C so all I am asking is better approach to rewrite the python code which is memory efficient.

Here's the question link:

Here's my code in python:

for _ in range(int(input())):
    n=int(input())
    c=0
    for i in range(1,n):
        for j in range(i+1,n+1):
            if(j>n):
                break
            if((i^j) <= n):
                c+=1
    print(f'{c}')

Here's my code in C:


#include <stdio.h>
int main(){
    int n,c,t,k,i,j;
    scanf("%d",&t);
    for(k=0;k<t;k++){
        c=0;
        scanf("%d",&n);
        for(i=1;i<n;i++){
            for(j=i+1;j<n+1;j++){
                if(j>n){
                    break;
                }
                if((i^j) <= n){
                    c+=1;
                }
            }
        }
        printf("%d\n",c);
    }
}

I am not asking anyone to solve any question here. I already solved the question using 2 programming languages I just to know why similar logic taking very long time and eventually failing due to time constraint in python. And how can I avoid this in future. I don't wanna code in C anymore as I totally forgot it and python is obviously easy to implement.

The difference in time in two languages

Swarnveer
  • 490
  • 5
  • 23
  • 2
    Does this answer your question? [What makes C faster than Python?](https://stackoverflow.com/questions/13853053/what-makes-c-faster-than-python) – snatchysquid Sep 26 '20 at 05:00
  • There surely must be some way in which similar speed can be obtained. I just wanna know that, how can I rewrite this python code of mine to achieve that. – Swarnveer Sep 26 '20 at 05:03
  • 2
    Sorry, this is the kind of thing you give up when you switch from a compiled language to an interpreted one. What you gain is lots of higher level abstractions and libraries, such as lists, dictionaries, pandas, and numpy. – Barmar Sep 26 '20 at 05:07
  • 3
    Sorry, afraid that python is slow in it's nature. We all love python but it is – snatchysquid Sep 26 '20 at 05:08
  • 1
    When one wants to **optimize** the code, the code should be **profiled**: On a concrete inputs it should be found which lines of code are the *bottleneck*. You show neither inputs nor profiling data. How do you expect us to improve the code? – Tsyvarev Oct 17 '20 at 12:24

0 Answers0