0

if i input A3B4 program its run but i input A10B13 so program will error index out of range, so how to fix the code without library and use based the code.

Char = input ("Input Char : ")
Total = len(Char)
Decompress =""

for i in range (0, Total,2):
    Loop = int(Char[i+1])
    for j in range (0, Loop):
        Decompress = Decompress + Char [i]
        
print("Output : ",Decompress)
Petup
  • 11

1 Answers1

1
Char = input("Input Char : ")
Total = len(Char)
Decompress = ""

for i in range(0, Total, 2):
    print('i', i)
    print('Char[i + 1]', Char[i + 1])
    Loop = int(Char[i + 1])
    for j in range(0, Loop):
        Decompress = Decompress + Char[i]

print("Output : ", Decompress)

You are doing the conversion of 'B' to int. The symbol cannot be converted to a number. I made a printout of this particular line. Run the code and see. Also, when you have a string with an even number, there is no way out of the array. But, if, for example, enter 7 characters, then there will be an exit outside the array.

Indexing of arrays starts from 0. That is, the seventh element will have an index of six. Added a line where indexes are printed print('i', i).And the string asks for +1(Char[i + 1]). That is, 1 more. Having an array of 7 elements in size, we request a non-existent 8.

Char = input("Input Char : ")
Total = len(Char)
Decompress = ""

for i in range(0, Total, 2):
    print('i', i)
    print('Char[i + 1]', Char[i + 1])
    Loop = str(Char[i + 1])
    for j in range(0, len(Loop)):
        Decompress = Decompress + Char[i]

print("Output : ", Decompress)
inquirer
  • 4,286
  • 2
  • 9
  • 16