The following code should work:
a = [int(s) for s in input().split()]
sortedLst = sorted(a)
unique = []
uniqueOrd = []
for i in range(len(a) - 2):
if sortedLst[i + 1] != sortedLst[i] and sortedLst[i + 1] != sortedLst[i + 2]:
unique.append(sortedLst[i + 1])
for num in a:
if num in unique:
uniqueOrd.append(num)
print(uniqueOrd)
#1 5 3 4 2 6 1 3 4 6
Output with input (1 5 3 4 2 6 1 3 4 6):
[5, 2]
We make the range of our for loop len(a) - 2
so that the max value of i
is len(a) - 3
, and the maximum element we access, a[i + 2]
, is a[len(a) - 1]
, or the last element of the list.
Starting from i = 0
, we will check if the i + 1
th element is equal to the i
th or i + 2
th element. If at least one of these equalities is true, the element is not unique. If the i + 1
th element is not equal to either the i
th or i + 2
th element, we add it to our unique list.
To preserve the order from the original list, a
, we iterate through a
, and if the element in a
is also found in unique
, we add it to uniqueOrd
, so the order is preserved.
I hope this helped! Please let me know if you have any further questions or clarifications :)