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)
I don't see why you would need to use a dictionary here. You don't have a key or a value. All you want to do is return a letter which is repeated in a list.
The below code uses list comprehension to solve your problem. First we call this function passing in listOfElems
. Then we will iterate through the given list and check the occurrences of that each element. We can do this using count
. It appears you have used that too. If a letter appears more than once we will append that letter the a new list.
In the example you have provided, we will end up with something like this, ['c','c']
. It would be nice if c
only appeared once. To solve that we can use set
which will give us {'c'}
which is quite nice. To finish it all up, we return this set as a list.
listOfElems = ["a", "c", "c"]
def checkIfDuplicates_3(listOfElems):
dups = [x for x in listOfElems if listOfElems.count(x) > 1]
return list(set(dups))
print("The duplicates in", listOfElems, "are", checkIfDuplicates_3(listOfElems))
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)
Using set
and list comprehension a one-liner function could do:
listOfElems = ["a", "c", "c","e","c","e","f"]
def checkIfDuplicates_3(listOfElems): return set([x for x in listOfElems if listOfElems.count(x)>1])
#test
test = [listOfElems]
for t in test:
output = checkIfDuplicates_3(t)
print("The duplicate in", t, "is", sorted(output))
Note that order of insertion may not be preserved by set. To get ordered output, use sorted
(as shown in example above).
To get a dictionary counting the number of occurences>1 you may use:
def checkIfDuplicates_3(listOfElems):
return {x:listOfElems.count(x) for x in set(listOfElems) if listOfElems.count(x)>1}
eg returning for checkIfDuplicates_3(listOfElems)
the result {'e': 2, 'c': 3}
(see note for ordering above).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.