2020年12月26日 星期六

判斷是否為閏年

year=int(input("enter one number of year"))
if (year%4)==0:
    if (year%100)==0:
         if(year%400)==0:
             print("{}是閏年".format(year))
         else:
             print("{}是平年".format(year))
    else:
        print("{}是平年".format(year))
else:
    print("{}是平年".format(year))
    

2020年12月22日 星期二

更新 list array 內容


=========list 更新內容 =====
list01=["apple","banan","cherry","durian","eggplant","fig"]
print(list01)
list01[2]=888
print(list01)

結果
['apple', 'banan', 'cherry', 'durian', 'eggplant', 'fig']
['apple', 'banan', 888, 'durian', 'eggplant', 'fig']


============array 更新內容 =====
from array import *
array01=array("i",[1,2,3,4,5,6,7])
print(array01)
array01[2]=999
print(array01)

結果
['apple', 'banan', 'cherry', 'durian', 'eggplant', 'fig']
['apple', 'banan', 888, 'durian', 'eggplant', 'fig']

array list index


===== 搜尋array元素====
from array import *
array01=array("i",[1,2,3,4,5,6,7])
print(array01)
print(array01.index(6))

結果
array('i', [1, 2, 3, 4, 5, 6, 7])
5



===== 搜尋list元素====
list01=["apple","banan","cherry","durian","eggplant","fig"]
a=list01.index("apple")
print(list01)
print(a)

結果
['apple', 'banan', 'cherry', 'durian', 'eggplant', 'fig']
0

處理字串

str1="""やられたらやり返す、倍返しだ!
      以牙還牙,加倍奉還"""
str2="やられたらやり返す、倍返しだ!"\
      "以牙還牙,加倍奉還"
str3=("やられたらやり返す、倍返しだ!"+
      "以牙還牙,加倍奉還")
print(str1)
print(str2)
print(str3)


結果
やられたらやり返す、倍返しだ!
      以牙還牙,加倍奉還
やられたらやり返す、倍返しだ!以牙還牙,加倍奉還
やられたらやり返す、倍返しだ!以牙還牙,加倍奉還

array 的建立,插入,刪除

建立
from array import *  #array模組 可建立 整數 浮點數的陣列
x=array("i",[1,2,3,4,5,6,7])
for data in x:
    print(data,end=",")
print()
for i in range(len(x)):
    print("x的索引值{}是{}".format(i,x[i]))
    
print(type(x))
print(x[0])


結果是
1,2,3,4,5,6,7,
x的索引值0是1
x的索引值1是2
x的索引值2是3
x的索引值3是4
x的索引值4是5
x的索引值5是6
x的索引值6是7
<class 'array.array'>
1


list的建立
list01=[1,2,3,4,5,6,7]
print(list01)

=============array  的插入 刪除============
from array import *  #array模組 可建立 整數 浮點數的陣列
x=array("i",[1,2,3,4,5,6,7])
x.insert(1,999)
print(x)
print(x[1])
x.remove(999)  #刪除999數字 
print(x)

結果是
array('i', [1, 999, 2, 3, 4, 5, 6, 7])
999
array('i', [1, 2, 3, 4, 5, 6, 7])

=============list 的插入 刪除============

list01=[1,2,3,4,5,6,7]
list01.insert(2,999)
print(list01)
list01.remove(999)
print(list01)

結果
[1, 2, 999, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]

2020年12月21日 星期一

一元三次方程式


import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-5,5,100)
y=x**3-3
plt.plot(x,y)
plt.grid()
plt.show()

2020年12月17日 星期四

二次函數最大值或最小值

#求 f(x)=y=3x**2-12+10 y最小值 x之值
from scipy.optimize import minimize_scalar

def yAns(x):
    yAns=3*x**2 - 12*x + 10
    return yAns
a=3
b=-12
c=10
r = minimize_scalar(yAns)
print(type(r))
print(r)
print(r.x)
print("當x是{:4.2f}時,y的最小值是{:4.2f}".format(r.x,yAns(r.x)))

結果是
<class 'scipy.optimize.optimize.OptimizeResult'>
     fun: -2.0
    nfev: 9
     nit: 4
 success: True
       x: 2.0
2.0
當x是2.00時,y的最小值是-2.00

二次函數(三)

# f(x)=y=-3x**2+12x-9 求y=0 x之解
import numpy as np
from sympy import Symbol,solve
x=Symbol("x")
f=Symbol("f")
f=-3*x**2+12*x-9
ans=solve(f,x)
print(ans)

# f(x)=y=-3x**2+12x-9 畫圖形
import numpy as np
from sympy import Symbol,solve
import matplotlib.pyplot as plt
x=Symbol("x")
f=Symbol("f")
f=-3*x**2+12*x-9
ans=solve(f,x)
print(ans)
def yAns(x):
    y=-3*x**2+12*x-9
    return y
x1=np.linspace(-1,5,100)
y1=yAns(x1)
plt.plot(x1,y1)
plt.grid()
plt.show()

# f(x)=y=-3x**2+12x-9 畫圖及y=0 x之兩點
import numpy as np
from sympy import Symbol,solve
import matplotlib.pyplot as plt
x=Symbol("x")
f=Symbol("f")
f=-3*x**2+12*x-9
ans=solve(f,x)
print(ans)
def yAns(x):
    y=-3*x**2+12*x-9
    return y
x1=np.linspace(-1,5,100)
y1=yAns(x1)
plt.plot(x1,y1)
plt.plot(ans[0],0,"-o")
plt.plot(ans[1],0,"-o")
plt.text(ans[0],-3,"("+str(ans[0])+","+str(0)+")")
plt.text((ans[1]-0.5),-3,"("+str(ans[1])+","+str(0)+")")
plt.grid()
plt.show()

2020年12月16日 星期三

二次函數(二)

#求 f(x)=y=3x**2-12x+10 y=0 x值多少 
import matplotlib.pyplot as plt
import numpy as np
import math
from sympy import Symbol,solve
x1=np.linspace(-6,10,100)
y1=3*x1**2-12*x1+10
plt.plot(x1,y1)
"""
 使用sympy無法求到解
x1=Symbol("x1")
f=Symbol("f")
f=3*x1**2-12*x1+10
ans=solve(f)
print(ans)
"""
#f(x)=y=3x**2-12x+10 a=3 b=-12 c=10
#x=(-b/2a)+math.sqrt(b**2-4ac)/2a
a=3
b=-12
c=10
x1=(-b/(2*a))+(math.sqrt(b**2-4*a*c)/(2*a))
#x1=(-b + (b**2-4*a*c)**0.5)/(2*a)
x2=(-b/(2*a))-(math.sqrt(b**2-4*a*c)/(2*a))
print(x1)
print(x2)
plt.plot(x1,0,"-o")
plt.text(x1,20,"("+str(round(x1,2))+","+str(0)+")")
plt.plot(x2,0,"-o")
plt.text(x2-2,20,"("+str(round(x2,2))+","+str(0)+")")
plt.show()

2020年12月15日 星期二

二次函數(一)

from sympy import Symbol,solve
import numpy as np
x=Symbol("x")
f=Symbol("f")
f=x**2-6*x+8
ans=solve(f)
print(ans)


結果
[2, 4]

print 之 format

math=90
chi=89.5
eng=89.99
print("數學是{}分".format(math))
print("數學是{:3.1f}分".format(math))  #{index: 3.1f}  <==3是資料總長度,1是取自小數點 1位
print("英語是{:3.1f}分".format(eng))
print("英語是{:^10.3f}".format(eng))
print("{}".format(1/3))
print("{:3.1f}".format(1/3))
"""
b - 二進位制
o - 八進位制
d - 十進位制整數
x - 十六進位制
c - 將整數轉 Unicode

"""
print("17的二進制是{:b}".format(17))
print("17的八進制是{:o}".format(17))
print("17的十進制是{:d}".format(17))
print("17的十六進制是{:x}".format(17))
print("{:c}的unicode碼是97".format(97))
print("{:c}的unicode碼是65".format(65))

結果

數學是90分
數學是90.0分
英語是90.0分
英語是  89.990  
0.3333333333333333
0.3
17的二進制是10001
17的八進制是21
17的十進制是17
17的十六進制是11
a的unicode碼是97
A的unicode碼是65

knn 畢式定理在高維空間


原始碼
import math

film = [5, 7, 8, 10, 2]             # 玩命關頭特徵值
film_titles = [                     # 比較影片片名
    '復仇者聯盟',
    '決戰中途島',
    '冰雪奇緣',
    '雙子殺手',
]
film_features = [                   # 比較影片特徵值
    [2, 8, 8, 5, 6],
    [5, 6, 9, 2, 5],
    [8, 2, 0, 0, 10],
    [5, 8, 8, 8, 3],
]

dist = []                           # 儲存影片相似度值
for f in film_features:
    distances = 0
    for i in range(len(f)):
        distances += (film[i] - f[i]) ** 2
    dist.append(math.sqrt(distances))
    
min = min(dist)                     # 求最小值
min_index = dist.index(min)         # 最小值的索引

print("與玩命關頭最相似的電影 : ", film_titles[min_index])
print("相似度值 : ", dist[min_index])
for i in range(len(dist)):
    print("影片 : %s, 相似度 : %6.2f" % (film_titles[i], dist[i]))

基本測試
import math

film = [5, 7, 8, 10, 2]             # 玩命關頭特徵值
film_titles = [                     # 比較影片片名
    '復仇者聯盟',
    '決戰中途島',
    '冰雪奇緣',
    '雙子殺手',
]
film_features = [                   # 比較影片特徵值
    [2, 8, 8, 5, 6],
    [5, 6, 9, 2, 5],
    [8, 2, 0, 0, 10],
    [5, 8, 8, 8, 3],
]
dist=[]
num=0
for f in film_features:
    print("這是file_features[{}]{}".format(num,f))
    num=num+1

計算list[0]的平方和
import math

film = [5, 7, 8, 10, 2]             # 玩命關頭特徵值
film_titles = [                     # 比較影片片名
    '復仇者聯盟',
    '決戰中途島',
    '冰雪奇緣',
    '雙子殺手',
]
film_features = [                   # 比較影片特徵值
    [2, 8, 8, 5, 6],
    [5, 6, 9, 2, 5],
    [8, 2, 0, 0, 10],
    [5, 8, 8, 8, 3],
]
distances=0
for i in range(len(film)):
    distances=distances+(film[i]-film_features[0][i])**2
a_squr=math.sqrt(distances)
print(a_squr)

使用二層迴圈計算
import math

film = [5, 7, 8, 10, 2]             # 玩命關頭特徵值
film_titles = [                     # 比較影片片名
    '復仇者聯盟',
    '決戰中途島',
    '冰雪奇緣',
    '雙子殺手',
]
film_features = [                   # 比較影片特徵值
    [2, 8, 8, 5, 6],
    [5, 6, 9, 2, 5],
    [8, 2, 0, 0, 10],
    [5, 8, 8, 8, 3],
]
dist = []                           # 儲存影片相似度值
for f in film_features:
    distances = 0
    for i in range(len(f)):
        distances += (film[i] - f[i]) ** 2
    dist.append(math.sqrt(distances))
    print(dist)
print(type(dist))
print(type(distances))

解連立方程式(三)

#解方程式x,y 並畫出 L1=x-y,L2=-x-y+2
import matplotlib.pyplot as plt
from sympy import Symbol,solve
impo=rt numpy as np
x=Symbol("x")
y=Symbol("y")
eq1=x-y
eq2=-x-y+2
ans=solve((eq1,eq2))
print(ans)
x1=np.linspace(-20,20,100)
y1=x1
x2=np.linspace(-20,20,100)
y2=-x2+2
plt.plot(x1,y1)
plt.plot(x2,y2)
plt.plot(ans[x],ans[y],"-o")
plt.text(ans[x]-2,ans[y]+4,"("+str(ans[x])+","+str(ans[y])+")")
plt.grid()
plt.axis("equal")
plt.show()

2020年12月13日 星期日

解聯立方程式(二)

 
import matplotlib.pyplot as plt
from sympy import Symbol,solve
import numpy as np
x=Symbol("x")
y=Symbol("y")
eq1=x+y-20
eq2=2*x+4*y-56
ans=solve((eq1,eq2))
print(ans)
print("雞有{}隻".format(ans[x]))
x1=np.linspace(0,31,100)
y1=-x1+20
#print(y1)
y2=(-2*x1+56)/4
plt.plot(x1,y1)
plt.plot(x1,y2)
plt.plot(ans[x],ans[y],"-o")
plt.text(ans[x],ans[y]+2,"("+str(ans[x])+","+str(ans[y])+")")
plt.show()

2020年12月10日 星期四

解連立方程式

#連立方程式 3x+y=5, 4x+2y=12 求x,y值
from sympy import Symbol,solve
a=Symbol("x")
b=Symbol("y")
eq1=3*a+b-5
eq2=4*a+2*b-12
ans=solve((eq1,eq2))
print(ans)

結果 {x: -1, y: 8}
#y=f(x)=ax+b=0.03x-18 x軸0-3000 標示 x=300,y= 點(x,y)標示
import matplotlib.pyplot as plt
import numpy as np
a=0.03
b=-18
x1=300
y1=a*x1+b
plt.plot(x1,y1,"-o")
plt.text(x1+100,y1-4,"f(300)")

x=np.linspace(1,3000,100)
y=a*x+b
plt.plot(x,y)
plt.grid()
plt.show()

2020年12月9日 星期三

python about 方程式

import matplotlib.pyplot as plt
x=[]
y=[]
for i in range(1,11):
    x.append(i)
    y.append(2*i+10)
plt.plot(x,y,"-*")
plt.grid()
plt.axis([-2,16,10,38])
plt.xlabel("children")
plt.ylabel("apples")
plt.show()

也可以寫成
import matplotlib.pyplot as plt
x=[x for x in range(0,10)]
y=[(2*y+10) for y in x]
plt.plot(x,y,"-*")
plt.grid()
plt.xlabel("Xchildren")
plt.ylabel("Yapples")
plt.show()

#y=f(x)=5x+1000 x從1到1000 分成10等份
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(1,1000,10) #x從1到1000 分成10等份
#print(type(x))
y=5*x+1000
plt.plot(x,y,"-*")
plt.grid()
plt.axis([0,1000,1000,6000])
plt.xlabel("number")
plt.xlabel("money")
plt.show()

2020年12月8日 星期二

tkinter 之 title entry button

import tkinter as tk
mainwin=tk.Tk()
vId=tk.StringVar()
mainwin.geometry("400x200")
mainwin.title("銷售系統")

lbe01=tk.Label(mainwin,text="編號")  #label
lbe01.grid(row=0,column=0)

texPid=tk.Entry(mainwin,width=15,textvariable=vId)  #輸入
texPid.grid(row=0,column=1)

btnCreate=tk.Button(mainwin,text="產品新增") #
btnCreate.grid(row=0,column=2)
mainwin.mainloop()

python about json (一)

import json
dict01={"apple":100,"banana":50,"cherry":20}
list01=["apple","banana","cherry"]
tuple01=("apple","banana","cherry")
print("dict01的資料型態是{}".format(type(dict01)))
print(type(list01))
print(type(tuple01))

jasn01=json.dumps(dict01)
jasn02=json.dumps(list01)
jasn03=json.dumps(tuple01)
print("jasn01的資料型態是{}".format(type(jasn01)))
print(type(jasn02))
print(type(jasn03))
print("jasn01的資料是{}".format(jasn01))
print("jasn02的資料是{}".format(jasn02))
print("jasn03的資料是{}".format(jasn03))


結果是
dict01的資料型態是<class 'dict'>
<class 'list'>
<class 'tuple'>
jasn01的資料型態是<class 'str'>
<class 'str'>
<class 'str'>
jasn01的資料是{"apple": 100, "banana": 50, "cherry": 20}
jasn02的資料是["apple", "banana", "cherry"]
jasn03的資料是["apple", "banana", "cherry"]

python about json (一)

import json
dict01={"apple":100,"banana":50,"cherry":20}
list01=["apple","banana","cherry"]
tuple01=("apple","banana","cherry")
print("dict01的資料型態是{}".format(type(dict01)))
print(type(list01))
print(type(tuple01))

jasn01=json.dumps(dict01)
jasn02=json.dumps(list01)
jasn03=json.dumps(tuple01)
print("jasn01的資料型態是{}".format(type(jasn01)))
print(type(jasn02))
print(type(jasn03))
print("jasn01的資料是{}".format(jasn01))
print("jasn02的資料是{}".format(jasn02))
print("jasn03的資料是{}".format(jasn03))

2020年12月7日 星期一

matplotlib(four) 畫圓


#畫圓心(0,0) 半徑為10的圓
import matplotlib.pyplot as plt
import numpy as np
import math
x=[]
y=[]
angle=np.arange(0,360)
for i in angle:
    x.append(10*math.cos(i))
    y.append(10*math.sin(i))
plt.plot(x,y)
plt.axis("equal")
plt.grid()
plt.show()

另一種畫法
#以圓心(10,20)畫圓 半徑3000
import matplotlib.pyplot as plt
import numpy as np
a=10
b=20
r=3000
x1=np.arange(a-r,a+r+1)
y1=np.sqrt(r**2-(x1-a)**2)
# (y1+y2)/2=b ==>y2=2b-y1 y1和y2對稱
y2=2*b-y1
plt.plot(x1,y1)
plt.plot(x1,y2)
plt.grid(color="0.8")
plt.axis("equal")
plt.show()

matplotlib(三) y=x^2


import matplotlib.pyplot as plt
#y=x^2
x=[]
y=[]
for i in range(-8,9):
    x.append(i)
for j in range(-8,9):
    y.append(j*j)
plt.plot(x,y,color="red")
plt.grid(color="0.8")
plt.show()


mathplotlib(二) y=2x-10的圖形


import matplotlib.pyplot as plt
#求 y=2x-10 的圖形
x=[]
y=[]
for i in range(1,11):
   x.append(i)
for i in range(1,11):
   y.append(2*i-10)
plt.plot(x,y,color="red")
plt.grid(color="0.8")
plt.show()
print(x)
print(y)
 

matplotlib(一)


import matplotlib.pyplot as plt
x=[]
y=[]
for i in range(9):
    x.append(i)
for j in range(9):
    y.append(j)
plt.plot(x,y)
plt.grid(color="0.8")
plt.show()

二維陣列(2d array) matrix

import numpy as np fru_items=[["apple","banana","cherry","durian","eggplant","fig...