|
3 | 3 | # The function should look through a list, |
4 | 4 | # Find all duplicate elements, and remove them |
5 | 5 | # Sort the resulting list |
6 | | -# YOU MAY NOT USE THE set() function IN PYTHON. Use this problem to practice list iteration! |
| 6 | +# YOU MAY NOT USE THE set() function IN PYTHON. |
7 | 7 | # Hint: To sort a list, use sorted(list) |
8 | | -# Another hint: Use list.count(element) |
9 | | -# To count the number of times that element appears |
| 8 | +# Another hint: Use dict.fromkeys(list) |
| 9 | +# To take the elements from a list, |
| 10 | +# and convert them to keys in a dictionary |
10 | 11 |
|
11 | 12 | # Example: array = [1,1,2,5,4,6,12,3,4,6] |
12 | 13 | # Result should print [1,2,3,4,5,6,12] |
|
16 | 17 | list1 = [1, 1, 2, 5, 4, 6, 12, 3, 4, 6] # Define your list |
17 | 18 |
|
18 | 19 |
|
19 | | -def remove_duplicate(array): |
20 | | - for i in array: |
21 | | - # Checks if element appears multiple times |
22 | | - for j in range(i, len(array) - 1): |
23 | | - # Counts the number of times an element appears. |
24 | | - if array.count(array[i]) == 1: |
25 | | - break # If it appears once, break out of the loop |
26 | | - else: |
27 | | - # If it appears more than once, remove it |
28 | | - array.remove(array[i]) |
29 | | - return sorted(array) # Sorts the list |
| 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 | 30 |
|
31 | 31 |
|
32 | | -print(remove_duplicate(list1)) # Call the function |
| 32 | +print(remove_duplicates(list1)) # Call the function |
0 commit comments