I'm currently studying Python 2.7 from an online course. One of the problems is I have to remove a char from a string based from a list of chars.
What I did was:
def getAvailableLetters(letters):
alphabet = string.ascii_lowercase
reduced_alphabet = ''
for char in alphabet:
if char not in lettersGuessed:
reduced_alphabet += char
return reduced_alphabet
I've learned that there's no such thing as a string method to directly remove a char from a string as they are immutable, so I came up with this. I've successfully submitted a correct answer, but I'm not quite satisfied with it as I feel like there's a more efficient way to do it.
Fastest way would be to use str.translate here:
>>> lettersGuessed = ['a', 'b', 'c']
>>> 'wedqwdasdasccdshjasdcas'.translate(None, ''.join(lettersGuessed))
'wedqwdsdsdshjsds'
if lettersGuessed is already a string then remove the ''.join call.
Timing results compared to str.join and filter, taken from @thefourtheye's solution:
def getAvailableLetters2(lettersGuessed):
return string.ascii_lowercase.translate(None, lettersGuessed)
from timeit import timeit
print 'filter-->', timeit("getAvailableLetters('Welcome')", setup="from __main__ import getAvailableLetters")
print '.join-->', timeit("getAvailableLetters1('Welcome')",setup="from __main__ import getAvailableLetters1")
print 'trans-->', timeit("getAvailableLetters2('Welcome')",setup="from __main__ import getAvailableLetters2")
Output:
filter--> 6.49355100548
.join--> 4.02496357229
trans--> 0.69938109531
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With