Python Forum

Full Version: Loop do not start for letter matching algoritm
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I make a simple algoritm to compare two strings, but the loop do not continue to the end. This end is the minimum string lenght from these two data entry.

Here's my code :

j1 = "BB"
j2 = "AABBCCDDEEFFGGHHIIJJKKLLMMBBDCCDEEFFGGHHIIJJKKLLMM"

t = 0
tab = []

if len(j1) < len(j2):
    n = len(j1)
else:
    n = len(j2)

for i in range(n):

    while j1[i] == j2[i]:
        t += 1
        tab.append(t)

print(tab)
print(t)
I have this :

[]
0
I must have this type of result:

[1, 2]
2
For AA in the first string = AA to the second string and the loop stop.

Thanks for any help. Big Grin
This happens because you took the shorter string.

import itertools

new_list = []
for a, b in itertools.zip_longest(j1, j2):
    if a == b:
        new_list.append(a)
This must result in an empty list.
Describe what you want to do.
Finaly I solved my problem by doing this :

t = 0
tab = [0] * 26

if len(j1) < len(j2):
    n = len(j1)
else:
    n = len(j2)

for i in range(n):

    if j1[i] == j2[i]:
        t += 1
        tab[i] = t
        
    if tab[i] == 0:
            break
Because in my programm I need to stop the loop on minimum lenght.

Thank you.
This code here is simple but not easy to read
if len(j1) < len(j2):
    n = len(j1)
else:
    n = len(j2)
This code here does the same, is more simple and easy to read
n = min(len(j1), len(j2))