summaryrefslogtreecommitdiff
path: root/searx/answerers/statistics/answerer.py
blob: 60f0d304fb44974146092fad4767b0e19380901b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from functools import reduce
from operator import mul

from flask_babel import gettext


keywords = ('min', 'max', 'avg', 'sum', 'prod')


# required answerer function
# can return a list of results (any result type) for a given query
def answer(query):
    parts = query.query.split()

    if len(parts) < 2:
        return []

    try:
        args = list(map(float, parts[1:]))
    except:
        return []

    func = parts[0]
    answer = None

    if func == 'min':
        answer = min(args)
    elif func == 'max':
        answer = max(args)
    elif func == 'avg':
        answer = sum(args) / len(args)
    elif func == 'sum':
        answer = sum(args)
    elif func == 'prod':
        answer = reduce(mul, args, 1)

    if answer is None:
        return []

    return [{'answer': str(answer)}]


# required answerer function
# returns information about the answerer
def self_info():
    return {
        'name': gettext('Statistics functions'),
        'description': gettext('Compute {functions} of the arguments').format(functions='/'.join(keywords)),
        'examples': ['avg 123 548 2.04 24.2'],
    }