summaryrefslogtreecommitdiff
path: root/python/util.py
blob: 390b831be73595eae4a4344be4e98fac12e3d633 (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
#!/usr/bin/python

import io
from tokenize import tokenize

# Check if code contains a sequence of tokens (given as a list of strings).
def has_token_sequence(code, sequence):
    stream = io.BytesIO(code.encode('utf-8'))
    tokens = [t.string for t in tokenize(stream.readline) if t.string]
    for i in range(len(tokens)-len(sequence)+1):
        if tokens[i:i+len(sequence)] == sequence:
            return True
    return False

def almost_equal(a, b, prec=1):
    """ Compares values a and b using at most <code>prec</code> decimal values. """
    return int(a*10**prec) == int(b*10**prec)

def string_almost_equal(s, a, prec=1):
    """ Searches string s for a value that is almost equal to a.

    Args:
        s (str): string to search
        a (float): value to find in string

    Returns:
        bool: True if successful, else False
    """
    for v in s.split():
        try:
            if almost_equal(float(v), a, prec):
                return True
        except:
            pass
    return False 

if __name__ == '__main__':
    print(has_token_sequence('x + y >= 0', ['>=', '0']))
    print(has_token_sequence('x + y > 0', ['>=', '0']))