Skip to content

Commit 4d26c4a

Browse files
Update remove_duplicates.py
Redid the solution using dictionaries, didn't realize that they were covered in Ch.9. If you plan on teaching Ch.11 before Ch.9, highly recommend that you don't use this problem.
1 parent 506bf89 commit 4d26c4a

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

2_intermediate/chapter11/solutions/remove_duplicates.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
# The function should look through a list,
44
# Find all duplicate elements, and remove them
55
# 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.
77
# 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
1011

1112
# Example: array = [1,1,2,5,4,6,12,3,4,6]
1213
# Result should print [1,2,3,4,5,6,12]
@@ -16,17 +17,16 @@
1617
list1 = [1, 1, 2, 5, 4, 6, 12, 3, 4, 6] # Define your list
1718

1819

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.
3030

3131

32-
print(remove_duplicate(list1)) # Call the function
32+
print(remove_duplicates(list1)) # Call the function

0 commit comments

Comments
 (0)