2

Here is my code to solve a problem of finding the largest sequence of the same letters in two strings in the same order. My approach is basically to see if the letter is in both strings, then on that letter, the comparison string is sliced to avoid counting anything in the wrong order (EXAMPLE, SHA and HAP, have HA common, but SAH and HAP only have A or H in common.)

def commonChild(s1, s2):
stringA = []
a = s1
stringB = []
b = s2
y = 0
x = 0

for num in s1:
    if num in b[y:]:
        
        stringA.append(num)
        y = b.index(num) + 1
      
    else:
        pass

for num in s2:
    if num in a[x:]:
        
        stringB.append(num)
        x = a.index(num) + 1

    else:
        pass

theone = max(len(stringA),len(stringB))
return theone

It works with small tests (s1 = SALLY, s2= HARRY), but with large tests, I find that my slicing is not preforming correctly (slices occur at wrong index). Any suggestions on how to better my slicing.

Melin
  • 29
  • 2
  • I don't fully understand how it should work , for e.g. 'HHAAT' and 'CATR' what do you want to have ? index in first string ,here 3? – alekq Aug 19 '20 at 23:08
  • s1 = HHAAT. The first for loop will compare each common character (num) in s1 to CATR, CATR then sliced. [num= H, pass; H, pass; A, num appended to empty list, CATR sliced to TR; A, pass; T, num appended to list, TR sliced to R. emptylist = [A,T] ] In the second for loop, the same is done to compare s2 to HHAATT C,pass; A, appended,HHAATT now AATT; T, appended, AATT now T; R, pass emptylist2 = [A,T] Both empty lists are the same size, so either length is the max, and 2 is returned. slicing is implemented to avoid miss counting, e.g code says there are 2 As in common because hhAAt. – Melin Aug 20 '20 at 07:43

0 Answers0