简体   繁体   中英

Statistics Mode function Exceptions in Python

I have compiled a small code using the mode function from the statistics library in python. The code is basically taking input from sensors, listing them in an array of 10 inputs and then finding the mode in that list. The problem is that as soon as there are 2 equally common values, the codes gives "StatisticsError: no unique mode".

Instead of giving an error, I want it to print the data with the lesser value. This might be possible if I could access the list which the mode function makes and then compare the "2 or more modes", but I don't quite know how to do that.

import RPi.GPIO as GPIO
import time
import math
import statistics
GPIO.setmode(GPIO.BCM)

TRIGA = 23 
ECHOA = 24
TRIGB = 17 
ECHOB = 27

dist_lista=[]
dist_listb=[]

print "Distance Measurement In Progress"

GPIO.setup(TRIGA,GPIO.OUT)
GPIO.setup(ECHOA,GPIO.IN)
GPIO.setup(TRIGB,GPIO.OUT)
GPIO.setup(ECHOB,GPIO.IN)

GPIO.output(TRIGA, False)
print "Waiting For Sensor To Settle"
time.sleep(1)
GPIO.output(TRIGB, False)
time.sleep(1)

def roundoff(x):
    return int(math.ceil(x/10.0))*10

def function(TRIG, ECHO, var):
    dist_list = []
    for i in range (0,10):
        GPIO.output(TRIG, True)
        time.sleep(0.00001)
        GPIO.output(TRIG, False)

        while GPIO.input(ECHO)==0:
            pulse_start = time.time()

        while GPIO.input(ECHO)==1:
            pulse_end = time.time()

        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17150
        distance = roundoff(distance)
        dist_list.append(distance)
        time.sleep(0.01)
    if(distance<350 and distance>40):
        try:
            print "Distance",var, ":", statistics.mode(dist_list),"cm"
        except statistics.StatisticsError as e:
            print "Error: ", e
    time.sleep(0.1)
while True:
    function(TRIGA, ECHOA, "A")
    function(TRIGB, ECHOB, "B")

GPIO.cleanup()

Thank you in advance

Use this function instead of statistics.mode :

def lower_mode(sequence):
    try:
        return statistics.mode(sequence)
    except statistics.StatisticsError as e:
        return sorted(sequence)[len(sequence)//2 - 1]

You can then replace the whole try-except block in your code with this call:

if(distance < 350 and distance > 40):
    print "Distance", var, ":", lower_mode(dist_list), "cm"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM