+ 1
Help with code to remove duplicate in a string and return tuple of the remaining word and number of word removed python
4 Answers
+ 6
- 'remove' is a method of list objects, not strings, and get an argument to remove from the list on wich the method is applied.
- 'set' return a set of unique elements ( remove dupicates ) from a list. Passing a string instead a list is possible, but will split the string in an array of character, so the result of 'set(string)' is not an array of words...
Instead of implicitly auto-split your string in an array of characters, split it explicitly withs spaces:
words = string.split(" ")
... you maybe must do some treatment to trim words of punctuation, spaces remainig ( empty items in list if many successives spaces in the string ).
Then use the set() function on the 'words' list, give you the list of unique words:
unique_words = set(words)
Now, you need to implement the counting of words, remove those wich have a count greater than one, and get the count of thoses removed ( according to your needs, can be the count of unique words removed, or the count of words removed in original string... ). For that, initialize a count variable to zero before removing words, and each time you remove a word, increment your counter...
Anyway, did your problem suppose that there is necessarly once unique word supposed to be remaining?
If not, you should think to return a tupple with a list of word and the removed word count insread of just a tupple word/count.
+ 4
Show your code for getting help ^^
+ 1
Remove = string. remove
If len(set (string))! = len(string)
return (Remove, len(Remove))
+ 1
def remove_duplicates(string):
s = list(string)
t = set(s)
final = len(string) - len(t)
return "".join(t), final
print(remove_duplicates("aaabbbac"))
>>('acb', 5)