Run Length coding project isn't outputing

Viewed 29
def expand(nums):
    finalword = ''
    position = 0
    wordlength = len(nums)
    keypoint = ''
    while position <= wordlength:
        keypoint = nums[position] * int(nums[position + 1])
        finalword = finalword + keypoint
        keypoint = 0
        position + 2
    return finalword

For some reason, this function does not return a value. I am trying to get the integers after a char to multiply said char. I add 2 to position due to a char being on every 2nd index

print(expand("d3o5z2y1")) #should output: dddooooozzy

What am I doing wrong?

2 Answers

Your line:

position + 2

does not changes the value of the position. You calculate position + 2, and then throw that value away, you should assign the result to position, so:

def expand(nums):
    finalword = ''
    position = 0
    wordlength = len(nums)
    keypoint = ''
    while position < wordlength:
        keypoint = nums[position] * int(nums[position + 1])
        finalword = finalword + keypoint
        keypoint = 0
        position = position + 2  # or more compact: position += 2
    return finalword

the bound check should be replaced with < since if the position is equal to the length, we already have an index that is too large.

A lot of lines are also unnecessary, we can remove a lot of lines, and retain:

def expand(nums):
    finalword = ''
    wordlength = len(nums)
    for position in range(0, len(nums), 2):
        keypoint = nums[position] * int(nums[position + 1])
        finalword += keypoint
    return finalword

That being said, you can improve the above by using an iter(..)ator, and zip:

def expand(nums):
    inums = iter(nums)
    return ''.join(c * int(n) for c, n in zip(inums, inums))

You never update position.

position + 2 just does a calculation without storing the value of that calculation anywhere. You probably wanted position = position + 2.

In addition, you are off-by-one with position <= wordlength because the last index of nums is len(nums) - 1. Change it to position < wordlength.

With these changes

print(expand("d3o5z2y1"))

produces

'dddooooozzy'

However, your way of extracting the characters and the counts is a bit clunky. I suggest using the grouper recipe from the itertools docs.

>>> s = "d3o5z2y1"
>>> list(zip(*[iter(s)]*2))
>>> [('d', '3'), ('o', '5'), ('z', '2'), ('y', '1')]
>>>
>>> ''.join(char*int(count) for char, count in zip(*[iter(s)]*2))
>>> 'dddooooozzy'
Related