M
M
mrpropper2020-05-02 13:16:47
Python
mrpropper, 2020-05-02 13:16:47

Why are C++ and Python code comparably slow? How to fix?

def main():
    n = int(input())
    input1 = list(input().split())
    output = []
    input1.reverse()
    for i in input1:
        if i not in output:
            output.append(i)

    print(len(output))
    output.reverse()
    for i in output:
        print(i, end = ' ')

main()

Similar code in C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool checkel(vector<int> mas,int el)
{
    for (int i:mas)
        if (i == el)
            return true;
    return false;
}

int main()
{
    int n;
    cin >> n;
    int* mas = new int[n];
    for (int i=0;i<n ;i++ ) {
        cin >> mas[i];
    }
    vector<int> vec;
    for (int i=n-1;i>=0 ;i--) {
        if (!checkel(vec,mas[i])) {
            vec.push_back(mas[i]);
        }
    }

    cout << vec.size() << endl;
    reverse( vec.begin(), vec.end() );
    for (int i:vec)
        cout << i << ' ';
    return 0;
}

They showed commensurately poor results for speed. From Python I expected, but from crosses ...
Or maybe it's because of the output delay (in crosses)? How can it be optimized?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Zagaevsky, 2020-05-02
@mrpropper

Perhaps it's a non-optimal algorithm. In the worst case, you will have quadratic complexity. Stop walking on the internal list all the time, and I think it will become faster. Well, you don't need to reverse the arrays, just iterate over them in reverse order.
Also look at how olympiads set up input-output, it can influence.

A
Artyom Varlamov, 2020-05-03
@Frontend777

I don't think python is slow

Here you go.....

K
k-morozov, 2020-05-05
@k-morozov

C++ code:
1. pass a vector to a function by reference, try a reference in the for loop - although int is unlikely to be profitable there
2. if you just need to output the result, then reverse is fashionable

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question