Censor


#1

I noticed that a solution for censor is

def censor2(text, word):
    return (text.replace(word, "*" * len(word)))

I compared this against what I wrote (am I wrong?),

Solution #1 (Sloppy!):

def censor(text, word):
    words = text.split()
    
    t = ""
    for something in words:
        if something == word:
            t = t + "*" * len(word) + " "    
        else:
            t = t + something + " "
    return t.rstrip()

Solution #2:

def censor2(text, word):
    return (text.replace(word, "*" * len(word)))

print censor("this hack is a wack hack", "hack")
print censor("Ayy Ayy Ayyyy Ayyyy Ayy", "Ayy")
print censor2("this hack is a wack hack", "hack")
print censor2("Ayy Ayy Ayyyy Ayyyy Ayy", "Ayy")

Text printed from Solution 1:
this **** is a wack ****
*** *** Ayyyy Ayyyy ***

Text Printed from Solution 2:
this **** is a wack ****
*** *** ***yy ***yy ***


#2

It's a built-in solution, but what does it teach us? Nothing. It comes up when we reach the stage of refactoring our code to take into consideration all the advantages that Python has built in. Sure it's so we don't re-invent the wheel, but inventing the wheel is at the foundations of learning programming. Algorithms and procedures.

When we know what an abstract approach is doing in procedural terms, we are ready to use abstracts (built-ins). Until then, procedures it is. And lots of them cause there's a 100 ways to boil an egg!


#3

I don't understand because I normally do everything myself (I also don't refactor code, I do work in software though). In the proposed solution the text printed from solution two looks wrong. Why does it remove the Ayy inside Ayyyy?


#4

Procedural code is the slowest because we are putting so much load on the runtime compiler. The compilation process is taking place WHILE our code is running. This is what makes JavaScript so slow. If Python can compile, or at least get a leg up on the compilation process, it will given the tools it affords. If we use those tools, and concepts such as generators in our code we get the benefits in the form of a faster program that uses fewer resources.


#5

Because it is a matching pattern. It doesn't account for adjacent characters. That would take a more specific criterion.