【问题标题】:I before E program not working我在 E 程序之前不工作
【发布时间】:2014-10-20 02:27:43
【问题描述】:

刚刚写了一个python程序来确定助记符“I before E except after C”的用处。

输入:

'I before e except when conducting an efficient heist on eight foreign neighbors. I believe my friend has left the receipt for the diet books hidden in the ceiling'

它会显示:

Number of times the rule helped: 5
Number of times the rule was broken: 5

改变了一些东西,我以为我把它们改回来了,但代码现在已经坏了,任何建议都会有所帮助

while True:

    line = input("Line: ")                         
    count = 0                                       
    h = 0
    nh = 0


    words = line.split()                            
    for x in range(0, len(words)):                  
        word = words[count]

        if "ie" in word:                            
            if "cie" in word:                     
                nh += 1
            else:
                h +=1

        if "ei" in word:
            if "cei" in word:
                h += 1
            else:
                nh += 1
        else:
            h += 0
    count += 1                                      

    print("Number of times the rule helped:",h)     
    print("Number of times the rule was broken:",nh)
    print()

【问题讨论】:

  • 也许 x 应该做索引,而不是计数?
  • 欢迎来到 Stackoverflow。我们不是在这里倾注您的整个程序并猜测问题可能是什么。请提供有关代码“损坏”原因的具体信息。有没有不成功的测试用例?如果是这样,请向我们提供有关它的所有详细信息。
  • 抱歉没有提供足够的信息,我还是新手。发生的事情是我之前发布的输入没有任何时候规则帮助或被破坏,在返回答案的意义上没有来自程序的响应。但是,它仍然会检测较小输入中的规则破坏/遵循。我不确定为什么或如何,但我认为我已经以某种方式打破了 for 循环或逻辑
  • @musical_coder: "毛孔"。
  • 不要忘记像“古代”这样的奇怪词:)

标签: if-statement for-loop python-3.x input


【解决方案1】:

天哪,我是个白痴。我可能总共花了 3 个小时左右的时间来修复这个问题。

for x in range(0, len(words)):                  
    word = words[count]

    if "ie" in word:                            
        if "cie" in word:                       
            nh += 1
        else:
            h +=1

    if "ei" in word:
        if "cei" in word:
            h += 1
        else:
            nh += 1
    count += 1   

谁能发现这与旧代码的相应部分之间的区别?最后的 'count+=1' 只是缩进了一次。所有这些时间都浪费了......如果我在这里浪费了其他人的时间,我很抱歉:|

【讨论】:

  • 呵呵,欢迎来到我们的世界 :) 说真的,坚持下去做得很好——很多人在类似的编码直线上就放弃了。话虽如此,我认为您甚至不需要count- 只需使用word = words[x]
【解决方案2】:

如果您能更好地表达您的测试用例,您会得到很好的帮助。我不完全明白你想要做什么。

您似乎只需要查看文本中出现了多少次“cie”或“cei”。

在这种情况下:

for i in range(0, len(line)):

    print("scanning {0}".format(line[i:i+3]))
    if line[i:i+3].lower() == "cie":
        nh += 1
    if line[i:i+3].lower() == "cei":
        h += 1

【讨论】:

  • 嗯,好像没用。好主意,但它似乎应该奏效。我去看看
  • 我很抱歉,但是像“这似乎不起作用”这样的 cmets 是没用的。除非您可以提供非常明确的错误反馈等,否则您不会在 stackoverflow 上找到太多帮助。祝您调试工作顺利。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 2019-08-20
相关资源
最近更新 更多