65 lines
1.7 KiB
Python
65 lines
1.7 KiB
Python
|
import re
|
||
|
import random
|
||
|
import operator
|
||
|
|
||
|
# Define operators and their corresponding functions
|
||
|
ops = {
|
||
|
'+': operator.add,
|
||
|
'-': operator.sub,
|
||
|
'*': operator.mul,
|
||
|
'/': operator.truediv
|
||
|
}
|
||
|
|
||
|
def calculate(expression, num=1):
|
||
|
"""Calculate the result of the expression using n[0], n[1], ..."""
|
||
|
numbers = [random.randint(1, 10) for _ in range(num)]
|
||
|
print(numbers)
|
||
|
# Replace placeholders with actual number values
|
||
|
for i, num in enumerate(numbers):
|
||
|
placeholder = f'n{i}'
|
||
|
expression = re.sub(rf'\{placeholder}\s*([+-/*])', rf'{num} \1', expression)
|
||
|
expression = re.sub(rf'({placeholder})\s*', rf'{num}', expression)
|
||
|
|
||
|
print(expression)
|
||
|
# Evaluate the result
|
||
|
return eval(expression)
|
||
|
|
||
|
def parse_expression(expression):
|
||
|
"""Parse an algebraic expression and determine the required number of numbers"""
|
||
|
op_count = 0
|
||
|
|
||
|
# Count operators in parentheses
|
||
|
paren_count = 1
|
||
|
max_depth = 0
|
||
|
|
||
|
for i, char in enumerate(expression):
|
||
|
if char == '(':
|
||
|
paren_count += 1
|
||
|
elif char == ')':
|
||
|
paren_count -= 1
|
||
|
|
||
|
# Update max depth when a closed parenthesis is encountered
|
||
|
max_depth = max(max_depth, paren_count)
|
||
|
|
||
|
if char in ops.keys():
|
||
|
op_count += 1
|
||
|
|
||
|
return max_depth + op_count
|
||
|
|
||
|
def main():
|
||
|
expression = input("Enter an algebraic structure (e.g., -(+)): ")
|
||
|
|
||
|
# Handle the empty string case by providing a default expression
|
||
|
if not expression:
|
||
|
expression = 'n0-(n1+n2)'
|
||
|
|
||
|
num_needed = parse_expression(expression)
|
||
|
|
||
|
result = calculate(expression, num_needed)
|
||
|
|
||
|
print(f"Generated calculation: {expression}")
|
||
|
print(f"Result: {result}")
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|