Home > Blockchain >  Exponential-Golomb Decoder in Python (Codewars)
Exponential-Golomb Decoder in Python (Codewars)

Time:01-06

I am trying to pass one of the Codewars challenge ,,Exponential-Golomb Decoder" here: https://www.codewars.com/kata/5e4d8a53b499e20016b018a0/swift

The idea is to take input in binary format:"001000000101111001010001101" -> 00100 000010111 1 00101 0001101

and return list of decoded numbers:[3, 22, 0, 4, 12]

If You give the Sentence of for example 00100 00101, let's see that You start with 2 leading zeros, then hit 1, and so the first resulted number is number of zeros 1 number of zeros (00 1 00), let's say the Length of this number is 5, so I wanted to make new sentence like sentence = [length:] and iterate through it, but it is not going to iterate through new sentence, but the old one

Any Ideas? Big thanks

def reccurent():
    sentence = input("Enter the number:")
    nums = []
    number = ""

    for i in sentence:
        i = int(i)

        if i == 0:
            number  = str(0)

        else:
            number  = str(1)

            if len(number) == 1:
                nums.append(number)
                number = ""
                sentence = sentence[i:]

            else:
                length = len(number)   len(number) - 1
                word = str(sentence[:length])
                nums.append(word)
                number = ""
                sentence = sentence[length:]
    print(nums)

reccurent()

Result Enter the number:0011000100

['00110', '1', '0100']

Process finished with exit code 0

Should be ['00110','00100']

Thanks

CodePudding user response:

The following is a modification based on the provided code.

def reccurent():
    sentence = input("Enter the number:")
    nums = []
    number = ""
    
    # Define parameters to save the cursor offset position
    offset = 0
    for index, i in enumerate(sentence):

        # Skip the value before the cursor
        if index < offset:
            continue

        number  = i
        if i != "0":

            if len(number) == 1:
                nums.append(number)
                offset = index   1
            else:
                length = len(number) * 2 - 1
                word = sentence[offset: offset   length]
                nums.append(word)
                offset  = length
            number = ""

    print(nums)
    
reccurent()
Enter the number:0011000100
['00110', '00100']
  •  Tags:  
  • Related