Reputation: 13
I'm trying to make a function that returns only the unique number in a list by checking each number in the lists count. but even if it already knows a numbers count is more than 1 it will check that number over and over again which will of course cause a problem when checking a large list, I want it to stop checking counts of a number if it already has been checked, but I can't find any way to do it.
this is my code:
def find_uniq(arr):
for i in arr:
if arr.count(i) == 1:
return i
Upvotes: 1
Views: 102
Reputation: 176
I think one of the easiest ways to do what you're asking is to create a temporary list that stores the numbers that you have already checked, and then check to see if you have checked that number yet.
def find_uniq(arr):
checked_nums = [] #list of all checked numbers
for i in arr:
if i not in checked_nums: #if the number hasn't been checked yet:
if arr.count(i) == 1:
return i
checked_nums.append(i) #add the number to the checked numbers list
Upvotes: 0
Reputation: 811
def find_uniq(arr):
uniqueList = list(set(arr)) # This list contains unique elements in the list "arr".
return uniqueList
In this way, you can easily find unique elements. In fact,
def find_uniq(arr):
return list(set(arr))
This function is also doing the same thing but the first code is easy to understand.
Upvotes: 1
Reputation: 331
This approach should work if you need to find first number that only occurs once. tempSet is here to shrink down the array to smallest way possible.
def find_uniq(arr):
tempSet = list(set(arr))
for i in tempSet:
if arr.count(i) == 1:
return i
Upvotes: 0
Reputation: 279
You can use a dictionary to store the count of each element in the array. More about dictionaries is given in the documentation here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
def find_uniq(arr):
count = {}
for i in arr:
if i in count:
count[i] += 1
else:
count[i] = 1
return count
The returned dictionary gives a count of each element in the array. To find out which element occurs once, simply compare count[elem] to 1.
This is also more efficient as a dictionary is a 'lookup' table whose elements can be accessed in O(1) time. The arr.count function is O(n), because it needs to check the entire array to count the number of times an element is in it.
Upvotes: 0
Reputation: 24049
use set
and check count of unique value.
from doc:
Sets : Python also includes a data type for sets. A set is an unordered collection with no duplicate elements.
like below:
def find_uniq(arr):
ret_arr = []
for i in set(arr):
if arr.count(i) == 1:
ret_arr.append(i)
return ret_arr
Upvotes: 1
Reputation: 1607
use Counter and it will create dictionary:
for example:
from collections import Counter
After that, get the list element where the value of the dictionary is 1
lst =
[k for k,v in mydict.items() if v == 1]
Upvotes: 2
Reputation: 459
You could just convert it into set, it'll only hold unique elements.
arr = list(set(arr))
Upvotes: 0