【问题标题】:I want to create a program that finds the longest substring in alphabetical order using python using basics我想创建一个程序,使用 python 使用基础知识按字母顺序查找最长的子字符串
【发布时间】:2018-09-12 13:03:33
【问题描述】:

我的使用python按字母顺序查找最长子字符串的代码

我所说的按字母顺序排列的最长子串是什么意思? 如果输入是“asdefvbrrfqrstuvwxffvd”,则输出将是“qrstuvwx”

#we well use the strings as arrays so don't be confused
s='abcbcd'
#give spaces which will be our deadlines
h=s+'    (many spaces)                                                                      '
#creat outputs
g=''
g2=''
#list of alphapets
abc='abcdefghijklmnopqrstuvwxyz'

#create the location of x"the character the we examine"  and its limit 
limit=len(s)
#start from 1 becouse we substract one in the rest of the code
x=1
while (x<limit):
    #y is the curser that we will move the abc array on it
    y=0
    #putting our break condition first
    if ((h[x]==' ') or (h[x-1]==' ')):
        break
    for y in range(0,26):
        #for the second character x=1
        if ((h[x]==abc[y]) and (h[x-1]==abc[y-1]) and (x==1)):
            g=g+abc[y-1]+abc[y]

            x+=1
        #for the third to the last character x>1
        if ((h[x]==abc[y]) and (h[x-1]==abc[y-1]) and (x!=1)):
            g=g+abc[y]
            x+=1
        if (h[x]==' '):
            break
print ("Longest substring in alphabetical order is:" +g )

它没有结束,好像它处于无限循环中 我该怎么办? 我是初学者,所以我想要一些 for 循环而不是库中的函数 提前致谢

【问题讨论】:

  • @natn2323 不,线路是h=s+' (many spaces) '
  • @Jonas 对于这样的行,我发现最好按照以下方式做一些事情:A_SPACE = ' ',然后是h = s + A_SPACE*74(或者你有多少空格)。编辑 - 抱歉刚刚意识到你不是提问者
  • 是否有使用h的要求,还是您想做的事情?
  • @natn2323 不,我只是用它来有一个可以称之为“结束”的地方我仍然是初学者,但我发现使用空格比数字更容易打破它,因为 s 可能会有所不同作为输入。

标签: python python-3.x edx


【解决方案1】:

为避免无限循环,请在 while 循环的最后添加 x += 1。因此,您的代码可以正常工作,但在一般情况下会出错。

它工作错误的原因是你只使用了一个变量g 来存储结果。使用至少两个变量来比较先前找到的子字符串和新找到的子字符串或使用列表记住所有子字符串,然后选择最长的一个。

【讨论】:

    【解决方案2】:
    s = 'abcbcdiawuhdawpdijsamksndaadhlmwmdnaowdihasoooandalw'
    longest = ''
    current = ''
    for idx, item in enumerate(s):
        if idx == 0 or item > s[idx-1]:
            current = current + item
        if idx > 0 and item <= s[idx-1]:
            current = ''
        if len(current)>len(longest):
            longest = current
    print(longest)
    

    输出:

    dhlmw
    

    为了您的理解,'b'&gt;'a'True'a'&gt;'b'False 等等

    编辑:

    对于最长的连续子串:

    s = 'asdefvbrrfqrstuvwxffvd'
    abc = 'abcdefghijklmnopqrstuvwxyz'
    longest = ''
    current = ''
    for idx, item in enumerate(s):
        if idx == 0 or abc.index(item) - abc.index(s[idx-1]) == 1:
            current = current + item
        else:
            current = item
        if len(current)>len(longest):
            longest = current
    print(longest)
    

    输出:

    qrstuvwx
    

    【讨论】:

    • @natn2323 没有?在我的世界里是 -> abcdefghijklmnopqrstuvwxyz
    • @jonas 但这并不是真正的字母顺序,因为字母不是相邻的
    • @kuro-san 那么在这种情况下,你想要的是最长的、连续的字母子串。你应该在你的帖子中提到这一点。另外,这就是为什么最好有一个示例输出。
    • @kuro-san 答案应该是qrstuvwx 而不是rstuvwx
    • @Jonas 这不会产生预期的结果。编辑它
    【解决方案3】:
    def sub_strings(string):
        substring = ''
        string +='\n'
        i = 0
        string_dict ={}
        while i < len(string)-1:
            substring += string[i]
            if ord(substring[-1])+1 != ord(string[i+1]):
                string_dict[substring] = len(substring)
                substring = ''
            i+=1
        return string_dict   
    
     s='abcbcd'
    
     sub_strings(s)
      {'abc': 3, 'bcd': 3} 
    

    要找到最长的你可以做max(sub_strings(s))

    那么这里你希望哪一个被认为是最长的??现在这是您需要解决的问题

    【讨论】:

      【解决方案4】:

      您可以遍历字符串并继续与最后一个字符进行比较,如果当前字符比最后一个字符大一个序数,则附加到可能最长的字符串:

      def longest_substring(s):
          last = None
          current = longest = ''
          for c in s:
              if not last or ord(c) - ord(last) == 1:
                  current += c
              else:
                  if len(current) > len(longest):
                      longest = current
                  current = c
              last = c
          if len(current) > len(longest):
              longest = current
          return longest
      

      这样:

      print(longest_substring('asdefvbrrfqrstuvwxffvd'))
      

      会输出:

      qrstuvwx
      

      【讨论】:

      • 将主字符串命名为s 和当前字符c 是很常见的,所以我没有给这两个变量起更长的名字。
      • 我的意思是你半小时后发布了和我一样的答案,甚至称这两个字符串是当前和最长的:D
      • 嗯?我什至没有看别人的答案。 currentlongest 在这个问题的上下文中是非常常见的变量名。我们的逻辑实际上大相径庭,那么是什么让您认为这是“相同的答案”?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多