|
| 1 | +# Write a function called remove_duplicates |
| 2 | +# The sole parameter of the function should be a list |
| 3 | +# The function should look through a list, |
| 4 | +# Find all duplicate elements, and remove them |
| 5 | +# Sort the resulting list |
| 6 | +# YOU MAY NOT USE THE set() function IN PYTHON. |
| 7 | +# Hint: To sort a list, use sorted(list) |
| 8 | +# Another hint: Use dict.fromkeys(list) |
| 9 | +# To take the elements from a list, |
| 10 | +# and convert them to keys in a dictionary |
| 11 | + |
| 12 | +# Example: array = [1,1,2,5,4,6,12,3,4,6] |
| 13 | +# Result should print [1,2,3,4,5,6,12] |
| 14 | + |
| 15 | +# Write code here |
| 16 | + |
| 17 | +list1 = [1, 1, 2, 5, 4, 6, 12, 3, 4, 6] # Define your list |
| 18 | + |
| 19 | + |
| 20 | +# Define your Function |
| 21 | +def remove_duplicates(array): |
| 22 | + my_list = list(dict.fromkeys(array)) |
| 23 | + # Converts the list into a dictionary. |
| 24 | + # Fromkeys(array) turns each item into a key |
| 25 | + # There cannot be multiple keys, |
| 26 | + # So all the duplicate keys are removed |
| 27 | + # Convert the keys back into a list |
| 28 | + return sorted(my_list) |
| 29 | + # Returns the sorted list of keys that are not duplicate. |
| 30 | + |
| 31 | + |
| 32 | +print(remove_duplicates(list1)) # Call the function |
0 commit comments