[Tutor] Getting greatest 3 numbers from list
Peter Otten
__peter__ at web.de
Mon Feb 21 09:13:12 EST 2022
On 21/02/2022 14:46, Manprit Singh wrote:
> Dear Sir ,
>
> This is not related to python, but a general question, in c++ we have sets
> in standard template library and iterators, and sets are basically sorted,
> So doing the same problem in c++ using sets is a bad idea ?
>
> #include<iostream>
> #include<set>
> #include<functional>
> using namespace std;
>
> int main()
> {
> int arry[6] = {2, 4, 9, 2, 4, 1};
> set<int> second(arry, arry+6);
> auto itr = second.end();
> itr--;
> auto greatest = *itr;
> itr--;
> auto seclargest = *itr;
> itr--;
> auto thirdlargest = *itr;
> cout << greatest << " " << seclargest << " "<<thirdlargest;
> return 0;
> }
>
> Gives the right answer
>
> My apologies for posting c++ code if it is against the rule of python
> mailing list
Well, don't make it a habit ;)
I suppose the above is roughly equivalent to
>>> sorted(set([2, 4, 9, 2, 4, 1]))[-3:]
[2, 4, 9]
This produces different results when the list contains duplicates:
>>> items = [1, 2, 3, 3, 2, 1]
>>> sorted(set(items))[-3:]
[1, 2, 3]
>>> sorted(items)[-3:]
[2, 3, 3]
Also, can the C++ code cope with input consisting of less than three
different values?
Finally, when you pick a complex tool like C++ you usually want
something algorithmically efficient -- which reminds me of the heap I
mentioned above...
More information about the Tutor
mailing list