I am trying to check if a list constitutes a set. I created a code to check for the duplicates, and if there are duplicates in the list which means it is not set, it should output False and convert it to the desired set; if there are no duplicates, the output should be True. But when I run my code, it gives no output, I tried to change the return to print, but it printed the value by each iteration time instead of once. I don't understand what is wrong.
def testsets(array):
for elem in array:
if array.count(elem) > 1:
return False, " the set should be: ", set(array)
else:
return True
testsets([1, 2, 3, 4, 5])
testsets([1, 1, 3, 2, 3])
testsets([0])
Expected output
True
False the set should be: {1, 3, 2}
True
But it doesn't show any output, and when I change return to print, it prints it multiple times.
CodePudding user response:
Aren't you supposed to print the output?
print(testsets([1, 1, 3, 2, 3]))
Output:
(False, ' the set should be: ', {1, 2, 3})
Note return followed by commas generates a tuple if you want a string return this instead:
return f"False, the set should be: {set(array)}"
Also to check if there're duplicates is better to do this:
if len(set(array)) != len(array)