Censor excercise: https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/censor-?action=resume_content_item


Link: https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/censor-?action=resume_content_item

So I just passed the censor excersise using the code below, and i see that most other solutions in the FAQs use a count so I’m just curious why that is better, and also just general feedback on how it could be more efficient. Many thanks!

def censor(text, word):
  txt = text.split(" ")
  for i in txt:
    if i == word:
      txt[txt.index(i)] = "*" * len(word)
  return " ".join(txt)


The count approach is called naive in that it is akin to a first crack at the solution. It follows simple logic and reasoning and a learner might come up with that solution on their own, given a little thought about the problem.

Of course there are other solutions, such as the one you came up with (which is anything but naive). If we did not know about the .index() method we would never arrive at this answer. Just like most learners at this stage will not know many str methods, including .replace().

I would suggest that efficiency is the last thing we would need to consider at this point on the learning curve. Rather find all the myriad ways of solving this with the use of an algorithm (a plan of attack) that can be expressed in code.

It’s not clever or crafty solutions that are important, here. All working solutions are equally as good for our purposes. Put terms like ‘efficiency’ out of your mind for the time being and wait until you get into the sorts of problems that demand it or they take too long to run, and or use up too mahy resouces.

First we walk, then we run. Right now it is all about walking.


Hi mtf,

thank you for your answer. Got it, I was just checking to see if using the count method has some advantage I was missing, but it’s clear. Thanks!