2017-06-03 136 views
-8

我有一个代码分配,但我无法找到答案,所以我在网上检查。代码是用python编写的。代码是绝对正确的,但我无法理解它。我对python非常陌生,所以plz帮助我。我不能理解Python中的这段代码,你能帮助我吗?

这里是问题

假设s是一个小写字母的字符串。

编写一个程序,打印s中按字母顺序排列的最长字符串。例如,如果s ='azcbobobegghakl',那么你的程序应该打印

按照字母顺序排列的最长的子字符串是:beggh 在关系的情况下,打印第一个子字符串。例如,如果s = 'abcbcd',那么你的程序应该打印

按字母顺序排列

最长的串是:ABC

的代码是:

# initialise tracker variables 
    maxLen=0 
    current=s[0] 
    longest=s[0] 

    # step through s indices 
    for i in range(len(s) - 1): 
    if s[i + 1] >= s[i]: 
     current += s[i + 1] 
     # if current length is bigger update 
     if len(current) > maxLen: 
      maxLen = len(current) 
      longest = current 
    else: 
     current=s[i + 1] 

    i += 1 

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

采取一个语句的时间和读出的文件。你有什么问题?顺便说一下,你的缩进对于'for'循环是不正确的 - 这在python中是非常重要的。 – cdarke

+0

另请参阅https://stackoverflow.com/questions/27937076/python-word-counter –

+0

我可以逐行解决这个问题,但是最好打开IDLE,在这些行中输入一个通过一个,并检查变量,让你可以看到它在做什么。 或者你可以用打印语句胡椒粉的东西,所以你可以看到它是这样做... –

回答

2
s="abdhbdwba" 

maxLen=0  # sets the current highest length to 0 
current=s[0] # sets the current letter to the first letter (this is the output string) 
longest=s[0] # sets the longest letter to the first letter(just for programming sake) 

# step through s indices 
for i in range(len(s) - 1): # goes over every letter in the string s except the last letter 
    if s[i + 1] >= s[i]: # checks if the next letter in the string is greater than (in ascii code) the current letter 
     current += s[i + 1] # if it is, adds the next letter to the current value 
     if len(current) > maxLen: # if we've got to a sequence that is larger, just set the max length to the length of the sequance 
      maxLen = len(current) # just lets the max length to the current length 
      longest = current  # just sets the longest to the current value 
    else: 
     current=s[i + 1] # just sets the current as is 

i += 1 # not sure why this is here? 

print ('Longest substring in alphabetical order is: ' + longest) # just prints it out 

就让我们去了一些基础知识:

for i in range(x): 
    print(i) 

将打印I,I + 1,I + 2 ... I +(X - 1)

x = y[i + 1] 

X现在将等于第(i + 1)个索引数组中

len(x) 

将输出该字符串是在X多久