pythonimplementation

nrzi signal decoding implementation in python - whats wrong?


solving simple nrzi python decoding. 0 bit means no changed occurred but 1 bit means a change occurred in digital signal sequence.

"_": low signal
'¯': high signal
"|": pipe signal( pipe  leads to change of signal and itself pipe is not recorded)

given input: _ | ¯ | _ _ _ | ¯ | _| ¯ ¯ ¯

output: 011000110100

my code:

def nrzi(signal: str) -> str:
    res = ''
    prev = '_'  

    for i in range(len(signal)):
        cur = signal[i]
        prev = signal[i-1]
        #signal same as prev - no change
        if (prev == cur == '_') or (prev == cur == '¯'):
            res += '0'
        #signal changed cuz prev is pipe
        elif prev == '|' and cur == '_':
            res += '0'
        elif prev == '|' and cur == '¯':
            res += '1'
                          
    return ''.join(res)

signal = "_|¯|____|¯|__|¯¯¯"

result = nrzi(signal)
print(result)

it produces

10000100100 vs correct 011000110100

whats wrong?


Solution

  • you had two problem in your code

    first: at the first time looping through the for loop you are getting the last result with the signal[i-1] this means at the first you will be getting the _- which means +1 this is happening because python is looking at the if statements and none of them declare anything about the _- so python uses the last statement which is the +1.

    second: is your if statement going from your output that you expect you want to get 1 every time you have |_ so I changed it to look like this:

    elif prev == '|' and cur == '_':
                res += '1'
    

    The code now looks like this and the output is: 011000110100:

    def nrzi(signal: str) -> str:
        res = ''
        prev = '_'
    
        for i in range(len(signal)):
            cur = signal[i]
            prev = [signal[i], signal[i-1]] [i >= 1]
    
            #signal same as prev - no change
            if (prev == cur == '_') or (prev == cur == '¯'):
               res += '0'
            #signal changed cuz prev is pipe
            elif prev == '|' and cur == '_':
               res += '1'
            elif prev == '|' and cur == '¯':
               res += '1'
    
    
        return ''.join(res)
    
    signal = "_|¯|____|¯|__|¯¯¯"
    
    result = nrzi(signal)
    print(result)