summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
Diffstat (limited to 'python')
-rw-r--r--python/util.py48
1 files changed, 30 insertions, 18 deletions
diff --git a/python/util.py b/python/util.py
index 390b831..f149953 100644
--- a/python/util.py
+++ b/python/util.py
@@ -1,12 +1,16 @@
#!/usr/bin/python
import io
+import re
from tokenize import tokenize
-# Check if code contains a sequence of tokens (given as a list of strings).
-def has_token_sequence(code, sequence):
+def get_tokens(code):
+ """ Gets a list of tokens. """
stream = io.BytesIO(code.encode('utf-8'))
- tokens = [t.string for t in tokenize(stream.readline) if t.string]
+ return [t.string for t in tokenize(stream.readline) if t.string]
+
+# Check if tokens contain a sequence of tokens (given as a list of strings).
+def has_token_sequence(tokens, sequence):
for i in range(len(tokens)-len(sequence)+1):
if tokens[i:i+len(sequence)] == sequence:
return True
@@ -16,23 +20,31 @@ 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 get_numbers(s):
+ """ Extracts numbers from string s. """
+ str_vals = re.findall(r'''
+ [-+]? # optional sign
+ (?:
+ (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
+ |
+ (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
+ )
+ # followed by optional exponent part if desired
+ (?: [Ee] [+-]? \d+ ) ?
+ ''', s, re.VERBOSE)
+ return [float(v) for v in str_vals]
+
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):
+ """ Searches string s for a value that is almost equal to a. """
+ for v in get_numbers(s):
+ if almost_equal(v, a, prec):
return True
- except:
- pass
- return False
+ return False
+
+def string_contains_number(s, a):
+ """ Searches string s for a value that is equal to a. """
+ return a in get_numbers(s)
+
if __name__ == '__main__':
print(has_token_sequence('x + y >= 0', ['>=', '0']))