简体   繁体   中英

Python exercise about finding indices of X in the list

def leesFormulier(l1):
    index = 0
    lres = []
    for j in range(len(l1)):
        for k in range(0,9,2):
            if l1[j][k] == 'X':
                lres.append(index+1)
                index += 1
            else:
                index += 1
    return lres
print(leesFormulier(l1 = ['1 X 3 4 X', 'X 7 X X 10', '11 12 13 14 15', '16 17 18 19 20', '21 22 23 24 25', '26 27 28 29 30', '31 32 33 34 35', '36 37 38 39 40', '41 42 43 44 X']))

result : [2, 5, 6, 8, 9]

Hello everybody,

I'm making an exercise on Python and I have to find the indices of where you can find the 'X'. And I solved it for the most part but the only problem I'm having is the last 'X' that won't be recognized. I put it in Pythontutor and there I could see that on the last time going through the for loops that it goes to the last k for loop but it doesn't check it but instead goes immediately to the j for lus and then ends the iteration and goes to the return part. I don't know what I'm doing wrong, would appreciate it if somebody could help me out.

Thanks in advance!

Don't need all those indexes or nested loops for this problem and you can simplify it a lot

def lessFromulier(l1):
    lres = []
    new_string = " ".join(l1).split(" ")
    for i, letter in enumerate(new_string):
        if letter == "X":
            lres.append(i+1)
    return lres


test = [
    "1 X 3 4 X",
    "X 7 X X 10",
    "11 12 13 14 15",
    "16 17 18 19 20",
    "21 22 23 24 25",
    "26 27 28 29 30",
    "31 32 33 34 35",
    "36 37 38 39 40",
    "41 42 43 44 X",
]
print(lessFromulier(test))

which gives this output

[2, 5, 6, 8, 9, 45]

Your input is really weird to me, but here is a solution to your question

def leesFormulier(l1):
    index = 0
    lres = []
    for i in range(len(l1)):
        for j in range(len(l1[i])):
            c = l1[i][j]
            if c == ' ':
                continue
            if c == 'X':
                index += 1
                lres.append(index)
            else:
                index += 1
    return lres

print(leesFormulier(l1 = ['1 X 3 4 X', 'X 7 X X 10', '11 12 13 14 15', '16 17 18 19 20', '21 22 23 24 25', '26 27 28 29 30', '31 32 33 34 35', '36 37 38 39 40', '41 42 43 44 X']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM