简体   繁体   中英

Why does Python know the answer is alphabetically correct using the following code?

I came upon this problem at the Introduction to computer Science and Programming using Python:

Assume s is a string of lower case characters.

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl' , then your program should print: Longest substring in alphabetical order is: beggh.

In the case of ties, print the first substring. For example, if s = 'abcbcd' , then your program should print: Longest substring in alphabetical order is: abc.

I have already read a lot of answers (codes) about this problem. I can say that I understand the logic behind those answers.

However, what I can't comprehend is that "How does Python know the answer is alphabetically correct?"

Just for reference, the following is a correct code I saw online:

s = "azcbobobegghakl"  
longest = current = s[0]

for i in range (len(s) - 1):

        if s[i+1] >= s[i]:
            current += s[i+1]
            if len(current) > len(longest):
                longest = current
        else:
            current = s[i+1]

    print("Longest substring in alphabetical order is:", longest)

Again, I understand the logic behind the code. What I don't is how does Python know the answer is alphabetically correct.

I know this may be a silly question. But as I am a newbie in Programming, the answer to this question means a lot to me.

In this code, the condition

if s[i+1] >= s[i]

compares two characters. In python, when you compare two characters, you are comparing their's ascii code. As you can see here , characters are arranged alphabetically in the ascii table.

If it is arranged alphabetically, it is added to the possible solution. In other case, it just create a new possible solution.

The program keeps track of the longest alphabetical substring it has found so far (variable longest ). When it finds a new one that is longer than the one it already knows ( current ), it remembers that one instead ( longest = current ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM