2013-10-26 105 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) 
相關問題