Python String Compression Problem Questions

Asked 2 weeks ago, Updated 2 weeks ago, 3 views

Jump to Python Chapter 8, Comprehensive Question No. 13, and when I solved it like this, the result came out as "a1b1c1a1". I don't know why all the CNTs come out as 1.

ui="aaabbcccccca"
uilist=list(ui)
cnt=0
result=[]

for i,abc in enumerate(uilist):

    if cnt>0:
        if abc==uilist[i-1]: #When the same character is contiguous
            cnt=+1
        elif abc!=uilist[i-1]: #When the same character is not contiguous
            result.append(str(cnt))
            result.append(abc)
            cnt=1
    else:
        cnt+=1
        result.append(abc)

result.append(str(cnt))
result="".join(result)
print(result)

python

2022-09-20 11:00

1 Answers

There seems to be a mistake in the cnt increase or decrease expression when the same character is continuous.

# ...
if abc == uilist[i-1]:
    cnt += 1 # '=+' ==> '+='
# ...

I keep saving 1 whenever the characters are continuous, so I think the final value is also 1.

And it's not mandatory, but it's easier for us to do it ourselves if you write the code yourself rather than capture it! Enjoy coding :)


2022-09-20 11:00

If you have any answers or tips


© 2022 pinfo. All rights reserved.