Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the set of elements in a list without sorting in Python

Tags:

python

set

I have a list of elements 1,...,K with repeats. For example for K=4 :

[4 2 1 1 2 1 1 3 2  ] 

I want to find the sequence that 1,...,K is appeared in the list (without sorting). For example for the above sequence, the result would be

[4, 2 ,1 ,3 ]

How can I write this algorithm efficiently in python, with less runtime.

Thank you!

like image 391
Mgorji Avatar asked Jan 24 '26 17:01

Mgorji


1 Answers

from collections import OrderedDict
list_numbers=[4,2,1,1,2,1,1,3,2]
print list(OrderedDict.fromkeys(list_numbers))

This gives the desired output - [4, 2, 1, 3]

like image 120
aramase Avatar answered Jan 26 '26 10:01

aramase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!