2016年1月23日土曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 4.(Algebra and Symbolic Math with SymPy)、Programming Challenges #1: Factor Finder(No. 2907)を解いてみる。

#1: Factor Finder(No. 2907)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sympy

while True:
    expr = input('Etner a mathematical expression: ')
    if expr == 'q':
        break
    try:
        expr = sympy.sympify(expr)
    except sympy.SympifyError as err:
        print(err)
    else:
        print(sympy.factor(expr))
    

入出力結果(Terminal, IPython)

$ ./sample1.py
Etner a mathematical expression: x**2 - 1
(x - 1)*(x + 1)
Etner a mathematical expression: x**2 + 1
x**2 + 1
Etner a mathematical expression: x**2 + 2*x + 1
(x + 1)**2
Etner a mathematical expression: x ** 2 + 2 * x * y + y ** 2
(x + y)**2
Etner a mathematical expression: x ** 2 +
Sympify of expression 'could not parse 'x ** 2 +'' failed, because of exception being raised:
SyntaxError: unexpected EOF while parsing (<string>, line 1)
Etner a mathematical expression: q
$

0 コメント:

コメントを投稿