10. censor - alternative solution?


#1



Here's the link to the exercise.

So. I wrote this code, choosing basically the simplest solution which came to my mind. And it works. (I also played a little adding the option 'What if the word is nit in the string?" and thought I'm quite smart. )

def censor(text, word):
    replacement = '*' * len(word)
    if word in text:
        text = text.replace(word, replacement)
        return text
    if word not in text:
        print "We couldn't find the word."
        
print censor("this hack is wack hack", "hack")
print censor("this hack is wack hack", "hag")

Then scrolled through the forum and saw people coming up with solutions using str.split(), like this one below.

def censor(text, word):
    count = len(word)
    tear = text.split()
    new = ""
    for item in tear:
        if item == word:
            new = new +" " + ("*" * count)
        else:
            new = new + " " + item
    sliced = new[1:]
    return sliced

My question is: are they both fine? I mean, they are both working and you get what you need to get... Is one of them 'better'? And if so, why?

I'm awfully new to programming, so I'd be grateful if someone explained the differences.


#2

there is no 'better' code, it depends on who is viewing the code, one is just simpler to read, the other is more efficient to the computer. in most cases programmers refer to the most efficient code as 'better', but i prefer to call the easier to read better, its just a matter of preferences


#3

i would use your approach. For the simple reason that strings are immutable in python.

if you concate strings in python, a new string with the combined result is handed back to you, this is memory wise not very efficient. your approach only does string mutation once, where as the other code does this many times.

as for readability, there is not much differences between this two codes, so i would go for the most efficient one.

Also, if you word is not found in text you can simply return text:

def censor(text, word):
    replacement = '*' * len(word)
    if word in text:
        text = text.replace(word, replacement)
    return text

this will simply return the string and show the user there was nothing to censor


#4

Thank you guys.
Way more clear now :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.