+ 6

How do I use python to remove duplicates in a string, and return it's number?

Write a function called remove_duplicates which will take one argument called string. This string input will only have characters between a-z. The function should remove all repeated characters in the string and return a tuple with two values: A new string with only unique, sorted characters. The total number of duplicates dropped. For example: remove_duplicates('aaabbbac') => ('abc', 5) remove_duplicates('a') => ('a', 0) remove_duplicates('thelexash') => ('aehlstx', 2)

27th Feb 2017, 8:32 PM
Mcdavid
Mcdavid - avatar
7 Respuestas
+ 9
I've just created this for you, and I hope it helps: def removeDupes(chars): new_chars = [] new_form = [] for i in range(0,len(chars)): if i == 0: new_chars+= chars[0] else: if chars[i] not in new_chars: new_chars+= chars[i] new_form.append("".join(new_chars)) new_form.append(len(new_form[0])) return new_form theChars = "aaassffyyttbuuwweeyyffbbccxhg" newChars = removeDupes(theChars) print("The new string: " + newChars[0] + " has a length of " + str(newChars[1])) Loop through chars but first store the first one, then proceed to check if the next target is NOT IN the new formed string and if it isn't add it. Once done. At list or array index 0 join string together with no spaces, and then count the length storing it at index 1 and return the array.
27th Feb 2017, 9:55 PM
Mark Foxx
Mark Foxx - avatar
+ 2
before = 'aaabbbac' after = ''.join(sorted(set(before))) n_removed = len(before) - len(after)
27th Feb 2017, 11:37 PM
Twelfty
Twelfty - avatar
+ 1
Try a nested for cycle in another for cycle iterating over letters in a string, with counter, that will increment when letters match each other.
27th Feb 2017, 8:37 PM
Leshark
Leshark - avatar
+ 1
hello Mcdavid . Could share your code solution .please I need to see how this problem was solved.
12th Apr 2017, 3:50 PM
franciz
0
Thanks guys i got through it thanks to you, my problem was that I was omitting the s.join() function
1st Mar 2017, 7:15 AM
Mcdavid
Mcdavid - avatar
0
Mcdavid, Could paste the code here,I could like to see the solution .thanks.
12th Apr 2017, 3:52 PM
franciz