47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
|
import re
|
||
|
import random
|
||
|
|
||
|
def calculate(expression, num=1):
|
||
|
"""Calculate the result of the expression using n[0], n[1], ..."""
|
||
|
|
||
|
# Generate random numbers and replace placeholders with them in the expression
|
||
|
numbers = [random.randint(1, 10) for _ in range(num)]
|
||
|
new_expression = expression
|
||
|
|
||
|
for i, num in enumerate(numbers):
|
||
|
placeholder = f'n[{i}]'
|
||
|
new_expression = re.sub(rf'\b{n[i]}(\W|$)', str(num), new_expression)
|
||
|
|
||
|
# Evaluate the result
|
||
|
return eval(new_expression)
|
||
|
|
||
|
def parse_expression(expression):
|
||
|
"""Parse an algebraic expression and determine the required number of numbers"""
|
||
|
|
||
|
count_n = 0
|
||
|
|
||
|
i = 0
|
||
|
for char in expression:
|
||
|
if char == 'n' and (i+1 < len(expression) and expression[i+1] == '['):
|
||
|
count_n += 1
|
||
|
i += 1
|
||
|
|
||
|
return count_n
|
||
|
|
||
|
def main():
|
||
|
expression = input("Enter an algebraic structure (e.g., -(+)): ")
|
||
|
|
||
|
# Handle the empty string case by providing a default expression
|
||
|
if not expression:
|
||
|
expression = '-(+)'
|
||
|
|
||
|
num_needed = parse_expression(expression)
|
||
|
|
||
|
result = calculate(expression, num_needed)
|
||
|
|
||
|
print(f"Generated calculation: {expression}")
|
||
|
print(f"Result: {result}")
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|