Search code examples
pythonfunctionreturnreturn-value

How to use a variable from one function in the next function after returned


Can not pass the encoded information to the the second function. I know that when the variable is returned that the data is basically None. But I'm looking for a work around.

string = 'WWWWBBWWWWBWWWBBBBWWWWWWBBWWWWW'

# Encoding algroithm.
def runLengthEncoding(data):
    runCount = 0
    i = 0
    data = data + '5'
    encoded = ''
    for j in range(len(data)):
        if data[i] == data[j]:
            runCount += 1
        else:
             encoded += str(runCount)+ '' + data[i]
             i = j
             runCount = 1
    return encoded

# Decoding algorithm.
def runLengthDecoding(encoded):
    k = 0
    decoded = ''
    for l in range(len(encoded), 2):
        if encoded[k]:
           if encoded[l]:
              decoded += int(encoded[k]) * encoded[l]
              k += 2
    return decoded

print('\t\t\t***Run Length Encoding***\n')
print('Uncompressed:', string)
print('Encoded:  ', runLengthEncoding(string))
print('\n\t\t\t***Run Length Decoding***\n')
print('Encoded:  ', runLengthEncoding(string))
# Can't use the return value.
print('Decoded:  ', runLengthDecoding(runLengthEncoding(string))) 

Solution

  • The problem isn't that you can't use the return value, the problem is that your Decoding function doesn't actually add anything to your string and just returns "". Replace your decoding function with this bug free version and it will work:

    def runLengthDecoding(encoded):
        decoded = ''
        for i in range(0, len(encoded), 2):
            decoded += int(encoded[i])*encoded[i+1]
        return decoded