【问题标题】:Find the longest substring in alphabetical order. What is wrong with my code按字母顺序查找最长的子串。我的代码有什么问题
【发布时间】:2018-07-06 21:22:42
【问题描述】:

到目前为止,我有:

s = 'azcbobobegghakl'
i = 0
j = 1 

temp = ''  #temporary variable I use to change longest
longest = ''   
for b in range(len(s)):
    if s[i] <= s[j]: #checks if it's in alphabetical order
        temp+=s[i] 
        if len(longest) < len(temp):
           longest  = temp       
    else: 
        temp = ''    #reset temp after every substring  
    if len(longest) < len(temp):
        longest  += temp      #update longest if the new substring is longer
    i +=1
    if j < len(s) - 1 : # because otherwise i get an IndexError
       j +=1


print('Longest substring in alphabetical order is:', longest)

现在我的问题是我总是得到正确的字符串但没有最后一个字母。 (例如,这里不是“beggh”,而是“begg”)。

我还必须做到,如果是平局,第一个算作最长的(如果 s = abcbcd,abc 应该是最长的)

最后我知道这个问题已经在这里被问过好几次了,但我想尽可能修复我想出的代码,而不是完全使用别人的代码。

【问题讨论】:

  • 如果我一直在思考你的代码,我会头疼的。有太多的事情在我的思维方式中没有意义。只需要几个一般提示:不要使用ij,使用ii+1。为避免最后出现 IndexError,不要迭代 range(len(s)),迭代 range(len(s)-1)。最后,不要遍历bb 不用于其他任何用途。遍历i。这种变化会清理很多东西和困难。
  • @ti7 findall 到底如何找到按字母顺序排列的字符串?
  • @Poshi 感谢您的建议。希望现在可以更好地理解。
  • 更好。但是您不必初始化i,它会在for 循环中被覆盖。增量相同,它将被for 循环的下一次迭代覆盖。
  • @NikolaiTh3KillerKirilov 请不要根据给出的答案更新您的问题。否则,这些答案对未来的用户毫无意义。

标签: python python-3.x alphabetical longest-substring


【解决方案1】:

您将s[i]s[i+1] 进行比较,但仅将s[i] 添加到temp。而是始终以temp 中的当前字母开头,并在比较后将s[i+1] 添加到temp

s = 'azcbobobegghakl'
i = 0

temp = s[0]   #temporary variable I use to change longest
longest = ''   
for i in range(len(s)-1):
    if s[i] <= s[i+1]:  #checks if it's in alphabetical order
        temp+=s[i+1]
        if len(longest) < len(temp):
           longest  = temp       
    else: 
        temp = s[i+1]     #reset temp after every substring
    if len(longest) < len(temp):
        longest  += temp    #update longest if the new substring is longer
    i +=1



print('Longest substring in alphabetical order is:', longest)

# Longest substring in alphabetical order is: beggh

【讨论】:

    【解决方案2】:

    如果您发现下一个字符不是按字母顺序排列的,您就没有考虑当前字符,这就是您最后缺少一个字符的原因。

    相反,如果下一个字符不按顺序排列,则应始终先处理当前字符,然后再重置 temp

    s = 'azcbobobegghakl'
    i = 0
    
    temp = ''   #temporary variable I use to change longest
    longest = ''   
    for i in range(len(s)-1):
        temp += s[i]
        if len(longest) < len(temp):
            longest = temp
        if s[i] > s[i+1]:  #checks if it's in alphabetical order
            temp = ''     #reset temp after every substring
        if len(longest) < len(temp):
            longest  += temp    #update longest if the new substring is longer  
        i +=1
    
    
    
    print('Longest substring in alphabetical order is:', longest)
    

    这个输出:

    Longest substring in alphabetical order is: beggh
    

    【讨论】:

      【解决方案3】:
      s = 'azcbobobegghakl'
      i = 0
      j = 1 
      
      temp = ''  #temporary variable I use to change longest
      longest = '' 
      
      
      for b in range(0, len(s) -1):
          if s[b] <= s[b + 1]: #checks if it's in alphabetical order
              if len(temp) == 0:
                  temp+= s[b]
                  temp+= s[b+1]
              else:
                  temp+= s[b+1]
      
              if len(longest) < len(temp):
                 longest  = temp       
          else: 
              temp = ''    #reset temp after every substring  
          if len(longest) < len(temp):
              longest  += temp      #update longest if the new substring is longer
          i +=1
          if j < len(s) - 1 : # because otherwise i get an IndexError
             j +=1
      
      
      print('Longest substring in alphabetical order is:', longest)
      

      【讨论】:

        【解决方案4】:

        虽然我在其他答案中提到了如何修复您的代码,但我还想说直接的方法是使用itertools.accumulate

        list(accumulate(s, lambda s, c: s+c if s[-1]<=c else c) )
        # ['a', 'az', 'c', 'b', 'bo', 'b', 'bo', 'b', 'be', 'beg', 'begg', 'beggh', 'a', 'ak', 'akl']
        

        所以按字母顺序查找最长子字符串的单行是

        sorted(accumulate(s, lambda s, c: s+c if s[-1]<=c else c), key=len)[-1]
        # 'beggh'
        

        【讨论】:

          【解决方案5】:

          要在最后解决问题,您需要在代码到达最终索引时对其进行某种中断。此外,如果您到达字符串的末尾并且它仍然按字母顺序排列(见下文),您需要添加一些代码来重置循环。最后,对于最长字符串只有一个字符的情况,您需要在 s[0} 处定义最长的单词和单词的起始变量。只要坚持下去,你最终会得到它。 pythontutor.com 是一个很好的调试和故障排除工具。

          s = 'abcdefghijklmnopqrstuvwxyz'
          a = 0
          b = 1
          longest_word = s[0]
          word = s[0]
          for i in range(len(s)):
              a = 0
              b = 1
              if i == len(s) - 2 or b > len(s)-1:
                  i += 1
                  print('Longest substring in alphabetical order is:', longest_word)
                  break
              while (b < len(s)-i) and (s[i+a] <= s[i+b]):
                  word = s[i:i+b+1]
                  a += 1
                  b += 1
              if len(word) > len(longest_word):
                  longest_word = s[i:i+b]
              else: 
                  i += 1
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-08-05
            • 2020-09-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多