Note that there are some explanatory texts on larger screens.

plurals
  1. POIdentify substrings and return responses based on order of substrings in Python
    text
    copied!<p>I am a beginner in Python, I am teaching myself off of Google Code University online. One of the exercises in string manipulation is as follows:</p> <pre><code># E. not_bad # Given a string, find the first appearance of the # substring 'not' and 'bad'. If the 'bad' follows # the 'not', replace the whole 'not'...'bad' substring # with 'good'. # Return the resulting string. # So 'This dinner is not that bad!' yields: # This dinner is good! def not_bad(s): # +++your code here+++ return </code></pre> <p>I'm stuck. I know it could be put into a list using <code>ls = s.split(' ')</code> and then sorted with various elements removed, but I think that is probably just creating extra work for myself. The lesson hasn't covered RegEx yet so the solution doesn't involve re. Help?</p> <p>Here's what I tried, but it doesn't quite give the output correctly in all cases:</p> <pre><code>def not_bad(s): if s.find('not') != -1: notindex = s.find('not') if s.find('bad') != -1: badindex = s.find('bad') + 3 if notindex &gt; badindex: removetext = s[notindex:badindex] ns = s.replace(removetext, 'good') else: ns = s else: ns = s else: ns = s return ns </code></pre> <p>Here is the output, it worked in 1/4 of the test cases:</p> <pre><code>not_bad X got: 'This movie is not so bad' expected: 'This movie is good' X got: 'This dinner is not that bad!' expected: 'This dinner is good!' OK got: 'This tea is not hot' expected: 'This tea is not hot' X got: "goodIgoodtgood'goodsgood goodbgoodagooddgood goodygoodegoodtgood goodngoodogoodtgood" expected: "It's bad yet not" </code></pre> <p>Test Cases:</p> <pre><code>print 'not_bad' test(not_bad('This movie is not so bad'), 'This movie is good') test(not_bad('This dinner is not that bad!'), 'This dinner is good!') test(not_bad('This tea is not hot'), 'This tea is not hot') test(not_bad("It's bad yet not"), "It's bad yet not") </code></pre> <p><strong>UPDATE:</strong> This code solved the problem:</p> <pre><code>def not_bad(s): notindex = s.find('not') if notindex != -1: if s.find('bad') != -1: badindex = s.find('bad') + 3 if notindex &lt; badindex: removetext = s[notindex:badindex] return s.replace(removetext, 'good') return s </code></pre> <p>Thanks everyone for helping me discover the solution (and not just giving me the answer)! I appreciate it!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload