Practice makes perfect_censor


#1

ERROR:
Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "['h', 'e', 'y', ' ', 'h', 'e', 'y', ' ', 'h', 'e', 'y']" when it should return "*** *** ***".

PROGRAM:(WHAT`S WRONG)

def censor(text,word):
newword=[]
s=len(word)
for phrase in text :
p=[]
if phrase==word:
i=1
while i<=s:
newword=p.append('*')
i=i+1
newword.append('')
else:
flag=True
newword.append(phrase)
return newword


#2

    newword = []

The first step is correct, if we follow your approach--a temporary list of terms.

    s = len(word)

Useful, perhaps, but unnecessary since we only see it once in the code.

    for phrase in text:

This is a little bit misleading since text is a phrase. Consider the singular, term.

    for term in text:

Just a semantics thing I have, but your readers are people like me, doing their best to understand your code from the clues contained in variable and object names.

The above segment of code is overkill, to be blunt, albeit interesting insight. The effort is lost since the desired effect never comes about.

    flag = True

Not sure I understand this line, or what purpose it serves.

    return newword

Needs to be a string. Read up on the join method, once you have the result you want to return.


#3

I changed the code
I got this error:

Oops, try again. Your function crashed on ('hey hey hey', 'hey') as input because your function throws a "'NoneType' object has no attribute 'append'" error.

def censor(text,word):
newword=[]
s=len(word)
a=text.split()
for phrase in a:
if phrase==word:
newword=newword.append('*' * s)
else:
newword.append(phrase)
return newword


#4

1st splitting the sentence/string into list is important I guess!


#5

My code finally ran.

I changed

*newword=newword.append('' * s) **
**to **
newword.append('*' * s)

Can anyone tell the difference the above makes?

full code:

def censor(text,word):
newword=[]
s=len(word)
a=text.split()
for phrase in a:
if phrase==word:
newword.append('*' * s)
else:
newword.append(phrase)
return " ".join(newword)


#6

>>> from random import randint
>>> while True:
    while randint(0,10):
        print (".",)
    print ("Bye")
    break

This is a segue that is purely thought experiment. It will take you away from the immediate problem and cast you into the conceptual lane where the speed is different. Now you get up to speed and move back into the exercise lane.


#7

What does it mean? I did not get you .


#8

s in your code is a random value. Can you write a simulation that will reproduce over a range of random inputs?


#9

BTW i rny program successfully .But why we don`t hav to split the stirng?????

def count (sequence,item):
# a=sequence.split(' ')
count=0
for i in sequence:
if i==item:
count=count+1
return count


#11

sequence is already a list. We only use split on a string.


#12

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