How can I edit the commented-off piece of code so that it returns a dictionary of the duplicate numbers rather than returning "{}"?
listOfElems = ["a", "c", "c"]
def checkIfDuplicates_3(listOfElems):
duplicates = {}
for x in listOfElems:
# duplicates = ??
if listOfElems.count(x) > 1:
return duplicates
return duplicates
#test
test = [listOfElems]
for t in test:
output = checkIfDuplicates_3(t)
print("The duplicate in", t, "is", output)
Here's a solution.
If there is more than one of the element in the list, listOfElems.count(x) > 1
, and our list of duplicates doesn't contain the element already, duplicates.count(x) == 0
, then we can add the element to the list of duplicates.
listOfElems = ["a", "c", "c"]
def checkIfDuplicates_3(listOfElems):
duplicates = []
for x in listOfElems:
if listOfElems.count(x) > 1 and duplicates.count(x) == 0:
duplicates.append(x)
return duplicates
# test
test = [listOfElems]
for t in test:
output = checkIfDuplicates_3(t)
print("The duplicate in", t, "is", output)