1

the only catch is that is has to be in alphabetical order: Where the unicode value is bigger than the previous character. If i have a string with the letters "owdnloquxat" then it would only print "loqux" since this is the longest substring in alphabetical order.

I've tried this code. However, in this instance it only prints "az", but it should print "beggh"

s = 'azcbobobegghakl'
sList = list(s)

sub = s[0]

long, lenght = sub, 1

for i in s[1:]:
    if ord(sub[-1]) <= ord(i):
        sub += i
    print(sub)

I am quite new to python, but need to complete this for a course. If you want to give answers, that's fine. Hints would be fine as well since i want to learn.

Loudee
  • 11
  • 1
  • You should give a better title to your question like: "find longest substring in alphabetical order". Similar question is answered here: https://stackoverflow.com/questions/19618533/finding-longest-substring-in-alphabetical-order/39658014#39658014 – m.rp Jun 18 '19 at 07:40
  • You are only checking the substring that starts with the first letter, that's why you can only find az. You should wrap your code inside another for loop that will change the starting letter. – Selcuk Jun 18 '19 at 07:44

1 Answers1

0

Here is one.

s = 'azcbobobegghakl'

c = s[0]
best = ""
for i in s[1:]:
    if i >= c[-1]:
        c += i
    else:
        if len(c) > len(best):
            best = c
        c = i

if len(c) > len(best):
    best = c


print(best)
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
  • I feel that your approach should be right. But there is no need to build string `c` explicitly (making algo quadratic) - just remember starting index and compare every char with previous one. – MBo Jun 18 '19 at 08:28
  • you are right, keep forgetting strings are immutable :-) – Christian Sloper Jun 18 '19 at 08:31