【问题标题】:Using While True loops使用 While True 循环
【发布时间】:2017-07-14 02:03:34
【问题描述】:

我应该编写一个代码来检查单词的某些音节(例如:inexare)。如果单词仅由这些音节组成,则代码返回“Yes”,否则返回“No”(如果该单词还包含其他音节)。该作业要求我使用while true 循环,虽然我想出了一种更简单的方法来使这段代码工作,但我不太清楚从哪里开始为这个问题制作while true 循环。

我当前的代码仅适用于 具有所有音节的单词:

def check(word):
    pos = 0
    while True:
        if pos < len(word):
            if word[pos:pos+2] == "in":
                pos += 2 
                break
            if word[pos:pos+2] == "ex":
                pos += 2
                break
            if word[pos:pos+3] == "are":
                pos += 3 
                break
    return "YES"

【问题讨论】:

  • 向我们展示你已经完成的代码
  • while True: pass。运行然后等待(不要这样做:))
  • 使用anyallwhile True: ... break 好得多
  • 您的问题是在考虑一种算法,还是您已经有了一个您认为应该可以工作的算法并且只需要帮助编写代码?这个问题不清楚。

标签: python if-statement while-loop conditional-statements words


【解决方案1】:

如果你出于某种原因决定使用 while 循环,它会是这样的:

i = 0

while True:

    i += 1
    word = words[i]

    if (syllables in word):
        print('Syllables are in word')
    else:
        print('Syllables not in word')

    if i > len(words):
        break

但是,这可能是解决问题的更糟糕的方法。在遍历一个集合时,使用for 循环通常更有效,以防止不必要地检查整个集合是否已被检查。 for 循环实现可能如下所示:

for s in syllable_set_1:
    if s in word:
        print('Syllable ' + s + ' is in word')
    else:
        print('Syllable ' + s + ' is not in word') 

【讨论】:

    【解决方案2】:

    对于重叠的音节,您实际上可能需要某种回溯。一个简单的解决方案可以使用 while ... else,像这样:

    syllables = ["in", "ex"]
    word = "exinex"
    while word:
        matches = [s for s in syllables if word.startswith(s)]
        if not matches:
            print "unable to find syllable for " + word
            break
        word = word.replace(matches[0], "", 1)
    else:
        print "only expected syllables found"
    

    【讨论】:

      【解决方案3】:

      无需您的实际代码,而 True-Loops 可用于继续询问用户输入,直到输入了特殊的“停用词”。

      while True:
          text = input("Enter next word to check, end to exit")
          if text=="end":
              break
          else:
              #... your syllable checking
      

      这将允许用户输入几个单词进行检查,而不必每次都重新启动程序。

      【讨论】:

        【解决方案4】:

        你可以做类似的事情

        words = iter(words)
        while True:
            try:
                if next(words) in allowed_words:
                    continue
                else:
                    return 'Yes'
            except StopIteration:
                return 'No'
        

        【讨论】:

        • return 没有函数诶
        • 好的,我说的是类似。 OP 似乎对问题的理解足以适应它
        • 为什么要尝试:除非出于兴趣需要?
        • 当迭代器用完单词时,它会抛出一个StopIteration 异常。所以,你知道你已经检查了所有的单词,你必须返回
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-23
        • 2016-12-03
        • 2014-07-30
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        相关资源
        最近更新 更多