Search code examples
python-2.7stringbuffer

Faster "switch-case" implementation in python


I made the script below to read a string buffer and distribute the numbers in 6 different variables. I found an example doing the same in C# using switch-case method, and when I tried a similar method in python (as shown below) I got the desired result but it takes too much time to read the buffer (more than a second). This script is just a way to test the method, and it will be a part of a bigger open-loop control code, so the loop time is really important. Is there any faster way to do in in python? I use python 2.7. Thank you in advance.

Julio = '123.5,407.4,21.6,9.7,489.2,45.9/\n'

letter = ''
x_c = '' 
y_c = '' 
z_c = '' 
theta_c = '' 
ux_c = '' 
uy_c = '' 
variable_number = 1

def one():
    global x_c
    x_c += letter

def two():
    global y_c
    y_c += letter

def three():
    global z_c
    z_c += letter

def four():
    global theta_c
    theta_c += letter

def five():
    global ux_c
    ux_c += letter

def six():
    global uy_c
    uy_c += letter

def string_reader(variable_number):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
        5: five,
        6: six
    }
    # Get the function from switcher dictionary
    func = switcher.get(variable_number, lambda: 'Invalid variable number')
    # Execute the function
    print func()

for letter in Julio:
    if (letter != '/') and (letter != ',') and (letter != '\n'):
        string_reader(variable_number)
    elif (letter == '/'):
        break
    elif (letter == '\n'):
        break
    else:
        variable_number = variable_number + 1


print x_c, y_c, z_c, theta_c, ux_c, uy_c

Solution

  • Err... Aren't you overcomplicating things ?

    >>> Julio = '123.5,407.4,21.6,9.7,489.2,45.9/\n'
    >>> x_c, y_c, z_c, theta_c, ux_c, uy_c = Julio.strip().rstrip("/").split(",")[:6]