Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are the first set of characters only replaced?

From my last post, I’ve made some changes to my code so that it functions more smoothly; however, it won’t print what I expect. I’ve found out how to count the individual characters in the input, but when changing the consecutive characters to letters, it only prints the first set of consecutive characters. For example, 1 consecutive character = A, 2 = B, 3 = C… When I input *^^**&&&, the output is A and not ABBC. How could I fix this; there’s probably a simple fix again sorry.

encrypted=input("Enter an encrypted message: ")
count=1
length=""

if len(encrypted)>1:
    for i in range(1,len(encrypted)):
       if encrypted[i-1]==encrypted[i]:
          count+=1
       else :
           length += encrypted[i-1] + str(count)
           count=1
           
    length += encrypted[i] + str(count)
    
else:
    i=0
    length += encrypted[i] + str(count)

print(chr(count+64))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This does what you describe:

encrypted = input("Enter an encrypted message: ")

count = 0
result = ''
for i, ch in enumerate(encrypted):
    if i == 0 or ch == encrypted[i-1]:
        count += 1
    else:
        result += chr(count + 64)
        count = 1
if count > 0:
    result += chr(count + 64)

print(result)

Result:

Enter an encrypted message: @##$$%%%
ABBC

It doesn’t build up a record of what was found, adding that back in if you need it:

encrypted = input("Enter an encrypted message: ")

ch = ''
count = 0
result = ''
counts = []
for i, ch in enumerate(encrypted):
    if i == 0 or ch == encrypted[i-1]:
        count += 1
    else:
        result += chr(count + 64)
        counts.append((ch, count))
        count = 1
if count > 0:
    result += chr(count + 64)
    counts.append((ch, count))

print(result, counts)

But if you need it anyway, you may as well:

encrypted = input("Enter an encrypted message: ")

ch = ''
count = 0
counts = []
for i, ch in enumerate(encrypted):
    if i == 0 or ch == encrypted[i-1]:
        count += 1
    else:
        counts.append((ch, count))
        count = 1
if count > 0:
    counts.append((ch, count))

print([chr(count+64) for _, count in counts], counts)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading