1

Given a list of numbers, find and print the elements that appear in it only once. Such elements should be printed in the order in which they occur in the original list. So I use sort and use a list to keep track of it order but python say "list index out of range", how do I fix this?

a = [int(s) for s in input().split()]
a.sort()
mylist = []
myorder = []
for i in range(len(a)):
    if  a[i-1] != a[i] != a[i+1]:
        mylist.append(a[i])
        myorder.append(a.index(a[i]))
mylist = [mylist[k] for k in myorder]
print(mylist)
Meno
  • 120
  • 8

2 Answers2

0

You are writing a for loop and accessing

a[i+1]

but by your definition in:

for i in range(len(a))

when i is its maximum value i+1 is out of the index range of a.

Kraigolas
  • 5,121
  • 3
  • 12
  • 37
0

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 + 1th element is equal to the ith or i + 2th element. If at least one of these equalities is true, the element is not unique. If the i + 1th element is not equal to either the ith or i + 2th 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 :)

Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14