2013-10-26 104 views
7

我在另一个主题上找到了这段代码,但它按照连续字符排序子字符串,而不是按字母顺序排序。我如何纠正它按字母顺序?它打印出lk,我想打印ccl。由于按字母顺序查找最长的子字符串

PS:我是在Python初学者

s = 'cyqfjhcclkbxpbojgkar' 
from itertools import count 

def long_alphabet(input_string): 
    maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str) 
    for start in range(len(input_string)): # O(n) 
     for end in count(start + len(maxsubstr) + 1): # O(m) 
      substr = input_string[start:end] # O(m) 
      if len(set(substr)) != (end - start): # found duplicates or EOS 
       break 
      if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr): 
       maxsubstr = substr 
    return maxsubstr 

bla = (long_alphabet(s)) 
print "Longest substring in alphabetical order is: %s" %bla 
+0

什么是 “最长的按字母顺序” 是什么意思?你打印的一个值如何以任何顺序? –

+0

嘿,欢迎来到StackOverflow!如果你自己解决问题并[描述你所尝试的](http://whathaveyoutried.com),我们更有可能帮助你。检查堆栈溢出[问题清单](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist)以获取有关询问正确问题的更多信息。祝你好运,快乐的编码! –

+0

你好,谢谢你的回答:例如,如果s ='tjkocgygiwc'字母顺序中最长的子字符串是'jko',我现在不会怎么做才能找到'jko',程序找到jk。 'wvcdcgykkaypy'发现'wv'而不是'cgy' – spacegame

回答

4

尝试改变这一点:

 if len(set(substr)) != (end - start): # found duplicates or EOS 
      break 
     if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr): 

这样:

​​

将显示ccl您输入例串。该代码是简单,因为你试图解决一个简单的问题:-)

+0

感谢您的帮助,您拯救了我的生命。 – spacegame

+0

aha ...这是如何timsort发现运行,对不对? –

12
s = 'cyqfjhcclkbxpbojgkar' 
r = '' 
c = '' 
for char in s: 
    if (c == ''): 
     c = char 
    elif (c[-1] <= char): 
     c += char 
    elif (c[-1] > char): 
     if (len(r) < len(c)): 
      r = c 
      c = char 
     else: 
      c = char 
if (len(c) > len(r)): 
    r = c 
print(r) 
+3

一些注释来解释它或有意义的变量名称将有助于提高可读性 – sniels

1

您可以通过注意该字符串可以分成最大长度的有序子的运行提高你的算法。任何命令字符串必须包含在这些运行

这可以让你只通过串o重复一次(N)

def longest_substring(string): 
    curr, subs = '', '' 
    for char in string: 
     if not curr or char >= curr[-1]: 
      curr += char 
     else: 
      curr, subs = '', max(curr, subs, key=len) 
    return max(curr, subs, key=len) 
1

在Python中字符比较的一个简单的比较,Java脚本,其中的ASCII值必须进行比较。据蟒蛇

A> B给出了一个布尔值false和b> a给出一个true

使用此按字母顺序排列的最长的子字符串可以通过下面的算法中找到:

def comp(a,b): 
    if a<=b: 
     return True 
    else: 
     return False 
s = raw_input("Enter the required sting: ") 
final = [] 
nIndex = 0 
temp = [] 
for i in range(nIndex, len(s)-1): 
    res = comp(s[i], s[i+1]) 
    if res == True:  
      if temp == []: 
      #print i 
       temp.append(s[i]) 
       temp.append(s[i+1]) 
      else: 
       temp.append(s[i+1]) 
     final.append(temp) 
     else: 
     if temp == []: 
     #print i 
     temp.append(s[i]) 
     final.append(temp) 
     temp = [] 
lengths = [] 
for el in final: 
    lengths.append(len(el)) 
print lengths 
print final 
lngStr = ''.join(final[lengths.index(max(lengths))]) 
print "Longest substring in alphabetical order is: " + lngStr 
+0

看起来像一个'C'代码。有没有最佳的方法? – AAI

0

稍有不同的实施,建立按字母顺序排列的所有子列表,并返回最长的一个:

def longest_substring(s): 
    in_orders = ['' for i in range(len(s))] 
    index = 0 
    for i in range(len(s)): 
     if (i == len(s) - 1 and s[i] >= s[i - 1]) or s[i] <= s[i + 1]: 
      in_orders[index] += s[i] 
     else: 
      in_orders[index] += s[i] 
      index += 1 
    return max(in_orders, key=len) 
+0

请给出一些意见或解释如何条件如何工作 – AAI

1

在递归的方式,你可以我从itertools

M端口计数或者定义同样的方法:

def loops(I=0, S=1): 
    n = I 
    while True: 
     yield n 
     n += S 

使用这种方法,你可以得到一个端点的值,当你创建你的anallitic过程中的任何字符串。

现在看起来anallize方法(基于spacegame问题和先生Tim Petters建议)

def anallize(inStr): 
    # empty slice (maxStr) to implement 
    # str native methods 
    # in the anallize search execution 
    maxStr = inStr[0:0] 
    # loop to read the input string (inStr) 
    for i in range(len(inStr)): 
     # loop to sort and compare each new substring 
     # the loop uses the loops method of past 
     # I = sum of: 
     #  (i) current read index 
     #  (len(maxStr)) current answer length 
     #  and 1 
     for o in loops(i + len(maxStr) + 1): 
      # create a new substring (newStr) 
      # the substring is taked: 
      # from: index of read loop (i) 
      # to: index of sort and compare loop (o) 
      newStr = inStr[i:o] 

      if len(newStr) != (o - i):# detect and found duplicates 
       break 
      if sorted(newStr) == list(newStr):# compares if sorted string is equal to listed string 
       # if success, the substring of sort and compare is assigned as answer 
       maxStr = newStr 
    # return the string recovered as longest substring 
    return maxStr 

最后,测试或执行pourposes:

# for execution pourposes of the exercise: 
s = "azcbobobegghakl" 
print "Longest substring in alphabetical order is: " + anallize(s) 

的很大一块这项工作发起人:spacegame和出席了先生。Tim Petters,是在使用本地str方法和代码的可重用性。

答案是:

按字母顺序最长子是:CCL

-1

另一种方式:

s = input("Please enter a sentence: ") 
count = 0 
maxcount = 0 
result = 0 
for char in range(len(s)-1): 
    if(s[char]<=s[char+1]): 
     count += 1   
    if(count > maxcount): 
      maxcount = count 
      result = char + 1 

    else: 

     count = 0 
startposition = result - maxcount 
print("Longest substring in alphabetical order is: ", s[startposition:result+1]) 
+0

试过这个。请输入一句话:sentententensebenz 按字母顺序排列的最长子字符串是:ent,这是错误的。这里最长的substrong是“benz”! – AAI

0
s = "azcbobobegghakl" 
ls = "" 
for i in range(0, len(s)-1): 
    b = "" 
    ss = "" 
    j = 2 
    while j < len(s): 
     ss = s[i:i+j] 
     b = sorted(ss) 
     str1 = ''.join(b) 
     j += 1 
     if str1 == ss: 
      ks = ss 
     else: 
      break 
    if len(ks) > len(ls): 
     ls = ks 
print("The Longest substring in alphabetical order is "+ls) 
+0

最好是增加一些注释来解释答案或使用有意义的变量名来使代码可读。 –

1

使用列表和最大功能,大大减少了代码。

actual_string = 'azcbobobegghakl' 
strlist = [] 
i = 0 
while i < len(actual_string)-1: 
    substr = '' 
    while actial_string[i + 1] > actual_string[i] : 
     substr += actual_string[i] 
     i += 1 
     if i > len(actual_string)-2: 
      break 
    substr += actual-string[i] 
    i += 1 
    strlist.append(subst) 
print(max(strlist, key=len)) 
+1

算法效果很好。只有注释是你想找到匹配,其中“a”跟在“a”之后,等等。因此,你想要 而actual_string [i + 1]> = actual_string [i] 大于或等于先前信 –

0
s = 'cyqfjhcclkbxpbojgkar' 
longest = "" 
max ="" 

for i in range(len(s) -1): 
    if(s[i] <= s[i+1]): 
     longest = longest + s[i] 
     if(i==len(s) -2): 
      longest = longest + s[i+1] 
    else: 
     longest = longest + s[i]   
     if(len(longest) > len(max)): 
      max = longest 
     longest = ""   

if(len(s) == 1): 
    longest = s 


if(len(longest) > len(max)): 
    print("Longest substring in alphabetical order is: " + longest) 
else: 
    print("Longest substring in alphabetical order is: " + max) 
相关问题