------------------------------------------------------
------------------------------------愛心
print('\n'.join([''.join([('KuoChinku'[(x-y)%9]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15,-15,-1)]))
------------------------------------愛心
print('\n'.join([''.join([('KuoChinku'[(x-y)%9]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15,-15,-1)]))
=========
------------------------------------------------------
------------------------------------符號3角形
top=9//2
#print(top)
for i in range(0,5):
for j in range(0,9):
if (i==1 and j==top) or (j==top or j==(8-top)) or i==4 :
print(j,end="")
else:
print(" ",end="")
top+=1
print()
== RESTART: F:/python/00.py ==
4
3 5
2 6
1 7
012345678
for x in range(0,13):
for y in range(0,19):
if ((x-6)==3 and y%2==0) or (x-y+3)==-6 or (x+y-15)==-6:
print("*",end="")
else:
print(" ",end="")
print()
for x in range(0,13):
for y in range(0,19):
if ((x-6)==-3 and y%2==0) or (x-y+3)==6 or (x+y-15)==6:
print("*",end="")
else:
print(" ",end="")
print()
#y%2==0 空1格才印
for x in range(0,13):
for y in range(0,19):
if (abs((x-6))==3 and y%2==0) or abs((x-y+3))==6 or abs((x+y-15))==6:
print("*",end="")
else:
print(" ",end="")
print()
for i in range(0,13):
for j in range(0,19):
print(j,end="")
print()
~~~~~~~~
for i in range(0,13):
for j in range(0,19):
if (abs((i-6))==3 and j%2==0) :
print(j,end="")
else:
print(" ",end="")
print()
~~~~~~~~
for i in range(0,13):
for j in range(0,19):
if abs((i+j-15))==6 :
print(j,end="")
else:
print(" ",end="")
print()
~~~~~~~~
for i in range(0,13):
for j in range(0,19):
if abs((i-j-(-3)))==6 :
print(j,end="")
else:
print(" ",end="")
print()
~~~~~~~~
for i in range(0,13):
for j in range(0,19):
#if (abs((i-6))==-3 and j%2==0) or abs((i-j-(-3)))==6 or abs((i+j-15))==6:
if (abs(i-6)==3 and j%2==0) or abs((i-j-(-3)))==6 or abs((i+j-15))==6:
print(j,end="")
else:
print(" ",end="")
print()
~~~~~~~~
for i in range(0,13):
for j in range(0,19):
#if (abs((i-6))==-3 and j%2==0) or abs((i-j-(-3)))==6 or abs((i+j-15))==6:
if (abs(i-6)==3 and j%2==0) or abs((i-j-(-3)))==6 or abs((i+j-15))==6:
print("*",end="")
else:
print(" ",end="")
print()
~~~~~~~~
for i in range(0,13):
for j in range(0,19):
#if (abs((i-6))==-3 and j%2==0) or abs((i-j-(-3)))==6 or abs((i+j-15))==6:
if ((i-6)==3 and j%2==0) or (i-j-(-3))==-6 or (i+j-15)==-6:
print("*",end="")
else:
print(" ",end="")
print()
~~~~~~~~
for i in range(0,13):
for j in range(0,19):
#if (abs((i-6))==-3 and j%2==0) or abs((i-j-(-3)))==6 or abs((i+j-15))==6:
if ((i-6)==-3 and j%2==0) or (i-j-(-3))==6 or (i+j-15)==6:
print("*",end="")
else:
print(" ",end="")
print()
~~~~~~~~
------------------------------------------------------
------------------ Random
>>> import random
>>> for i in range(0,5):
print(random.randint(1,42),end=", ")
1, 8, 3, 29, 36,
>>> dir()
>>> for i in dir(random):
print(i)
>>> help(random.randint)
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
------------------------------------------------------
------------------
>>> for i in range(0,16):
for j in range(0,20):
print(j%10 if j>9 else j,end=" ")
print()
~~~~~~~~
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
------------------------------------------------------
------------------水仙花數
for i in range(100,1000):
if i == (i//100)**3+((i//10)%10)**3+(i%10)**3:
print (i)
~~~~~~~~
153
370
371
407
------------------------------------------------------
------------------ 1-5三角形
for i in range (1,7):
for j in range (1,i):
print(j,end='')
print()
~~~~~~~~
1
12
123
1234
12345
------------------------------------------------------
------------------文字繪製三角形
for i in range(0,5+1):
for j in range(0,i):
if i>2 and j>0 and j<i-1 and i<5:
print(" ",end="")
else:
print("*",end="")
print()
~~~~~~~~
++++++++++++++
for i in range(0,5+1):
for j in range(0,i):
print("*",end="")
print()
~~~~~~~~
++++++++++++++
n=7
mid=((n-1)*2+0)/2
for i in range(0,n):
for j in range(0,2*(n-1)+1):
if (j>=mid-i and j<=mid+i):
print("*",end="")
else:
print(" ",end="")
print()
=========
++++++++++++++
n=7
mid=((n-1)*2+0)/2
for i in range(0,n):
for j in range(0,2*(n-1)+1):
print("*",end="")
print()
=========
------------------------------------------------------
------------------溫度轉換
# 溫度轉換
# 華氏 = 攝氏*(9/5)+32
# 攝氏 = (華氏-32)*5/9
print("1. 華氏轉攝氏")
print("2. 攝氏轉華氏")
s=int(input("請選擇: "))
print(s)
if s==1 :
f = int(input("請輸入華氏: "))
c = (f-32)*5/9
print("華氏",f, "度= 攝氏 ",c, "度")
elif s==2 :
c = int(input("請輸入攝氏: "))
f = c*(9/5)+32
print("攝氏",c, "度= 華氏 ",f, "度")
else :
print("請選擇: 1 或 2 ")
~~~~~~~~
1. 華氏轉攝氏
2. 攝氏轉華氏
請選擇: 2
2
請輸入攝氏: 28
攝氏 28 度= 華氏 82.4 度
------------------------------------------------------
------------------弧度(radian)
單位弧度(radian)定義為圓弧長度(arc length)等於半徑(radius)時的圓心角。角度以弧度給出時,通常不寫弧度單位,或有時記為rad(㎭)。
一個完整的圓的弧度是,所以rad = 360° --> rad = 180°,故 1°=rad、1 rad =
------------------n邊形內角
(180°/n)=(180/n)*(pi/180)=pi/n
A=n*(1/2*(底)*(高))
=n*(1/2*(2*r*sin(pi/n)*(r*cos(pi/n))))
=n*(r^2)*sin(pi/n)*cos(pi/n)
------------------算圓內切正多邊形面積
import math
r=1
n=int(input("計算圓(r=1)內切n邊形面積,n="))
A=n*(r*math.sin(math.pi/n)*math.cos(math.pi/n))
print(A)
~~~~~~~~
計算圓(r=1)內切n邊形面積,n=3
1.2990381056766582
計算圓(r=1)內切n邊形面積,n=4
2.0000000000000004
計算圓(r=1)內切n邊形面積,n=5
2.377641290737884
計算圓(r=1)內切n邊形面積,n=6
2.598076211353316
------------------------------------------------------
------------------Fibonacci(n)
a=0;b=1
for i in range(0,10):
print(a,end=" ")
a,b=b,a+b
~~~~~~~~
0 1 1 2 3 5 8 13 21 34
++++++++++++++
N=int(input("Please enter any integer to find the Fibonacci sequence:"))
LstN=[0,1]
for i in range(2,N+1):
if N==0:print(LstN[0])
if N==1:print(LstN[:1])
LstN.append(LstN[i-2]+LstN[i-1])
print(LstN)
~~~~~~~~
Please enter any integer to find the Fibonacci sequence:10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
++++++++++++++Recursive
def Fibonacci(n):
if n==1 or n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
print("第10項:",Fibonacci(10))
~~~~~~~~
第10項: 55
++++++++++++++Iterative
def Fibonacci(n):
n1=0;n2=1
for i in range(0,n+1):
if(i==0):
nn=0
elif(i==1):
nn=1
else:
nn=n1+n2
n1,n2=n2,nn
print(nn,end=' ,')
Fibonacci(10)
~~~~~~~~
0 ,1 ,1 ,2 ,3 ,5 ,8 ,13 ,21 ,34 ,55 ,
------------------GCD
>>> def GCD(x,y):
if(x<y):x,y=y,x
while(x%y!=0):
mod=x%y
x,y=y,mod
else:
return y
>>> GCD(15,18)
3
++++++++++++++Recursion
>>> def GCD(x,y):
if(x<y):x,y=y,x
mod=x%y
if(mod==0):
return y
else:
return GCD(y,mod)
>>> GCD(15,18)
3
++++++++++++++
def gcd(m, n):
if n == 0:
return m
else:
return gcd(n, m % n)
print(gcd(20, 30)) # 顯示 10
++++++++++++++
# 計算 gcd, lcm
def gcd(m, n): # 最簡潔的 gcd 函數
return m if n == 0 else gcd(n, m % n)
def lcm(m, n):
return m * n // gcd(m, n)
m = 56
n = 24
print(m,"&",n ,"的 GCD= ", gcd(m, n))
print(m,"&",n ,"的 LCM= ", lcm(m, n))
++++++++++++++
# 求GCD (輾轉相除法)
# 可以試 ( x=546 , y=429 ) or (x=9 , y=24 ) or ( x=24 , y=56 )
x=24; y=56
if (x>y):
# 先比較二數,把比較大的數放在 Y 當被除數,x當除數
x,y = y,x
m=x; x=y
while(m>0):
# 每運算過一次以後,就必須把除數 x 換成被除數,餘數當作除數
y=x ; x=m ; m=y % x
print('GCD=',x)
++++++++++++++2個數以上GCD、LCM
def twoGCD(x,y):
if x<y:x,y=y,x
if x%y==0:
return y
else:
return twoGCD(y,x%y)
def moreGCD(x):
tmpG=twoGCD(x[0],x[1])
for i in range (2,len(x)):
tmpG=twoGCD(tmpG,x[i])
return tmpG
#多個數求GCD,兩兩依序找出GCD,最後即所求
def twoLCM(x,y):
return x*y//twoGCD(x,y)
def moreLCM(x):
tmpL=twoLCM(x[0],x[1])
for i in range(2,len(x)):
tmpL=twoLCM(tmpL,x[i])
return tmpL
#多個數求LCM,兩兩依序找出LCM,最後即所求
InputStr=input("<Space>隔開、<Enter>離開。\n最後一碼控制符:\n1:求LCM\n2:求GCD\n3:皆要。\n請輸入任意個整數串列:")
Lst=[]
Lst=[int(i) for i in InputStr.split(' ')]
#Lst=[12, 15, 18, 2]
if Lst[-1]==1:
print("LCM:",moreLCM(Lst[:-1]))
elif Lst[-1]==2:
print("GCD:",moreGCD(Lst[:-1]))
#自己測試用
else:
print("LCM:",moreLCM(Lst[:-1]))
print("GCD:",moreGCD(Lst[:-1]))
~~~~~~~~
<Space>隔開、<Enter>離開。
最後一碼控制符:
1:求LCM
2:求GCD
3:皆要。
請輸入任意個整數串列:12 15 18 3
LCM: 180
GCD: 3
------------------------------------------------------
------------------猜數字
ans = 35 # 猜數字的解答
for guessChance in range(0,5):
guess = int(input("Please input a number (1~100):"))
#二行合併, 單引號改雙引號
if ans == guess:
print ('答對了')
break # 猜對後跳出 for 迴圈
else:
if ans>guess:
print('猜錯了,太小。')
else:
print('猜錯了,太大。')
print('遊戲 結束')
~~~~~~~~
Please input a number (1~100):50
猜錯了,太大。
Please input a number (1~100):25
猜錯了,太小。
Please input a number (1~100):35
答對了
遊戲 結束
------------------------------------------------------
------------------巴斯卡三角形 Pascal's triangle
Dict={}
def Pascal(row,col):
index=(row,col)
if index in Dict: return Dict[index]
if col==0: return 1
if col==row: return 1
upL=Pascal(row-1,col-1)
upR=Pascal(row-1,col)
Dict[index]=upL+upR
return upL+upR
for r in range(0,4+1):
for c in range(0,r+1):
print(Pascal(r,c),end=" ")
print(Dict)
print()
~~~~~~~~
1 {}
1 1 {}
1 2 1 {(2, 1): 2}
1 3 3 1 {(2, 1): 2, (3, 1): 3, (3, 2): 3}
1 4 6 4 1 {(2, 1): 2, (3, 1): 3, (3, 2): 3, (4, 1): 4, (4, 2): 6, (4, 3): 4}
++++++++++++++
n=int(input("輸出幾層:"))
Lst=[1]
for i in range(0,n):
print(Lst)
tmpLst=[]
tmpLst.append(Lst[0])
for i in range(len(Lst)-1):
tmpLst.append(Lst[i]+Lst[i+1])
#print(tmpLst)
#Lst[-1],Lst的最後一項
tmpLst.append(Lst[-1])
Lst=tmpLst
~~~~~~~~
輸出幾層:5
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
++++++++++++++
#預設有第1層
Lst=[[1]]
#輸出6層
for i in range(1,6+1):
#新增層的模型
Pattern=[1,1]
for j in range(0,i-1):
Pattern.insert(j+1,sub[j]+sub[j+1])
#sub元素加總,給下一層
sub=Pattern
Lst.append(sub)
for i in Lst:
print(i)
~~~~~~~~
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
++++++++++++++
n=4
Lst=[]
for i in range(0,n+1):
print("i=",i)
tmp=[]
for j in range(0,i+1):
print("j=",j)
if j==0 or j==i:
tmp.append(1)
else:
tmp.insert(j+1,Lst[i-1][j-1]+Lst[i-1][j])
print("tmp=",tmp)
print()
Lst.append(tmp)
print("FinalResult=",Lst)
=========
i= 0
j= 0
tmp= [1]
i= 1
j= 0
tmp= [1]
j= 1
tmp= [1, 1]
i= 2
j= 0
tmp= [1]
j= 1
tmp= [1, 2]
j= 2
tmp= [1, 2, 1]
i= 3
j= 0
tmp= [1]
j= 1
tmp= [1, 3]
j= 2
tmp= [1, 3, 3]
j= 3
tmp= [1, 3, 3, 1]
i= 4
j= 0
tmp= [1]
j= 1
tmp= [1, 4]
j= 2
tmp= [1, 4, 6]
j= 3
tmp= [1, 4, 6, 4]
j= 4
tmp= [1, 4, 6, 4, 1]
FinalResult= [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
------------------------------------------------------
------------------十進制轉其他進制
def numsys(dec,ns):
n=dec
x=''
hstr='0123456789ABCDEF'
if ( n == 0 ) :
x='0'
while ( n > 0 ):
# 要取n % 16的餘數,這個字元在hst字串的第(餘數)的位置的字元
x=hstr[(n % ns):(n % ns)+1]+x
# if ns==2:
# print("n=",n,"x=",x)
n= n//ns
return x
dec = 18
print("十進制:",dec,":")
print("二進制=",numsys(dec,2))
print("八進制=",numsys(dec,8))
print("十六進制=",numsys(dec,16))
~~~~~~~~
十進制: 18 :
二進制= 10010
八進制= 22
十六進制= 12
++++++++++++++
#十進制轉其他進制
dec = 26
print("十進制:",dec)
# 轉二進制
n=dec
b=''
if ( n== 0) :
b=str(n)
while ( n > 0) :
b=str(n%2)+b
n= n//2
print("二進制=",b)
# 轉八進制
n=dec
o=''
if ( n<8) :
o=str(n)
while ( n >7) :
o=str(n%8)+o
n= n//8
if ( n<8) :
o=str(n)+o
print("八進制=",o)
# 轉十六進制
n=dec
x=''
hex='0123456789ABCDE'
if ( n<15) :
x=str(n)
while ( n >15) :
x=hex[(n%16):(n%16)+1]+x # 要取 n % 16 的餘數,這個字元在 hex 字串的第(餘數)的位置的字元
n= n//16
if ( n<16) :
x=hex[(n%16):(n%16)+1]+x
print("十六進制=",x)
~~~~~~~~
十進制: 26
二進制= 11010
八進制= 32
十六進制= 1A
------------------------------------------------------
------------------數字方陣
n=4
for i in range(-n,n+1):
for j in range(-n, n+1):
if ( abs(i) > abs(j)) :
print(abs(i)+1,end='')
else:
print(abs(j)+1,end='')
print()
print('\n')
~~~~~~~~
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
------------------------------------------------------
------------------畫國旗
import turtle #引進turtle函式庫
turtle.speed(10) #設定畫筆速度
#定義畫長方形的方法
def rectangle(x,y,leng,wid,color):
#定義"rectangle"函式有五個變數輸入,xy是起點座標,leng跟wid是長跟寬,
#color是顏色
turtle.color(color) #設定顏色為參數傳入的顏色
turtle.penup() #畫筆拿起來
turtle.goto(x,y) #移動到起點位置x,y
turtle.down() #下筆開始畫
turtle.begin_fill() #開始填滿
turtle.forward(leng) #前進leng的長度
turtle.right(90) #右轉90度
turtle.forward(wid) #前進wid的長度
turtle.right(90) #右轉90度
turtle.forward(leng) #前進leng的長度
turtle.right(90) #右轉90度
turtle.forward(wid) #前進wid的長度
turtle.right(90) #右轉90度
turtle.end_fill() #結束填滿
rectangle(-200,200,600,400,'red')
#從(-200,200)開始畫一個長600寬400,紅色的長方形
rectangle(-200,200,300,200,'blue')
#從(-200,200)開始畫一個長300寬200,藍色的長方形
#定義畫太陽的方法
import turtle #引進turtle函式庫
turtle.speed(10) #設定畫筆速度
def sun(x,y,length,color):
#定義 "sun" 函式,有四個輸入,x,y是起點座標,length是長度,color是顏色turtle.up() #筆拿起來
turtle.color('white')
turtle.goto(x,y) #移動到(x,y)
turtle.setheading(345) #面向345度的方向
turtle.down() #下筆開始畫
turtle.begin_fill() #開始填滿
counter=0 #計數器=0
while True: #無線迴圈
turtle.forward(length) #往前length的距離
turtle.left(150) #左轉150度
counter+=1 #計數器+1
if counter>=12: #如果計數器大於或等於12
break #就跳出迴圈
turtle.end_fill() #結束填滿
turtle.color('blue') #藍色
turtle.goto(-104,100) #設定起點座標
turtle.setheading(270) #面向270度方向
turtle.down() #下筆
turtle.pensize(10) #筆的粗細調成10
turtle.circle(44) #畫一個半徑44的圓
turtle.up() #筆拿起來
sun(-150,100,175,'white') #從(-150,100)開始畫一個175大小的白色太陽turtle.up() #筆拿起來
#畫圓
~~~~~~~~
------------------------------------------------------
------------------字元的排列組合 Permutations
# 自訂函數
def perm(Lst, k=0):
if k == len(Lst):
print (Lst)
else:
for i in range(k, len(Lst)):
Lst[k], Lst[i] = Lst[i] ,Lst[k]
#print("i=",i,Lst)
perm(Lst, k+1)
Lst[k], Lst[i] = Lst[i], Lst[k]
perm(['a','b','c'])
perm([1,2,3])
~~~~~~~~
['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'b', 'a']
['c', 'a', 'b']
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
++++++++++++++
import itertools
Lst=['a','b','c']
perm=itertools.permutations(Lst)
for i in perm:
print(type(i),i)
~~~~~~~~
<class 'tuple'> ('a', 'b', 'c')
<class 'tuple'> ('a', 'c', 'b')
<class 'tuple'> ('b', 'a', 'c')
<class 'tuple'> ('b', 'c', 'a')
<class 'tuple'> ('c', 'a', 'b')
<class 'tuple'> ('c', 'b', 'a')
++++++++++++++
import itertools
str="ABC"
perm=itertools.permutations(str)
for i in perm:
print(type(i),i)
~~~~~~~~
<class 'tuple'> ('A', 'B', 'C')
<class 'tuple'> ('A', 'C', 'B')
<class 'tuple'> ('B', 'A', 'C')
<class 'tuple'> ('B', 'C', 'A')
<class 'tuple'> ('C', 'A', 'B')
<class 'tuple'> ('C', 'B', 'A')
++++++++++++++
import itertools
str="ABC"
perm=itertools.permutations(str)
#for i in perm:
# print(type(i),i)
for j in list(perm):
print(type(" ".join(j))," ".join(j))
~~~~~~~~
<class 'str'> A B C
<class 'str'> A C B
<class 'str'> B A C
<class 'str'> B C A
<class 'str'> C A B
<class 'str'> C B A
++++++++++++++
str1="ABC"
for i in str1:
for j in str1:
for k in str1:
if not(i==j or i==k or j==k):
print(i,j,k)
print()
=========
A B C
A C B
B A C
B C A
C A B
C B A
++++++++++++++
def permuation(Lst,tmp):
#tmp 與 Lst 長度一樣,表這回已完成,印出
if len(tmp)==len(Lst):
# print(tmp)
pass
for i in range(len(Lst)):
#tmp 已有相同元素,跳過
if Lst[i] in tmp:
continue
#tmp 沒有的元素,加入
tmp.append(Lst[i])
#利用遞迴從 Lst 把元素加入 tmp
permuation(Lst,tmp)
print("這回目前結果:",tmp)
tmp.pop()
print("回到每個遞迴點,依次拿掉一個元素:",tmp)
Lst=["A","B","C"]
permuation(Lst,[])
=========
這回目前結果: ['A', 'B', 'C']
回到每個遞迴點,依次拿掉一個元素: ['A', 'B']
這回目前結果: ['A', 'B']
回到每個遞迴點,依次拿掉一個元素: ['A']
這回目前結果: ['A', 'C', 'B']
回到每個遞迴點,依次拿掉一個元素: ['A', 'C']
這回目前結果: ['A', 'C']
回到每個遞迴點,依次拿掉一個元素: ['A']
這回目前結果: ['A']
回到每個遞迴點,依次拿掉一個元素: []
這回目前結果: ['B', 'A', 'C']
回到每個遞迴點,依次拿掉一個元素: ['B', 'A']
這回目前結果: ['B', 'A']
回到每個遞迴點,依次拿掉一個元素: ['B']
這回目前結果: ['B', 'C', 'A']
回到每個遞迴點,依次拿掉一個元素: ['B', 'C']
這回目前結果: ['B', 'C']
回到每個遞迴點,依次拿掉一個元素: ['B']
這回目前結果: ['B']
回到每個遞迴點,依次拿掉一個元素: []
這回目前結果: ['C', 'A', 'B']
回到每個遞迴點,依次拿掉一個元素: ['C', 'A']
這回目前結果: ['C', 'A']
回到每個遞迴點,依次拿掉一個元素: ['C']
這回目前結果: ['C', 'B', 'A']
回到每個遞迴點,依次拿掉一個元素: ['C', 'B']
這回目前結果: ['C', 'B']
回到每個遞迴點,依次拿掉一個元素: ['C']
這回目前結果: ['C']
回到每個遞迴點,依次拿掉一個元素: []
++++++++++++++
def permuation(Lst,tmp):
#tmp 與 Lst 長度一樣,表這回已完成,印出
if len(tmp)==len(Lst):
print(tmp)
for i in range(len(Lst)):
#tmp 已有相同元素,跳過
if Lst[i] in tmp:
continue
#tmp 沒有的元素,加入
tmp.append(Lst[i])
#利用遞迴從 Lst 把元素加入 tmp
permuation(Lst,tmp)
tmp.pop()
Lst=["A","B","C"]
permuation(Lst,[])
=========
['A', 'B', 'C']
['A', 'C', 'B']
['B', 'A', 'C']
['B', 'C', 'A']
['C', 'A', 'B']
['C', 'B', 'A']
++++++++++++++
cnt=0
def perm(Lst):
global cnt
cnt+=1
print("Recur",cnt,"次")
if len(Lst)==0:
return []
elif len(Lst)==1:
return Lst
else:
tmp=[]
for i in range(len(Lst)):
print("i=",Lst[i])
x=Lst[i]
y=Lst[:i]+Lst[i+1:]
print("x=",x,"y=",y)
for j in perm(y):
tmp.append(x+j)
print(cnt,"次","tmp=",tmp)
print()
print()
return tmp
data=list("ABC")
print(perm(data))
==========
Recur 1 次
i= A
x= A y= ['B', 'C']
Recur 2 次
i= B
x= B y= ['C']
Recur 3 次
3 次 tmp= ['BC']
i= C
x= C y= ['B']
Recur 4 次
4 次 tmp= ['BC', 'CB']
4 次 tmp= ['ABC']
4 次 tmp= ['ABC', 'ACB']
i= B
x= B y= ['A', 'C']
Recur 5 次
i= A
x= A y= ['C']
Recur 6 次
6 次 tmp= ['AC']
i= C
x= C y= ['A']
Recur 7 次
7 次 tmp= ['AC', 'CA']
7 次 tmp= ['ABC', 'ACB', 'BAC']
7 次 tmp= ['ABC', 'ACB', 'BAC', 'BCA']
i= C
x= C y= ['A', 'B']
Recur 8 次
i= A
x= A y= ['B']
Recur 9 次
9 次 tmp= ['AB']
i= B
x= B y= ['A']
Recur 10 次
10 次 tmp= ['AB', 'BA']
10 次 tmp= ['ABC', 'ACB', 'BAC', 'BCA', 'CAB']
10 次 tmp= ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
------------------------------------------------------
------------------河內塔
def hanoi(n,source,tmp,target):
if n>0:
hanoi(n-1,source,target,tmp)
print("dish{0:2d}: {1:1s} ==> {2:1s}".format(n,source,target))
hanoi(n-1,tmp,source,target)
hanoi(3,"A","B","C")
~~~~~~~~
dish 1: A ==> C
dish 2: A ==> B
dish 1: C ==> B
dish 3: A ==> C
dish 1: B ==> A
dish 2: B ==> C
dish 1: A ==> C
++++++++++++++
------------------------------------------------------
------------------
import itertools
#1~9 數字不能重複
for i in itertools.permutations(range(1,9+1),9):
if i[0]==6 or i[0]==7:
n1=i[0]*10000+i[1]*1000+i[2]*100+i[3]*10+i[4]*1
n2=i[5]*1000+i[6]*100+i[7]*10+i[8]*1
if (n1-n2)==66666:
print(n1,"-",n2,"= 66666")
=========
69153 - 2487 = 66666
69513 - 2847 = 66666
71358 - 4692 = 66666
71529 - 4863 = 66666
71934 - 5268 = 66666
73158 - 6492 = 66666
73194 - 6528 = 66666
73491 - 6825 = 66666
74931 - 8265 = 66666
75129 - 8463 = 66666
------------------------------------------------------
------------------遞迴算總和
def kksum(n):
print(n,end=" ")
if (n==0):
return 0
else:
#fac(n)=1+2+3+...+(n-1)+n
return kksum(n-1)+n
print("\n合計=",kksum(10))
=========
10 9 8 7 6 5 4 3 2 1 0
合計= 55
++++++++++++++
def fac(n):
if n==0 or n==1:
return 1
else:
#fac(n)=1*2*3*...*(n-1)*n
return fac(n-1)*n
print(fac(5))
=========
120
++++++++++++++
def exponent(a,n):
if n==0:
return 1
else:
#exponent(a,n)=a*a*a*...*a*a
return exponent(a,n-1)*a
print(exponent(2,10))
=========
1024
------------------------------------------------------
------------------Letter Combinations of a Phone Number
digit_map={
2:"abc",
3:"def",
4:"ghi",
5:"jkl",
6:"mno",
7:"pqrs",
8:"tuv",
9:"wxyz"
}
result=[""]
digits=["2","3"]
for i in digits:
print("i=",i)
tmp_list=[]
for ch in digit_map[int(i)]:
for str in result:
tmp_list.append(str+ch)
print("ch=",ch,"str=",str,"tmp_list",tmp_list,"result=",result)
result=tmp_list
print("\nFinal_result=",result)
print()
print(result)
=========
i= 2
ch= a str= tmp_list ['a'] result= ['']
ch= b str= tmp_list ['a', 'b'] result= ['']
ch= c str= tmp_list ['a', 'b', 'c'] result= ['']
Final_result= ['a', 'b', 'c']
i= 3
ch= d str= a tmp_list ['ad'] result= ['a', 'b', 'c']
ch= d str= b tmp_list ['ad', 'bd'] result= ['a', 'b', 'c']
ch= d str= c tmp_list ['ad', 'bd', 'cd'] result= ['a', 'b', 'c']
ch= e str= a tmp_list ['ad', 'bd', 'cd', 'ae'] result= ['a', 'b', 'c']
ch= e str= b tmp_list ['ad', 'bd', 'cd', 'ae', 'be'] result= ['a', 'b', 'c']
ch= e str= c tmp_list ['ad', 'bd', 'cd', 'ae', 'be', 'ce'] result= ['a', 'b', 'c']
ch= f str= a tmp_list ['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af'] result= ['a', 'b', 'c']
ch= f str= b tmp_list ['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf'] result= ['a', 'b', 'c']
ch= f str= c tmp_list ['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf', 'cf'] result= ['a', 'b', 'c']
Final_result= ['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf', 'cf']
['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf', 'cf']
------------------------------------------------------
------------------
res=[];Recsv=0
def DFS(Lst,tmp,i):
global Recsv
Recsv+=1
print("Recursive=",Recsv)
res.append(tmp[:])
print("目前結果=",res)
for i in range(i,len(Lst)):
#print("i=",i)
tmp.append(Lst[i])
print("Level=",i+1,"節點=",tmp)
print()
DFS(Lst,tmp,i+1)
tmp.pop()
DFS([1,2],[],0)
for i in res:
print(i)
=========
Recursive= 1
目前結果= [[]]
Level= 1 節點= [1]
Recursive= 2
目前結果= [[], [1]]
Level= 2 節點= [1, 2]
Recursive= 3
目前結果= [[], [1], [1, 2]]
Level= 2 節點= [2]
Recursive= 4
目前結果= [[], [1], [1, 2], [2]]
[]
[1]
[1, 2]
[2]
------------------------------------------------------
------------------Combinations
def combine(n,k):
output=[]
stack=[]
i=1
length=0
while True:
print("i=",i," n=",n," k=",k," length=",length,"(n-k+length+1)=",n-k+length+1)
if length==k:
output.append(stack[:])
print("kk=",output)
if length==k or i>(n-k+length+1):
if length==0:
print("0-output=",output)
return output
i=stack.pop()+1
length-=1
print("i=",i," length=",length)
print("00--output=",output)
print("00--stack=",stack)
else:
stack.append(i)
i+=1
length +=1
print("11--stack=",stack)
print()
print("\nFinalResult:",combine(3,2))
=========
i= 1 n= 3 k= 2 length= 0 (n-k+length+1)= 2
11--stack= [1]
i= 2 n= 3 k= 2 length= 1 (n-k+length+1)= 3
11--stack= [1, 2]
i= 3 n= 3 k= 2 length= 2 (n-k+length+1)= 4
kk= [[1, 2]]
i= 3 length= 1
00--output= [[1, 2]]
00--stack= [1]
i= 3 n= 3 k= 2 length= 1 (n-k+length+1)= 3
11--stack= [1, 3]
i= 4 n= 3 k= 2 length= 2 (n-k+length+1)= 4
kk= [[1, 2], [1, 3]]
i= 4 length= 1
00--output= [[1, 2], [1, 3]]
00--stack= [1]
i= 4 n= 3 k= 2 length= 1 (n-k+length+1)= 3
i= 2 length= 0
00--output= [[1, 2], [1, 3]]
00--stack= []
i= 2 n= 3 k= 2 length= 0 (n-k+length+1)= 2
11--stack= [2]
i= 3 n= 3 k= 2 length= 1 (n-k+length+1)= 3
11--stack= [2, 3]
i= 4 n= 3 k= 2 length= 2 (n-k+length+1)= 4
kk= [[1, 2], [1, 3], [2, 3]]
i= 4 length= 1
00--output= [[1, 2], [1, 3], [2, 3]]
00--stack= [2]
i= 4 n= 3 k= 2 length= 1 (n-k+length+1)= 3
i= 3 length= 0
00--output= [[1, 2], [1, 3], [2, 3]]
00--stack= []
i= 3 n= 3 k= 2 length= 0 (n-k+length+1)= 2
0-output= [[1, 2], [1, 3], [2, 3]]
FinalResult: [[1, 2], [1, 3], [2, 3]]
------------------------------------------------------
------------------
------------------------------------------------------
------------------
------------------------------------------------------
------------------
------------------------------------------------------
------------------
沒有留言:
張貼留言