A.Dave
A.Dave

Reputation: 31

How to identify ordered substrings in string using python?

I am new to python, so my question would be naive but I would appreciate your suggestion that help me get to the solution of it.

For example I have string "aeshfytifghkjgiomntrop" and I want to find ordered substrings from it. How should I approach?

Upvotes: 0

Views: 57

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

Scan the string using enumerate to issue index and value. Print string parts when chars are decreasing and start a new substring:

s = "aeshfytifghkjgiomntrop"

prev_c = None
prev_i = 0

for i,c in enumerate(s):
    if prev_c>c:
        print(s[prev_i:i])
        prev_i=i
    prev_c=c
print(s[prev_i:])

result:

aes
h
fy
t
i
fghk
j
gio
mnt
r
op

(No particular Python magic here, could be done simply even with C)

Upvotes: 1

Related Questions