Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
3 solutions solution in Clear category for Non-unique Elements by donnythelegend
def checkio(data: list) -> list:
## Solution 1: Populate a new list looping forward.
## Initialize an empty list for the new data.
#data_new = []
# Loop through data.
#for i in data:
# # Check if the frequency of the element greater than 1 (not unique).
# if data.count(i) > 1:
# # Append the element to data_new if so.
# data_new.append(i)
## Return data_new.
#return data_new
## Delete data since it's no longer needed in this case.
#del(data)
## Solution 2: Remove elements from data looping backward.
## Note that we go backward in this case so that elements aren't skipped in the loop due to removal.
## Loop through reversed data.
#for i in data[::-1]:
# # Check if the frequency of the element is 1 (unique).
# if data.count(i)==1:
# data.remove(i)
# Return data.
#return data
# Solution 3: Basically the same as Solution 1, but more compact.
# Loop through the data and populate new list using elements with frequency greater than 1 (not unique).
return [i for i in data if data.count(i) > 1]
# Delete data since it's no longer needed in this case.
del(data)
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example"
assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example"
assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example"
assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example"
print("It is all good. Let's check it now")
April 18, 2021
Comments: