spitta12
spitta12

Reputation: 3

How to calculate my program difference in python

so I send out two commands and through a communication port and a two strings are returned to me like this: accel x y z: -181 -7962 668 and accel x y z: -182 -7968 675. I need to calculate the difference and make sure they’re not more than 10. I then used the re.search n regex to group that string according like this: re.search('(-?\d{2,3})\s(-?\d{3,4})\s(-?\d{2,3})$', log[1])

Here’s what I have so far, my python script keeps failing and I don’t know why. If anyone can help it’ll be much appreciated.

Send a command through a communication channel and get back: accel x y z: -181 -7962 668 and accel x y z: -182 -7968 675.

accelSample = re.search('(-?\d{2,3})\s(-?\d{3,4})\s(-?\d{2,3})$', log[1])    
accelSample2 = re.search('(-?\d{2,3})\s(-?\d{3,4})\s(-?\d{2,3})$', log[1])

if accelSample:

    x_avg = int(accelSample.group(1) - accelSample2.group(1))
    y_avg = int(accelSample.group(2) - accelSample2.group(2))
    z_avg = int(accelSample.group(3) - accelSample2.group(3))
    #calculating difference from group 1
    if abs(x_avg) < 10 or abs(y_avg) < 10 or abs(z_avg) < 10:
        return Test.TestResult.PASS

else:
    return Test.TestResult.FAIL

Upvotes: 0

Views: 36

Answers (1)

johntellsall
johntellsall

Reputation: 15170

  • each regex match is a string, and has to be cast to an int separately

  • if any x,y,z value is > 10 from the other sample, then it fails. Original code was too lenient

  • fields tend to have random numbers of spaces -- new regex allows this

source

import re

sample_pat = re.compile(
    '(-?\d{2,3})\s+'
    '(-?\d{3,4})\s+'
    '(-?\d{2,3})$'
    )

def check(log):
    s1 = sample_pat.search(log[0])
    s2 = sample_pat.search(log[1])

    for n in range(1, 3+1):
        if abs( int(s1.group(n)) - int(s2.group(n)) ) > 10:
            return 'fail'
    return 'pass'

print check(['accel x y z: -181 -7962 668',
             'accel x y z: -182 -7968 675'
         ])

output

pass

Upvotes: 1

Related Questions