H
H
Hecntv2021-06-11 11:12:17
Python
Hecntv, 2021-06-11 11:12:17

What is the problem of incorrect code execution, for some reason the character skips???

Good day, I can’t understand why, at one of the iterations in the for loop, a character is skipped and the next character is taken, although in theory it should be 'c' but in fact 'a'. The idea is to pass a string like in this case
aaaabbcaa and get a4b2c1a2 as the result.

def run_in_letter(usr, letter):
    count = 0

    for i in usr:
        if i == letter:
            count += 1
        elif i != letter:
            return count


usr = list(input())
print("данные в списке после ввода", usr)
res_row = []
print("запуск основного цикла проход по буквам")
for letter in usr:
    print("список в начале ---------", usr)
    print("буква взятая цикло при первой итерации", letter)
    res_row.append(letter)
    print("список res_row при добавлении буквы", res_row)
    count = run_in_letter(usr, letter)
    print(f"результат с выполнения функции: {count}")

    res_row.append(count)

    print("\n запуск цикла for для удаления")
    for i in range(count):
        usr.pop(0)
    print("\n окончание цикла удаления")
    print("рузультат после удаления", usr)

print(res_row)

# ввод пользователя: aaaabbcaa


Here is the output from the console:

aaaabbcaa
data in list after typing ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'a', 'a']
run main loop to spell
list at the beginning --------- ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'a', 'a']
letter taken loop on first iteration of a
list res_row on adding letter ['a']
result from function execution: 4

run for loop to delete

end of delete loop
result after delete ['b', 'b', 'c', 'a', ' a']
list at the beginning --------- ['b', 'b', 'c', 'a', 'a']
letter taken by loop at first iteration b
res_row list when adding letter ['a', 4, 'b']
result from function execution: 2

run for loop to delete

end of deletion loop
result after deletion of ['c', 'a', 'a']
list at the beginning --------- ['c', 'a', 'a']
letter taken by the loop at the first iteration a
list res_row when adding the letter ['a', 4, 'b', 2, 'a']
result from the execution of the function: 0

start the for loop to remove

end of the remove loop
result after removing ['c', 'a', ' a']
['a', 4, 'b', 2, 'a', 0]

Process finished with exit code 0

Answer the question

In order to leave comments, you need to log in

4 answer(s)
H
Hecntv, 2021-06-11
@Yelo

Thanks for the advice), after reading all the answers I did this:

def run_in_letter(usr, letter):
    count = 0

    for i in usr:
        if i == letter:
            count += 1
        elif i != letter:
            print("\n запуск цикла for для удаления")
            for i in range(count):
                usr.pop(0)
            print("\n окончание цикла удаления")

    print("-----\nresult count run run_in_letter:", count)
    print("result usr run run_in_letter:", usr,"\n-----")
    return f"{letter}{count}", usr


def run_work(usr):
    print("список полученный функцией", usr)

    return usr[0]


usr = list(input())
print("данные в списке после ввода", usr)
res_row = []

while usr:
    run_work(usr)
    res_row.append(run_in_letter(usr, run_work(usr))[0])
    print(res_row)
    print(len(usr))

but it didn’t work)), after re-reading it again, I tried to go the easier way and did this:
usr = list(input())
# usr = 'aaaabbcaa'
count = 0
res_list = []
letter = usr[0]

for i in usr:
    if i != letter:
        # print("ловушка")
        res_list.append(letter)
        # print("буква которую добавить в res_list")
        res_list.append(str(count))
        # print("count который добавить как строка в res_list")
        count = 0
        # print("присвоено count", count)

    # print("буква для i в текущей итерации:", i)
    count += 1
    # print("значение для count в текущей итерации:", count)

    # print("присваиваем букву на этой итерации переменной letter")
    letter = i
    # print("данные в res_list", res_list)

res_list.append(letter)
res_list.append(str(count))

print("".join(res_list))

it seems to be simpler)), and the program works correctly.

D
Dmitry Shitskov, 2021-06-11
@Zarom

You are iterating over the list and removing values ​​from it at the same time. This is likely to lead to unexpected results. The best solution here is to change the algorithm to one that will not modify the original list. There are too many unnecessary operations in the current implementation - nested loops, deletion. The problem can be solved by a simple traversal of the list, counting identical characters encountered in a row.

M
Mikhail Krostelev, 2021-06-11
@twistfire92

We messed up with the removal of characters and with the passage for letter in usr:
during the first pass of the loop, the variable letter is assigned the value at the zero position usr . It 's a , and everything is fine.
then you remove all the a 's and on the second pass letter is assigned the value in the first position in usr , which is b . But already the second b in this line, because the remaining string is 'b b caa'
On the third pass, the value in the second position is assigned. at this point usr = "ca a " and the third character is a
That's actually the problem with your code.
To better understand this situation, enter the string 'aaabccca', and you will see that b will not be there

R
Ramis, 2021-06-11
@ramzis

Do you like crutches?, then hold)

def krik_dovakina(usr):
    result = ''
    count = 1
    for i in usr:
        try:
            if usr[1] == i:
                count+=1
            else:
                result += f'{i}{count}'
                count = 1
            usr = usr[1:]
        except IndexError:
            result += f'{i}{count}'
    return f'Сжатый  крик драконорожденного {result}'
print(krik_dovakina('aaaabbcaayyyyyz'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question