1

I'm trying to remove duplicates in a string upon user input. Here''s my code:

userinput = input("Enter a word:")
def duplicates_removal(x):
      for i in range(len(x)-1):
             if x[i] == x[i +1]:
                     return duplicates_removal(x.replace(x[i], ' '))
      return x 

print(duplicates_removal(userInput))

When I run the code, and input the string Bananas, it produces the output Bananas with the duplicates not removed. Is there any flaws in the code? Also I prefer not using built in functions for this since I just started learning on string manipulation.

Input: Bananas
Output desired: Bans
Electric
  • 517
  • 11
  • 25
  • 1
    you're just comparing each character to the previous character (`x[i] == x[i+1]`) that's the flaw. – dirkgroten Mar 29 '17 at 09:18
  • You say "I prefer not using built in functions for this", but you're using the built-in `range` and `len` functions, and the `str.replace` method, not to mention `input` and `print`. – PM 2Ring Mar 29 '17 at 09:45
  • There are several better ways to do this. It's _possible_ to make your recursive approach work with a couple of minor alterations (and no additional functions), but the resulting code is inefficient and not particularly easy to read. I guess it makes a fun "code golf" puzzle, but doing this sort of thing is _not_ a great way for a beginner to learn Python. – PM 2Ring Mar 29 '17 at 09:49
  • See https://pastebin.com/ByCa4R07 – PM 2Ring Mar 29 '17 at 10:10

1 Answers1

-1
def duplicates_removal(x):
    l = []
    for each in x:
        if each not in l:
            l.append(each)
    return "".join(l)
Technocrat
  • 99
  • 2
  • 11
  • 4
    @TigerhawkT3 The OP isn't asking for the best algorithm for this task. They want to understand why their existing code doesn't do what they expect. And they certainly _didn't_ ask for someone to write the code for them. – PM 2Ring Mar 29 '17 at 09:57