In: Computer Science
Python Question
Using lists, write the function non_unique(list) that takes a
list list as argument. It
returns a list which duplicated elements remains and each
duplicated element is followed by
a number which shows how many times it appears. All elements in
return list should be in
the same order as their appearance in the original list.
For example, given the input [‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘d’,
‘a’,‘e’], the function
would return [‘a’, 3, ‘b’, 2]. Another example, ['abc', 'def',
'abc', 'xyz', 'def','def', 'qwe'] -> ['abc', 2, 'def', 3]
If no such non_unique list exist, just return an empty list.
Your program should contain the function with format shown as
below:
def non_unique(list):
# Your codes here
return result # ‘result’ is a list.
#code
def non_unique(mylist):
newelements = dict()
# Iterate over each element in list
for element in mylist:
# If element exists in dict then increment its value else add it in dict
if element in newelements:
newelements[element] += 1
else:
newelements[element] = 1
# Filter key-value pairs in dictionary. Keep pairs whose value is greater than 1 i.e. only duplicate elements from list.
newelements = { key:value for key, value in newelements.items() if value > 1}
#convert dictionary to list
newlist=list(newelements.items())
# Returns a list of duplicate elements and thier frequency count
return newlist
# List of strings
mylist = ['a','b','c','a','b','d','a','e']
# Get a list containing duplicate elements in given list and their frequency count
newlist = non_unique(mylist)
#result
print(newlist)
co#screenshot of code and output
output 2:
--------------------------------------------------------------