util.py 1.04 KB
Newer Older
ichuang committed
1 2 3 4 5 6 7 8 9
from calc import evaluator, UndefinedVariable

#-----------------------------------------------------------------------------
#
# Utility functions used in CAPA responsetypes

def compare_with_tolerance(v1, v2, tol):
    ''' Compare v1 to v2 with maximum tolerance tol
    tol is relative if it ends in %; otherwise, it is absolute
ichuang committed
10 11 12 13 14

     - v1    :  student result (number)
     - v2    :  instructor result (number)
     - tol   :  tolerance (string or number)

ichuang committed
15 16 17 18 19 20 21 22 23
    '''
    relative = "%" in tol
    if relative: 
        tolerance_rel = evaluator(dict(),dict(),tol[:-1]) * 0.01
        tolerance = tolerance_rel * max(abs(v1), abs(v2))
    else: 
        tolerance = evaluator(dict(),dict(),tol)
    return abs(v1-v2) <= tolerance

24 25 26
def contextualize_text(text, context): # private
    ''' Takes a string with variables. E.g. $a+$b. 
    Does a substitution of those variables from the context '''
27
    if not text: return text
28 29 30
    for key in sorted(context, lambda x,y:cmp(len(y),len(x))):
        text=text.replace('$'+key, str(context[key]))
    return text