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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
| LEFT_BRACKET = '(' RIGHT_BRACKET = ')'
def bracket_validate(input_str): """ function for part1 checks whether any brackets occurring in the string appear as correctly matched pairs of one opening bracket :param input_str: :return: bracket is matched or not """ stack = [] for char in input_str: if char == LEFT_BRACKET: stack.append(char) elif char == RIGHT_BRACKET: if len(stack) != 0 and stack[-1] == LEFT_BRACKET: stack.pop() else: return False else: pass return len(stack) == 0
def test_bracket_validate(): assert bracket_validate("()") is True assert bracket_validate("a") is True assert bracket_validate("(b())") is True assert bracket_validate("(") is False assert bracket_validate("()a)") is False assert bracket_validate("|)") is False assert bracket_validate("(]") is False assert bracket_validate("([)") is True assert bracket_validate("[[") is True assert bracket_validate("(a(bb)ccc)dddd") is True assert bracket_validate("(a)bb()ccc") is True
def get_content_of_first_bracket(input_str): """ function for part2a returns the contents of the first matched pair of brackets :param input_str: :return: content of first brackets """ if bracket_validate(input_str): stack = [] start_idx, end_idx = None, None for idx in range(len(input_str)): char = input_str[idx] if char == LEFT_BRACKET: if start_idx is None: start_idx = idx stack.append(char) elif char == RIGHT_BRACKET: if len(stack) != 0 and stack[-1] == LEFT_BRACKET: stack.pop() if end_idx is None and len(stack) == 0: end_idx = idx else: pass if start_idx is not None: result = input_str[(start_idx + 1): end_idx] return result else: return "" else: print("error, input string contains mismatched brackets!") return None
def test_get_content_of_first_bracket(): assert get_content_of_first_bracket("(a)") == "a" assert get_content_of_first_bracket("()") == "" assert get_content_of_first_bracket("abcd") == "" assert get_content_of_first_bracket("a (b) c (d)") == "b" assert get_content_of_first_bracket("((a) b (c) d)") == "(a) b (c) d" assert get_content_of_first_bracket("(a(bb)ccc)dddd") == "a(bb)ccc" assert get_content_of_first_bracket("()a)") is None
def get_content_without_nested_bracket_in_first_bracket(input_str): """ function for part2b returns the contents of the first pair of brackets, except not including anything contained within any further nested brackets :param input_str: :return: content of first pair of brackets without content in nested brackets """ content_of_first_bracket = get_content_of_first_bracket(input_str) if content_of_first_bracket is None: return None stack = [] result = '' for char in content_of_first_bracket: if char == LEFT_BRACKET: stack.append(char) elif char == RIGHT_BRACKET: stack.pop() else: if len(stack) == 0: result += char else: pass return result
def test_get_content_without_nested_bracket_in_first_bracket(): assert get_content_without_nested_bracket_in_first_bracket("(a)") == "a" assert get_content_without_nested_bracket_in_first_bracket("((a))") == "" assert get_content_without_nested_bracket_in_first_bracket("((a)b)") == "b" assert get_content_without_nested_bracket_in_first_bracket("a (b (c) d) e") == "b d" assert get_content_without_nested_bracket_in_first_bracket("(a(bb)ccc)dddd") == "accc" assert get_content_without_nested_bracket_in_first_bracket("((a) b (c) d)") == " b d" assert get_content_without_nested_bracket_in_first_bracket("((a)b") is None
OPERATORS = ['+', '-', '*', '/', '^']
def parse_mathematical_expressions(expression): """ function for part3 analyze a math expression and spilt them into list formatted as [operator, left-hand tree, right-hand tree] :param expression: :return: list of math expression """ if len(expression) == 1 and expression.isalpha(): return expression if expression.isdigit(): return expression stack = [] item_temp = '' for char in expression: if char == LEFT_BRACKET: stack.append(char) elif char == RIGHT_BRACKET: if len(item_temp): stack.append(item_temp) item_temp = '' right = stack.pop() op = stack.pop() left = stack.pop() left_bracket = stack.pop() stack.append([op, left, right]) elif char in OPERATORS: if len(item_temp): stack.append(item_temp) stack.append(char) item_temp = '' else: item_temp += char return stack.pop()
def test_parse_mathematical_expressions(): assert parse_mathematical_expressions("52837") == '52837' assert parse_mathematical_expressions("x") == 'x' assert parse_mathematical_expressions("(a+b)") == ['+', "a", "b"] assert parse_mathematical_expressions("((a+b)^2)") == ['^', ['+', "a", "b"], "2"] assert parse_mathematical_expressions("((a+b)/(374-c))") == ['/', ['+', "a", "b"], ['-', "374", "c"]] assert parse_mathematical_expressions("(((x^2)*(x/(y^3)))+1)") == ['+', ['*', ['^', "x", "2"], ['/', "x", ['^', "y", "3"]]], "1"]
FUNCTIONS = ['exp', 'log', 'sin', 'cos']
def parse_mathematical_expressions_with_function(expression): """ function for part4 analyze math expression with math function such as sin and cos eg. :param expression: math expression :return:list of math expression """ stack = [] item_temp = '' for char in expression: if char == LEFT_BRACKET: if len(item_temp): stack.append(item_temp) item_temp = '' stack.append(char) elif char == RIGHT_BRACKET: if len(item_temp): stack.append(item_temp) item_temp = '' temp_arr = [] item = stack.pop() while item != LEFT_BRACKET: temp_arr.insert(0, item) item = stack.pop() if len(stack) != 0 and stack[-1] in FUNCTIONS: stack.append([stack.pop(), temp_arr[0]]) elif len(temp_arr) == 3: stack.append([temp_arr[1], temp_arr[0], temp_arr[2]]) else: stack.append(temp_arr[0]) elif char in OPERATORS: if len(item_temp): stack.append(item_temp) stack.append(char) item_temp = '' else: item_temp += char if item_temp != '': stack.append(item_temp) return stack.pop()
def test_parse_mathematical_expressions_with_function(): assert parse_mathematical_expressions_with_function("exp(1)") == ["exp", "1"] assert parse_mathematical_expressions_with_function("(a+sin(x))") == ['+', "a", ["sin", "x"]] assert parse_mathematical_expressions_with_function("(log(r)^3)") == ['^', ["log", "r"], "3"] assert parse_mathematical_expressions_with_function("log(log(((2*n)+1)))") == ["log", ["log", ['+', ['*', "2", "n"], "1"]]]
def simple_diff(fx): """ function for part5 get diff of f(x) :param fx: f(x) :return: diff of f(x) """ if fx == 'x': return 1 if fx.isdigit() or fx.isalpha(): return 0 if fx.startswith('exp'): return f"exp({get_content_of_first_bracket(fx)})" if fx.startswith('log'): return f"1/{get_content_of_first_bracket(fx)}" if fx.startswith('sin'): return f"cos({get_content_of_first_bracket(fx)})" if fx.startswith('cos'): return f"-sin({get_content_of_first_bracket(fx)})" if '^' in fx: power_items = fx.split('^') power_value = int(power_items[1]) if power_value >= 1: return f"{power_value}*({power_items[0]}^{power_value - 1})" else: return 0
FUNCTION_OPERATORS = ['+', '-', '*', '/']
def is_simple_diff(item_list): """ function for part5 judge that input can apply simple_diff function or not :param item_list: :return: """ for item in item_list: if isinstance(item, list): return False return True
def get_source_item(item_list): """ get source expression from split list :param item_list: :return: """ if not isinstance(item_list, list): return item_list if is_simple_diff(item_list): if len(item_list) == 3: return f"{item_list[1]}{item_list[0]}{item_list[2]}" elif len(item_list) == 2: return f"{item_list[0]}({item_list[1]})" else: if len(item_list) == 3: return f"{get_source_item(item_list[1])}{get_source_item(item_list[0])}{get_source_item(item_list[2])}" elif len(item_list) == 2: return f"{get_source_item(item_list[0])}({get_source_item(item_list[1])})"
def recursion_diff(item_list): """ get diff of complex expression by recursion :param item_list: :return: """ len_of_item_list = len(item_list) if is_simple_diff(item_list): if len_of_item_list == 3: operator = item_list[0] left_hand = item_list[1] right_hand = item_list[2] if operator == '^': return simple_diff(f"{left_hand}^{right_hand}") elif operator == '-': return f"{simple_diff(left_hand)}-{simple_diff(right_hand)}" elif operator == '+': return f"{simple_diff(left_hand)}+{simple_diff(right_hand)}" elif operator == '*': pass else: pass elif len_of_item_list == 2: func = item_list[0] func_parameter = item_list[1] return simple_diff(f"{func}({func_parameter})") else: if len_of_item_list == 3: operator = item_list[0] left_hand = item_list[1] right_hand = item_list[2] if operator == '^': return None elif operator == '-': return f"{recursion_diff(left_hand)}-{recursion_diff(right_hand)}" elif operator == '+': return f"{recursion_diff(left_hand)}+{recursion_diff(right_hand)}" elif operator == '*': return f"{recursion_diff(left_hand)}*{get_source_item(right_hand)}" \ f"+{recursion_diff(right_hand)}*{get_source_item(left_hand)}" elif operator == '/': a = f"{recursion_diff(left_hand)}*{get_source_item(right_hand)}-{recursion_diff(right_hand)}*{get_source_item(left_hand)}" b = f"({get_source_item(right_hand)})^2" return f"({a}/{b})" else: pass elif len_of_item_list == 2: func = item_list[0] func_parameter = item_list[1] a = simple_diff(f"{func}({get_source_item(func_parameter)})") b = recursion_diff(func_parameter) return f"{a}*{b}"
def symbolic_differentiation(expression): """ function for part5 get diff of expression :param expression: :return: """ mathematical_expressions_with_function_parse_result = parse_mathematical_expressions_with_function(expression) if not isinstance(mathematical_expressions_with_function_parse_result, list): return simple_diff(mathematical_expressions_with_function_parse_result) else: return recursion_diff(mathematical_expressions_with_function_parse_result)
def test_symbolic_differentiation(): print(symbolic_differentiation("32")) print(symbolic_differentiation("a")) print(symbolic_differentiation("x")) print(symbolic_differentiation("(1+x)")) print(symbolic_differentiation("(x^5)")) print(symbolic_differentiation("((x^3)-(x^2))")) print(symbolic_differentiation("exp(1)")) print(symbolic_differentiation("exp(x)")) print(symbolic_differentiation("exp((x^2))")) print(symbolic_differentiation("((x^2)*exp(x))")) print(symbolic_differentiation("log(sin(x))")) print(symbolic_differentiation("log(sin((x^2)))"))
if __name__ == '__main__': test_bracket_validate() test_get_content_of_first_bracket() test_get_content_without_nested_bracket_in_first_bracket() test_parse_mathematical_expressions() test_parse_mathematical_expressions_with_function() test_symbolic_differentiation()
|