fork download
  1. # your code goes here
  2. import random
  3.  
  4. def generate_question():
  5. while True:
  6. # 生成括号结构:如 (a ± b) ± (c ± d) 或 a ± (b ± c)
  7. structure = random.choice(["(a ± b) ± (c ± d)", "a ± (b ± c) ± d"])
  8. nums = [random.randint(1, 100) for _ in range(4)]
  9. a, b, c, d = sorted(nums, reverse=True) # 控制数值大小避免负数
  10.  
  11. # 随机运算符组合(仅加减)
  12. ops = [random.choice(["+", "-"]) for _ in range(3)]
  13. expr = structure.replace("a", str(a)).replace("b", str(b)).replace("c", str(c)).replace("d", str(d))
  14. expr = expr.replace("±", ops[0], 1).replace("±", ops[1], 1).replace("±", ops[2], 1)
  15.  
  16. # 计算结果并验证范围
  17. try:
  18. result = eval(expr)
  19. if 0 <= result <= 100 and all(0 <= eval(part) <= 100 for part in expr.split("±")[::2]):
  20. return expr
  21. except:
  22. continue
  23.  
  24. # 生成500道题目
  25. questions = [generate_question() for _ in range(500)]
Success #stdin #stdout 0.2s 14376KB
stdin
Standard input is empty
stdout
Standard output is empty