[Python] NRZ Scheme Decode

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a function that is supposed to decode an inputted NRZ scheme. My professor also prohibited any usages of import libraries. Here's my code so far.

    def nrz_encoding(input_scheme):
    # Split the input into lines and convert each line into a list of characters
    nrz_scheme = [list(line) for line in input_scheme.strip().split('\n')]

    index = 0
    nrz_output = ''

    # Identify the first and last rows
    first_row = nrz_scheme[0]
    last_row = nrz_scheme[3]

    # Determine the starting row (first or last) based on the leftmost underscore
    if first_row[0] == "_":
    current_row = first_row
    elif last_row[0] == "_":
    current_row = last_row
    else:
    raise ValueError("Please make sure that there's no spaces at the start of your leftmost underscore(_).")

    # Determine the maximum length of the rows
    max_length = max(len(first_row), len(last_row))

    while index < max_length:
    # Determine the current row based on the signal level
    if index < len(first_row) and first_row[index] == "_":
    current_row = first_row
    elif index < len(last_row) and last_row[index] == "_":
    current_row = last_row

    # Translate the signal level to 0 or 1
    if current_row is first_row:
    nrz_output += "0"
    else:
    nrz_output += "1"

    index += 3

    # Check for a transition (vertical bar)
    if index < len(nrz_scheme[1]) and nrz_scheme[1][index] == "|":
    # Switch the current row
    if current_row is first_row:
    current_row = last_row
    else:
    current_row = first_row
    # Move past the transition character
    index += 1

    return nrz_output


    I don't know why but it works for some test cases but not others. Like this one:

    nrz_input = """
    ______
    | |
    | |
    ___| |___
    """


    The input above should spit out a 0110 based on the scheme. But my code outputs a 1000. I don't really know why either. Also, I should note that I'm fairly new to coding.

    Continue reading...

Compartilhe esta Página