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 :
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)