-2

Can someone help me to go from this:

'BANANARAMA'

to

'BANRM'

in Python? I already tried this:

def reduceer(woord):
    return ''.join(c for c, in list(woord()))

but it won't work

timgeb
  • 76,762
  • 20
  • 123
  • 145
joan
  • 1
  • 1

2 Answers2

2

A few pointers:

  1. woord is not callable, so woord() will throw a TypeError.
  2. c, is trying to unpack a sequence of length one. This will work with lines like c, = 'x' but is pointless because characters (over which you are trying to iterate) already have length one.
  3. There is nothing in your code to remove the duplicates, list(my_string) will just build a list of characters.
  4. In addition to not removing duplicates, list does not do anything useful here, because strings are already iterable.

I won't rewrite your function, but here's the lazy man's approach for CPython 3.6 (or any 3.7 version):

>>> ''.join(dict.fromkeys('BANANARAMA'))
'BANRM'
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

You may create a new list, add every character only once (by checking if it is already in that list) and use join to create a new string

def reducer(word):
  res = []
  for ch in word:
    if(ch not in res):
      res.append(ch)
  return ''.join(res)

Test it:

print(reducer('BANANARAMA'))

Output:

BANRM
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93