对于循环变量不等于我的想法吗?

时间:2018-06-10 23:21:44

标签: python loops

因此我被分配了一个计算字符串中最长子串的任务,其中字母按字母顺序出现。我想出了一个有效且正确的答案,但坦率地说,我无法理解自己的代码......请耐心等待。我解决了我的误解,产生了工作代码。在这个例子中,为什么变量longest == 4而不是5?

s = 'azcbobobegghakl'

count = 0
longest = 0
end = 0

for a in range(len(s) - 1):
    if s[a] <= s[a + 1]:      # is s[a] greater than or = to the next char in string?
        count += 1            # if it is, +1 to count
        if count > longest:   # if count is greater than longest (longest is current longest - 1), continue, otherwise keep counting
            longest = count   # new longest is the current count because it is longest
            end = a + 1       # since end is in this if block, it counts the iteration where count was last greater than the longest
    else:                     # when count is never greater than longest again the longest will be the length of the longest string
        count = 0

start = end - longest

"""
end is the last position in the longest string (here it is 11 or h) 
longest is length of the string (here it is 4)
so the end - longest characters = the start of string which is 7 or b
"""

print('Longest substring in alphabetical order is: ' + s[start:end + 1])
#prints the letters in s from position 7 to 11 + 1 (+1 because end = index 11 but it goes up to and not including 11)

3 个答案:

答案 0 :(得分:3)

当以下条件为真时,这意味着您至少有一个长度为2的子字符串,但由于您从0开始count,因此您的longest比您少{1}}期望。

s[a] <= s[a + 1]

所以解决方法是将count初始化为1,这是有道理的,因为在初始情况下单个字母始终是最长的子字符串(除非你有一个空字符串,你应该处理它)。

答案 1 :(得分:0)

此代码计算间隙。也就是说,当两个字母之间的差异符合标准时,您正在寻找。这是一个差异,你正在计算成功的差异,这比获得这个差异所需的长度少一个。

您可能需要:

start = end - longest - 1

或者调整countend

答案 2 :(得分:0)

我想通了,我想它运行第11次迭代(h&lt; a)它意识到h不小于a,所以它将计数设置回0而不是将h计为第5个字母。由于最长子字符串中的最终评估等于false,因此longest = longest = longest = int RNG(int n) { int range = RAND_MAX - (RAND_MAX % n); srand(time(NULL)); int x = rand(); while (x > range) { x = rand(); } return x % n; } = {> 1}}总是短于最长字母子字符串的实际长度= 4即import requests import os.path #declares any necessary variables #file1, file2 to check if login is successful save_path = '/Users/myName/Documents/Webscraping Project/' login_url = 'https://www.consumerreports.org/cro/index.htm' my_url = 'https://www.consumerreports.org/cro/index.htm' pName = os.path.join(save_path, 'post text file'+".txt") rName = os.path.join(save_path, 'response text file'+".txt") post_file = open(pName, "w") response_file = open(rName, "w") #login using Session class from Requests package with requests.Session() as s: payload = {"userName":"myName@university.edu","password":"my_password"} p = s.post(login_url, data=payload) print(p.text) r = s.get(my_url) #saves files to see if login was successful post_file.write(str(p.text.encode('utf-8'))) response_file.write(str(r.text.encode('utf-8'))) post_file.close() response_file.close() print('Files created.') 实际上可以定义为一行中真实评估的数量。

所以我应该将变量重命名为最长,因为它在这里有点误导,因为它实际上并不是最长的,而是在最长子串中最后一个字符之前的多少个字符。