campusx-official / dsmp-2022-23

All the codes and tasks taught in the CampusX Data Science Mentorship Program 2022-23
7 stars 1 forks source link

Maintaining Order after removing Duplicates #6

Open samp-suman opened 1 year ago

samp-suman commented 1 year ago

I have written the code for removing duplicates Question. For input AAAAAABHISHEK answer is coming out correctly but if input is suppose AAAAABBHISHAAAAK the order gets shuffled how to tackle that

# Code here
 data = input('enter a data to work upon ')
data = list(data)
 for i in data:
   if data.count(i) ! = 1:
     for j in range (data.count(i)-1):
       data.remove(i)
   else:
     continue
 data = ". join(data)
 print(data)
samp-suman commented 1 year ago

What you are doing in your code is removing the character no of count-1 times. Which is one of the approaches to solve this problem.

But if you want to maintain the order like-- abcabbdcdad your output should be- abcd. This will not be achieved by your approach. Because .remove() function will remove the very first character it matches. For example after removing all duplicates of character 'a' you will be left with- "bcbbdcdad". It will only leave the last occurrence of 'a'.

Other approach suggestions- go through the string character by character and store it in a list only if that character is not already in the list. something like this --

for i in string: 
  if i not in data:
    dada.append(i)

I believe you Understood.

Happy Learning!!