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
A few pointers:
woord
is not callable, so woord()
will throw a TypeError
.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.list(my_string)
will just build a list of characters. 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'
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