Python中根据子字符串的顺序识别子字符串并返回响应

发布于 2024-11-28 10:54:56 字数 2021 浏览 1 评论 0原文

我是 Python 的初学者,我正在 Google Code University 在线自学。字符串操作的练习之一如下:

# 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

我被困住了。我知道可以使用 ls = s.split(' ') 将其放入列表中,然后删除各种元素进行排序,但我认为这可能只是为自己创造额外的工作。本课程尚未涵盖 RegEx,因此解决方案不涉及 re。帮助?

这是我尝试过的,但它并不能在所有情况下正确给出输出:

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 > badindex:
        removetext = s[notindex:badindex]
        ns = s.replace(removetext, 'good')
      else:
        ns = s
    else:
      ns = s
  else:
    ns = s
  return ns

这是输出,它在 1/4 的测试用例中工作:

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"

测试用例:

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")

更新:此代码解决了问题:

def not_bad(s):
  notindex = s.find('not')
  if notindex != -1:
    if s.find('bad') != -1:
      badindex = s.find('bad') + 3
      if notindex < badindex:
        removetext = s[notindex:badindex]
        return s.replace(removetext, 'good')
  return s

感谢大家帮助我找到解决方案(而不仅仅是给我答案)!我很感激!

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:

# 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

I'm stuck. I know it could be put into a list using ls = s.split(' ') 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?

Here's what I tried, but it doesn't quite give the output correctly in all cases:

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 > badindex:
        removetext = s[notindex:badindex]
        ns = s.replace(removetext, 'good')
      else:
        ns = s
    else:
      ns = s
  else:
    ns = s
  return ns

Here is the output, it worked in 1/4 of the test cases:

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"

Test Cases:

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")

UPDATE: This code solved the problem:

def not_bad(s):
  notindex = s.find('not')
  if notindex != -1:
    if s.find('bad') != -1:
      badindex = s.find('bad') + 3
      if notindex < badindex:
        removetext = s[notindex:badindex]
        return s.replace(removetext, 'good')
  return s

Thanks everyone for helping me discover the solution (and not just giving me the answer)! I appreciate it!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

单身情人 2024-12-05 10:54:56

好吧,我认为是时候进行一次小审查了;-)

您的代码中有一个错误: notindex > badindex 应改为 notindex <坏索引。更改后的代码似乎工作正常。

另外,我对您的代码有一些评论:

  1. 通常的做法是计算一次值,将其分配给变量并在下面的代码中使用该变量。对于这种特殊情况,此规则似乎是可以接受的:

例如,函数的头部可以替换为

notindex = s.find('not')
if notindex == -1:
  1. You can use return inside of your function 多次。

因此,您的代码尾部可能会显着减少:

if (*all right*):
    return s.replace(removetext, 'good')
return s

最后我想表明您可以使用 split 解决此问题。但这似乎并不是更好的解决方案。

def not_bad( s ):
    q = s.split( "bad" )
    w = q[0].split( "not" )
    if len(q) > 1 < len(w):
        return w[0] + "good" + "bad".join(q[1:])
    return s

Well, I think that it is time to make a small review ;-)

There is an error in your code: notindex > badindex should be changed into notindex < badindex. The changed code seems to work fine.

Also I have some remarks about your code:

  1. It is usual practice to compute the value once, assign it to the variable and use that variable in the code below. And this rule seems to be acceptable for this particular case:

For example, the head of your function could be replaced by

notindex = s.find('not')
if notindex == -1:
  1. You can use return inside of your function several times.

As a result tail of your code could be significantly reduced:

if (*all right*):
    return s.replace(removetext, 'good')
return s

Finally i want to indicate that you can solve this problem using split. But it does not seem to be better solution.

def not_bad( s ):
    q = s.split( "bad" )
    w = q[0].split( "not" )
    if len(q) > 1 < len(w):
        return w[0] + "good" + "bad".join(q[1:])
    return s
感情废物 2024-12-05 10:54:56

像这样分解:

  1. 你如何判断“not”这个词是否在字符串中?
  2. 如果字符串中存在单词“not”,您如何找出“not”一词的何处
  3. 您如何将#1 和#2 合并到一个操作中?
  4. 与 #1-3 相同,除了“坏”这个词?
  5. 鉴于您知道单词“not”和“bad”都在字符串中,您如何确定单词“bad”是否出现在单词“not”之后?
  6. 假设您知道“bad”位于“not”之后,那么如何获取“not”一词之前的字符串的每个部分?
  7. 如何获取“bad”一词后面的字符串的每个部分?
  8. 您如何结合#6 和#7 的答案来替换从“not”一词开头到“bad”一词结尾的所有内容,并用“good”替换?

Break it down like this:

  1. How would you figure out if the word "not" is in a string?
  2. How would you figure out where the word "not" is in a string, if it is?
  3. How would you combine #1 and #2 in a single operation?
  4. Same as #1-3 except for the word "bad"?
  5. Given that you know the words "not" and "bad" are both in a string, how would you determine whether the word "bad" came after the word "not"?
  6. Given that you know "bad" comes after "not", how would you get every part of the string that comes before the word "not"?
  7. And how would you get every part of the string that comes after the word "bad"?
  8. How would you combine the answers to #6 and #7 to replace everything from the start of the word "not" and the end of the word "bad" with "good"?
我们只是彼此的过ke 2024-12-05 10:54:56

既然你正在尝试学习,我不想给你答案,但我会首先在 python 文档中查找一些字符串函数,包括替换和索引。

另外,如果您有一个好的 IDE,它可以帮助您显示哪些方法附加到对象,甚至自动显示这些方法的帮助字符串。我倾向于使用 Eclipse 来处理大型项目,而使用轻量级的 Spyder 来处理小型项目

Since you are trying to learn, I don't want to hand you the answer, but I would start by looking in the python documentation for some of the string functions including replace and index.

Also, if you have a good IDE it can help by showing you what methods are attached to an object and even automatically displaying the help string for those methods. I tend to use Eclipse for large projects and the lighter weight Spyder for small projects

つ低調成傷 2024-12-05 10:54:56

http://docs.python.org/library/stdtypes.html#string-methods

我怀疑他们希望您使用 string.find 来定位各种子字符串:

>>> mystr = "abcd"
>>> mystr.find("bc")
1
>>> mystr.find("bce")
-1

因为您正在尝试自学(荣誉,顺便说一句:)我不会发布完整的解决方案,但还要注意您可以使用索引来获取子字符串:

>>> mystr[0:mystr.find("bc")]
'a'

希望这足以让您开始!如果没有,请在这里评论,我可以发布更多内容。 :)

http://docs.python.org/library/stdtypes.html#string-methods

I suspect that they're wanting you to use string.find to locate the various substrings:

>>> mystr = "abcd"
>>> mystr.find("bc")
1
>>> mystr.find("bce")
-1

Since you're trying to teach yourself (kudos, BTW :) I won't post a complete solution, but also note that you can use indexing to get substrings:

>>> mystr[0:mystr.find("bc")]
'a'

Hope that's enough to get you started! If not, just comment here and I can post more. :)

痕至 2024-12-05 10:54:56
def not_bad(s):
    snot = s.find("not")
    sbad = s.find("bad")
    if snot < sbad:
        s = s.replace(s[snot:(sbad+3)], "good")
        return s
    else:
        return s
def not_bad(s):
    snot = s.find("not")
    sbad = s.find("bad")
    if snot < sbad:
        s = s.replace(s[snot:(sbad+3)], "good")
        return s
    else:
        return s
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文