check if letters of a string are in sequential order in another string

  • A+
Category:Languages

If it were just checking whether letters in a test_string are also in a control_string,

I would not have had this problem.

I will simply use the code below.

if set(test_string.lower()) <= set(control_string.lower()):     return True 

But I also face a rather convoluted task of discerning whether the overlapping letters in the

control_string are in the same sequential order as those in test_string.

For example,

test_string = 'Dih' control_string = 'Danish' True  test_string = 'Tbl' control_string = 'Bottle' False 

I thought of using the for iterator to compare the indices of the alphabets, but it is quite hard to think of the appropriate algorithm.

for i in test_string.lower():     for j in control_string.lower():         if i==j:             index_factor = control_string.index(j) 

My plan is to compare the primary index factor to the next factor, and if primary index factor turns out to be larger than the other, the function returns False.

I am stuck on how to compare those index_factors in a for loop.

How should I approach this problem?

 


You can use find(letter, last_index) to find occurence of desired letter after processed letters.

def same_order_in(test, control):     index = 0     control = control.lower()     for i in test.lower():         index = control.find(i, index)         if index == -1:             return False         # index += 1 # uncomment to check multiple occurrences of same letter in test string       return True 

If test string have duplicate letters like:

test_string = 'Diih' control_string = 'Danish' 

With commented line same_order_in(test_string, control_string) == True

and with uncommented line same_order_in(test_string, control_string) == False

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: