Try   HackMD

高慶霖

Problem1:

程式說明(程式架構,測試方式…):

  • 用re判斷是否輸入正確
  • def calculate 判斷、計算並輸出

程式執行截圖:


程式碼:

""" 若多項式的根是有理數,請印出綠色的多項式的因式分解 若多項式的根是無理數,請印出藍色的多項式的根 若多項式的根是複數,請印出紅色的無解 """ from __future__ import division from sympy import * import re from colorama import init, Fore def calculate(a, b, c): #print(a,b,c) d = (b**2)-(4*a*c) if(d < 0): print(Fore.RED + "無解") else: a1 = (-b+d**0.5)/(2*a) a2 = (-b-d**0.5)/(2*a) x = symbols('x') f = a*x**2 + b*x + c if(f == factor(f)): if(a1!=a2): print(Fore.BLUE + f"{a1}") print(Fore.BLUE + f"{a2}") else: print(Fore.BLUE + f"{a1}") else: print(Fore.GREEN + f"{factor(f)}") while True: init(autoreset = True) try: f = input() f = f.replace(' ', '') #f = 'x^2+666x+2' #f = '6x^2+5x+1' #f = 'x^2+2x+1' #f = '2x^2+x+1' pattern = '\s*([-+]?)\s*(\d*)\s*[x]\s*\^\s*[2]\s*([-+]?)\s*(\d*)\s*[x]\s*([-+]?)\s*(\d*)\s*' if(re.search(pattern,f)==None): raise if(re.search(pattern,f).group(1) == '+' or re.search(pattern,f).group(1) == ''): if(re.search(pattern,f).group(2) == ''): x2 = 1 else: x2 = int(re.search(pattern,f).group(2)) else: x2 = int(re.search(pattern,f).group(2))*(-1) if(re.search(pattern,f).group(3) == '+'): if(re.search(pattern,f).group(4) == ''): x1 = 1 else: x1 = int(re.search(pattern,f).group(4)) else: x1 = int(re.search(pattern,f).group(4))*(-1) if(re.search(pattern,f).group(5) == '+'): x = int(re.search(pattern,f).group(6)) else: x = int(re.search(pattern,f).group(6))*(-1) calculate(x2, x1, x) break except: print("輸入錯誤,請學生重新輸入")