Szarny.io

There should be one-- and preferably only one --obvious way to do it.

Python3メモ - SymbolとFiniteSet

Sympyのインポート

from sympy import *

Sympyシンボルの生成と利用

x = Symbol("x")

y = Symbol("y")

exp = (x + y) * (x - y)

 

# 式の展開(expand)

exp.expand() # x**2 - y**2

 

# 変数への値代入

exp.subs({x:1, y:4}) # -15

二次方程式の解の公式

x = Symbol("x")
a = Symbol("a")
b = Symbol("b")
c = Symbol("c")

exp = a*x*x + b*x + c

 

# expをxについて解く
solve(exp, x) # [(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]

連立方程式を解く

x = Symbol("x")
y = Symbol("y")
exp1 = 2*x + 3*y - 6
exp2 = 3*x + 2*y - 12

 

# タプルとして引数に設定
solve((exp1, exp2), dict=True) # [{x:24/5,y:−6/5}]

 円の方程式(r=5)

x = Symbol("x")

y = Symbol("y")

 

# sympify関数を用いて文字列をsympy形式に変換

exp_str = "x*x + y*y - 25"
exp = sympify(exp_str)


s = solve(exp, y) # [-sqrt(-x**2 + 25), sqrt(-x**2 + 25)]

plot(s[0], s[1])

 

f:id:Szarny:20170716194507p:plain

 

集合関連

mylist = [1,2,3,4,5,5]

myset = FiniteSet(*mylist) # {1, 2, 3, 4, 5}

 

# 部分集合・真部分集合の判定

a = FiniteSet(1,2,3)

b = FiniteSet(1,2,3,4,5)

c = FiniteSet(1,2,3,4,5)

a.is_superset(b) # False (a ⊇ b)

a.is_subset(b) # True (a ⊆ b)

c.is_proper_superset(b) # False (c ⊃ b)

 

# 和・積・直積・冪集合

a = FiniteSet(1,2,3)
b = FiniteSet(2,3,4)

a.union(b) # {1, 2, 3, 4} (a ∪ b)

a.intersect(b) # {2, 3} (a ∩ b)

for element in a * b:

  element # (1, 2) (1, 3) (1, 4) (2, 2) (2, 3) (2, 4) (3, 2) (3, 3) (3, 4)

a.powerset() # {∅, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}

 集合を用いたビット列の出力

bit = FiniteSet(0,1)

# 4つのbit集合の直積

for decimal, halfbyte in enumerate(bit ** 4):

  print(decimal, "=", halfbyte) 

# 0 = (0, 0, 0, 0)
# 1 = (0, 0, 0, 1)
# 2 = (0, 0, 1, 0)
...
# 14 = (1, 1, 1, 0)
# 15 = (1, 1, 1, 1)