### Install cexprtk Source: https://pypi.org/project/cexprtk Install the package using pip. ```bash $ pip install cexprtk ``` -------------------------------- ### Instantiate Symbol_Table Source: https://pypi.org/project/cexprtk Example of initializing a Symbol_Table with variables and constants. ```python st = cexprtk.Symbol_Table({'x' : 1, 'y' : 5}, {'k'= 1.3806488e-23}) ``` -------------------------------- ### Initialize and Evaluate Expression with Variables Source: https://pypi.org/project/cexprtk Demonstrates initializing a Symbol_Table with variables, creating an Expression, and evaluating it. The symbol table's variables can be updated to re-evaluate the expression. ```python >>> import cexprtk >>> st = cexprtk.Symbol_Table({'x' : 5, 'y' : 5}) >>> expression = cexprtk.Expression('x+y', st) >>> expression() 10.0 ``` ```python >>> expression.symbol_table.variables['x'] = 11.0 >>> expression() 16.0 ``` -------------------------------- ### Define unknown symbol resolver return tuple Source: https://pypi.org/project/cexprtk The expected return format for the unknown symbol resolver callback. ```python (HANDLED_FLAG, USR_SYMBOL_TYPE, SYMBOL_VALUE, ERROR_STRING) ``` -------------------------------- ### Utility Functions Source: https://pypi.org/project/cexprtk Direct utility functions for quick expression evaluation and validation. ```APIDOC ## evaluate_expression(expression, variables) ### Description Evaluates a mathematical expression string using a provided dictionary of variables. ### Parameters #### Request Body - **expression** (string) - Required - The mathematical expression to evaluate. - **variables** (dict) - Required - A mapping of variable names to their numeric values. ### Response #### Success Response (200) - **result** (float) - The evaluated result of the expression. ### Request Example { "expression": "(A+B) * C", "variables": {"A": 5, "B": 5, "C": 23} } ### Response Example 230.0 ``` -------------------------------- ### Evaluate with variables Source: https://pypi.org/project/cexprtk Pass a dictionary to map variable names to values within an expression. ```python >>> import cexprtk >>> cexprtk.evaluate_expression("(A+B) * C", {"A" : 5, "B" : 5, "C" : 23}) 230.0 ``` -------------------------------- ### Evaluate Expression with Unknown Symbol Resolver Source: https://pypi.org/project/cexprtk Instantiate a cexprtk Expression with a custom unknown symbol resolver callback and evaluate an expression containing symbols that will be resolved by the callback. The callback logic determines the final value based on the symbol's prefix and a lookup. ```python st = cexprtk.Symbol_Table({}) e = cexprtk.Expression("(m_county_a - f_county_b)", st, callback) e.value() ``` -------------------------------- ### Re-use expressions Source: https://pypi.org/project/cexprtk Create a Symbol_Table and Expression object to evaluate the same formula with different variable values. ```python >>> import cexprtk >>> st = cexprtk.Symbol_Table({'r' : 1.0}, add_constants= True) ``` ```python >>> circumference = cexprtk.Expression('2*pi*r', st) ``` ```python >>> circumference() 6.283185307179586 ``` ```python >>> st.variables['r'] = 3.0 >>> circumference() 18.84955592153876 ``` -------------------------------- ### Class Symbol_Table Source: https://pypi.org/project/cexprtk Manages variables, constants, and functions used by Expression instances. ```APIDOC ## class Symbol_Table ### Description Class for providing variable and constant values to Expression instances. ### Constructor - **variables** (dict) - Required - Mapping between variable name and initial value. - **constants** (dict) - Optional - Dictionary of constants that cannot be updated. - **add_constants** (bool) - Optional - If True, adds standard constants (pi, inf, epsilon). - **functions** (dict) - Optional - Dictionary of custom functions available to expressions. - **string_variables** (dict) - Optional - Mapping for string variables. ### Request Example ```python st = cexprtk.Symbol_Table({'x': 1, 'y': 5}, {'k': 1.3806488e-23}) ``` ``` -------------------------------- ### Evaluate a simple equation Source: https://pypi.org/project/cexprtk Evaluate a basic arithmetic string without variables. ```python >>> import cexprtk >>> cexprtk.evaluate_expression("(5+5) * 23", {}) 230.0 ``` -------------------------------- ### Using String Variables in Expressions Source: https://pypi.org/project/cexprtk Shows how to use string variables within expressions. Note that evaluating an expression with string concatenation might return 'nan' for the main value, but the results can be obtained using the `results()` method. ```python >>> import cexprtk >>> st = cexprtk.Symbol_Table({}) >>> st.string_variables['s1'] = 'he' >>> st.string_variables['s2'] = 'l' >>> st.string_variables['s3'] = 'lo' >>> expression = cexprtk.Expression("return[s1+s2+s3+' world']", st) >>> expression.value() nan >>> expression.results() ['hello world'] ``` -------------------------------- ### Define unknown symbol resolver callback signature Source: https://pypi.org/project/cexprtk The callback function signature for resolving symbols not found in the Symbol_Table. ```python def callback(symbol_name): ... ``` -------------------------------- ### Symbol_Table Class Source: https://pypi.org/project/cexprtk Class for managing variables, constants, and functions used within expressions. ```APIDOC ## class Symbol_Table ### Description Stores variables, constants, and functions for use in expressions. ### Methods - **__init__(variables, constants={}, add_constants=False, functions={})**: Initializes the symbol table. ### Properties - **variables** (dict) - Dictionary-like object to access and modify variables. - **constants** (dict) - Dictionary of constants. - **functions** (dict) - Dictionary of custom functions. ``` -------------------------------- ### Define Unknown Symbol Resolver Callback Source: https://pypi.org/project/cexprtk Implement a callback function to resolve symbols (variables or constants) not found in the Symbol_Table during expression parsing. This allows for dynamic symbol resolution based on custom logic, such as prefix-based weighting. ```python variable_values = { 'county_a' : 82, 'county_b' : 76} ``` ```python def callback(symbol): # Tokenize the symbol name into prefix and VARIABLENAME components. prefix,variablename = symbol.split("_", 1) # Get the value for this VARIABLENAME from the variable_values dict value = variable_values[variablename] # Find the correct weight for the prefix if prefix == 'm': weight = 0.8 elif prefix == 'f': weight = 1.1 else: # Flag an error condition if prefix not found. errormsg = "Unknown prefix "+ str(prefix) return (False, cexprtk.USRSymbolType.VARIABLE, 0.0, errormsg) # Apply the weight to the value *= weight # Indicate success and return value to cexprtk return (True, cexprtk.USRSymbolType.VARIABLE, value, "") ``` -------------------------------- ### Expression Class Source: https://pypi.org/project/cexprtk Class for managing and re-using parsed mathematical expressions. ```APIDOC ## class Expression ### Description Represents a parsed mathematical expression that can be evaluated multiple times with different symbol values. ### Methods - **__init__(expression, symbol_table, unknown_symbol_resolver_callback=None)**: Initializes the expression with a symbol table. - **value()**: Returns the current value of the expression. - **__call__()**: Evaluates and returns the result of the expression. ### Properties - **symbol_table** (Symbol_Table) - The symbol table associated with this expression. ``` -------------------------------- ### Expression Returning Multiple Values (Vector) Source: https://pypi.org/project/cexprtk Define and evaluate a cexprtk expression that returns a vector. The results of such expressions must be accessed using the `results()` method after evaluation. The `value()` method will return NaN for expressions with return statements. ```python st = cexprtk.Symbol_Table({}) e = cexprtk.Expression("var v[3] := {1,2,3}; return [v+1];", st) e.value() e.results() ``` -------------------------------- ### Class Expression Source: https://pypi.org/project/cexprtk Represents a mathematical expression that can be evaluated. It requires a Symbol_Table and supports an optional unknown symbol resolver callback. ```APIDOC ## class Expression ### Description Class representing a mathematical expression. After instantiation, the expression is evaluated by calling the object or invoking its value() method. ### Constructor - **expression** (str) - Required - The formula string to be calculated. - **symbol_table** (Symbol_Table) - Required - Object defining variables and constants. - **unknown_symbol_resolver_callback** (callable) - Optional - A callback invoked when a symbol is not found in the Symbol_Table. ### Methods - **value()** (float) - Evaluates the expression using current variable values. - **results()** (list) - Returns values produced by a 'return []' statement in the expression. - **__call__()** (float) - Equivalent to calling value(). ### Properties - **symbol_table** (Symbol_Table) - Read-only property returning the associated Symbol_Table instance. ``` -------------------------------- ### Utility: evaluate_expression Source: https://pypi.org/project/cexprtk Evaluates a mathematical formula directly using provided variable mappings. ```APIDOC ## evaluate_expression(expression, variables) ### Description Evaluate a mathematical formula using the exprtk library and return the result as a float. ### Parameters #### Arguments - **expression** (str) - Required - The expression string to be evaluated. - **variables** (dict) - Required - A dictionary containing variable name and value pairs. ### Response #### Success Response (200) - **result** (float) - The evaluated result of the expression. ### Raises - **ParseException** - Raised if the expression is invalid. ``` -------------------------------- ### Expression Returning Multiple Values (Mixed Types) Source: https://pypi.org/project/cexprtk Evaluate a cexprtk expression that returns a mixture of strings and numerical values based on conditional logic. The `results()` method is used to retrieve these values, and the results can change if variables in the Symbol_Table are updated. ```python st = cexprtk.Symbol_Table({'c' : 3}) e = cexprtk.Expression("if(c>1){return ['bigger than one', c];} else { return ['not bigger than one',c];};",st) e.value() e.results() ``` ```python st.variables['c']=0.5 e.value() e.results() ``` -------------------------------- ### Define and Register Custom Python Function Source: https://pypi.org/project/cexprtk Register a Python function with a Symbol_Table to be used within cexprtk expressions. The function name used in the expression cannot conflict with existing variables, constants, or reserved names. ```python import random def rnd(low, high): return random.uniform(low,high) ``` ```python import cexprtk st = cexprtk.Symbol_Table({}) st.functions["rand"] = rnd ``` -------------------------------- ### Utility: check_expression Source: https://pypi.org/project/cexprtk Validates if a given mathematical expression string can be parsed by the library. ```APIDOC ## check_expression(expression) ### Description Check that an expression can be parsed. If successful, the function completes silently; if unsuccessful, it raises a ParseException. ### Parameters #### Arguments - **expression** (str) - Required - The mathematical formula to be validated. ### Raises - **ParseException** - Raised if the provided expression is invalid. ``` -------------------------------- ### Use Custom Function in cexprtk Expression Source: https://pypi.org/project/cexprtk Evaluate a cexprtk expression that utilizes a custom-registered function. The expression may produce different results on each evaluation due to the nature of the custom function (e.g., random number generation). ```python e = cexprtk.Expression("rand(5,8) * 10", st) e() ``` ```python e() ``` ```python e() ``` ```python e() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.