【问题标题】:I cant understand this code in Python, can you help me? [closed]我无法理解 Python 中的这段代码,你能帮帮我吗? [关闭]
【发布时间】:2017-06-03 13:00:49
【问题描述】:

我有一个代码分配,但我找不到答案,所以我在网上查了一下。代码是用python编写的。代码绝对正确,但我无法理解。我对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)

【问题讨论】:

  • 一次做一份声明并阅读文档。你哪部分有问题?顺便说一句,for 循环的缩进不正确 - 这在 python 中很关键。
  • 我可以为你逐行分解,但你最好打开IDLE,一一输入这些行,并检查沿途的变量,这样你就可以看看它在做什么。或者你可以用 print 语句来点缀这个东西,这样你就可以看到它是怎么做的......

标签: python iteration


【解决方案1】:
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中的长度

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    相关资源
    最近更新 更多