Salman Fardeen
Salman Fardeen

Reputation: 1

Read a list and print the element that is not repeated

The Following code complies properly for small lists and Timed out error for large sets.

li=list(input());
se=set(li);
for i in se:
    count=0
    for j in li:
        if(j==i):
            count=count+1
    if(count==1):
        print(i)

Success

Timed out

"Success" data set

1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2

Expected result

8

Upvotes: 0

Views: 66

Answers (2)

Rohith V
Rohith V

Reputation: 1123

Another method is by using bit manipulation

def getSingle(arr, n):
    ones = 0
    twos = 0
     
    for i in range(n):
        # one & arr[i]" gives the bits that
        # are there in both 'ones' and new
        # element from arr[]. We add these
        # bits to 'twos' using bitwise OR
        twos = twos | (ones & arr[i])
         
        # one & arr[i]" gives the bits that
        # are there in both 'ones' and new
        # element from arr[]. We add these
        # bits to 'twos' using bitwise OR
        ones = ones ^ arr[i]
         
        # The common bits are those bits
        # which appear third time. So these
        # bits should not be there in both
        # 'ones' and 'twos'. common_bit_mask
        # contains all these bits as 0, so
        # that the bits can be removed from
        # 'ones' and 'twos'
        common_bit_mask = ~(ones & twos)
         
        # Remove common bits (the bits that
        # appear third time) from 'ones'
        ones &= common_bit_mask
         
        # Remove common bits (the bits that
        # appear third time) from 'twos'
        twos &= common_bit_mask
    return ones
     

Upvotes: 0

edusanketdk
edusanketdk

Reputation: 602

from collections import Counter
li=list(input())
cnt = Counter(li)
ans = []

for i in cnt:
    if cnt[i] == 1:
        ans.append(i)

print(*ans)

To find the occurrences of an element in a collection, you can use collections.Counter.

Also, your code's time complexity was exceeding o(n^2), that is why the time out was happening.

Upvotes: 2

Related Questions