我正在尝试编写一个代码,该代码将返回字符串中最长的子字符串以及连续的字符。
这是我的代码:
s = 'abcecdefgh'
n = 1
string_l = ''
string_s = str(s[0])
for char in range(0,(len(s)-1)):
if s[n]>s[n-1] and n+1 < (len(s)):
string_s += str(s[n])
n +=1
else:
#string_s += str(s[n+1])
if len(string_s)> len(string_l):
string_l = string_s
string_s = str(s[n])
n += 1
else:
n += 1
print(string_l)
“工作”,除了除非值小于前一个字符,否则不打印最后一个字符。
在我的情况下,当s ='abcecdefgh'时,输出为“ cdefg”。 如果s ='abcecdefgh',则输出为'cdefgh'。
我不明白为什么!
答案 0 :(得分:0)
我没有检查您的代码以查看此错误的出处,因为它存在多个问题,而是创建了一个新的实现:
script.py :
#!/usr/bin/env python3
import sys
def substring_original(s):
n = 1
string_l = ''
string_s = str(s[0])
for char in range(0, (len(s) - 1)):
if s[n] > s[n - 1] and n + 1 < (len(s)):
string_s += str(s[n])
n += 1
else:
#string_s += str(s[n+1])
if len(string_s) > len(string_l):
string_l = string_s
string_s = str(s[n])
n += 1
else:
n += 1
return string_l
def substring(s):
l = len(s)
max_sub_len = 0
max_sub_idx = -1
for idx in range(l):
cur_len = 0
idx1 = idx + 1
while idx1 < l and ord(s[idx1]) - ord(s[idx1 - 1]) == 1:
idx1 += 1
cur_sub_len = idx1 - idx
if cur_sub_len > max_sub_len:
max_sub_len = cur_sub_len
max_sub_idx = idx
return s[max_sub_idx:max_sub_idx + max_sub_len]
def main():
for s in [
"abcecdefgh",
"abcecdefgg",
"abcecdxefxgh",
"ab",
"cba",
"a",
"",
]:
try:
orig_substr = substring_original(s)
except Exception as e:
orig_substr = str(e)
try:
new_substr = substring(s)
except Exception as e:
new_substr = str(e)
print(f"\nText: [{s}]\n Original substring: [{orig_substr}]\n New substring: [{new_substr}]")
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
print("\nDone.")
注释:
输出:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q057025425]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" script.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Text: [abcecdefgh]
Original substring: [cdefg]
New substring: [cdefgh]
Text: [abcecdefgg]
Original substring: [cdefg]
New substring: [cdefg]
Text: [abcecdxefxgh]
Original substring: [cdxfx]
New substring: [abc]
Text: [ab]
Original substring: [a]
New substring: [ab]
Text: [cba]
Original substring: [c]
New substring: [c]
Text: [a]
Original substring: []
New substring: [a]
Text: []
Original substring: [string index out of range]
New substring: []
Done.