Home > Software engineering >  How can I match element by element of list?
How can I match element by element of list?

Time:01-04

i'm trying to solve the problem of checking the distance between letters by looking at the alphabet. I described it in a dictionary. I gave "l = 10000" so that later I could easily distinguish the correct numerator. I think the idea itself is good, but it gives me the error "if abs (words [text [i] [j]] - words [text [i] [j 1]] <10): IndexError: string index out of range "

I will be grateful for every tip.

Code:

    words={'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25,}
    text = ['XXUXXTYVXWA', 'YTWYVWUTYA', 'PUOMQVMRNOSNVONOQOQMPPMRTVRSVRUNMOUSVUOTTMNRVQX']
    l = 0
    t = []
    for i in range(0,len(text)):
        for j in range(0,len(text[i])):
            if abs(words[text[i][j]] - words[text[i][j 1]] < 10):
                l = l 1
            else:
                l = 10000
        t.append(l)
        l = 0
    print(t)

CodePudding user response:

The error is raised with the last iteration, when you want to compare the last letter with the letter after the last letter, which doesn't exist. Perhaps start at 1 and compare the current letter with the previous letter like this:

words={'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25,}
    text = ['XXUXXTYVXWA', 'YTWYVWUTYA', 'PUOMQVMRNOSNVONOQOQMPPMRTVRSVRUNMOUSVUOTTMNRVQX']
    l = 0
    t = []
    for i in range(0,len(text)):
        for j in range(1,len(text[i])):
            if abs(words[text[i][j-1]] - words[text[i][j]] < 10):
                l = l 1
            else:
                l = 10000
        t.append(l)
        l = 0
    print(t)

CodePudding user response:

I would recommend using the ord built-in to check distance between letters.

In [1]: ord("i") - ord("g")
Out[1]: 2
  • Related