14/15 remove_duplicates : my solution vs the given solution, better?


#1

Here is my solution to the problem:

def remove_duplicates(same):
  if same == []:
  	return []
  unique = []
  for i in same:
    if i not in unique:
      unique.append(i)
  return unique

Here is the given solution, is there a benefit to doing it this way instead?

def remove_duplicates(inputlist):
    if inputlist == []:
        return []
    
# Sort the input list from low to high    
    inputlist = sorted(inputlist)
# Initialize the output list, and give it the first value of the now-sorted input list
    outputlist = [inputlist[0]]

# Go through the values of the sorted list and append to the output list
# ...any values that are greater than the last value of the output list
    for i in inputlist:
        if i > outputlist[-1]:
            outputlist.append(i)
        
    return outputlist

#2

The author used slightly different logic to arrive at the same outcome.

When two different approaches are compared, the only real comparison, assuming the both are error free is their benchmark time.

Something else to consider, though, is the order. Your method preserves order of first occurrence where the given solution does not. I would favor yours for that reason.

This check is not needed. If the supplied list is empty, unique will return empty.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.