羅德興老師的教學歷程檔案 - 104-2 資訊技術 - 程式範例下載 |
|
|
程式範例下載1. "雙層 Loop 應用2" # loop2.py 2. # This is double loop by L.D.S on 2016/03/08 print ("雙層 Loop 應用 九九乘法表") 3. 猜數字遊戲 guess2.py 4. GUI 練習 # Getting input using Button # -*- coding: utf-8 -*- """ 註解:此為 Recursive 遞迴呼叫 by L.D.S on 2022/04/03 檔名:recursive3.py 功能:此程式為遞迴呼叫 & 非遞迴呼叫 (Iterative 迭代) 遞迴讓你直覺地表示特定模式經典題型:最大公因數 (GCD)、費波納契數列 (Fibonacci Sequence)、河內塔 (Hanoi Tower)、N 個字元的排列組合。# \t Tab 印出,\n 跳行 印出, end= "" 接續印出 """ import time def fact(n): if (n==1): result= 1 else: result = n*fact(n-1) print(" * " + str(n)) return result def sum_fact(n): total = i = 1 while(i<=n): total *= i print(" * " + str(i)) i+=1 return total n=int(input("請輸入一個數字:")) start = time.time() sum2 = fact(n) print(str(n) + " ! 階層 = " + str(sum2)) end = time.time() print("遞迴呼叫") print(end - start) start = time.time() total2= sum_fact(n) print("%d! 階層 =%d" % (n, total2)) end = time.time() print("非 遞迴呼叫") print(end - start) # -*- coding: utf-8 -*- """ 註解:此為 Recursive 遞迴呼叫 by L.D.S on 2022/04/03 檔名:recursive4.py 功能:此程式為遞迴呼叫 & 非遞迴呼叫 (Iterative 迭代) 遞迴讓你直覺地表示特定模式 經典題型:最大公因數 (GCD)、費波納契數列 (Fibonacci Sequence)、河內塔 (Hanoi Tower)、N 個字元的排列組合。 """ counter=0 def hanoi(n, A, B, C): global counter if n == 1: return [(A, C)] else: return hanoi(n-1, A, C, B) + hanoi(1, A, B, C) + hanoi(n-1, B, A, C) n = input("請輸入整數:") for move in hanoi(int(n), 'A', 'B', 'C'): counter +=1 print("盤由 %c 移至 %c" % move) print("共移動了 " + str(counter) + " 次 盤子") # -*- coding: utf-8 -*- """ 註解:此為 Recursive 非遞迴呼叫 by L.D.S on 2022/04/03 檔名:recursive5.py 功能:此程式為遞迴呼叫 & 非遞迴呼叫 (Iterative 迭代) 遞迴讓你直覺地表示特定模式 經典題型:最大公因數 (GCD)、費波納契數列 (Fibonacci Sequence)、河內塔 (Hanoi Tower)、N 個字元的排列組合。 非遞迴呼叫 (Iterative 迭代)方式 如果函式中只遞迴呼叫自身一次,使用堆疊來模擬遞迴過程的話,基本上需要一個堆疊, 單色河內塔遞迴解會在函式中,呼叫自身兩次,這需要兩個堆疊, 把自己當成電腦來思考的話,就得小心堆疊中狀態的儲存與取出順序,才能正確地解決問題,無疑地,這是個繁瑣的過程, """ counter=0 def hanoi(n, a, b, c): global counter param_stack_recursion2 = [[n, a, b, c]] while param_stack_recursion2: m, pa, pb, pc = param_stack_recursion2.pop() param_stack_recursion1 = [] while True: if m == 1: print("盤由 " + pa +" 搬到 "+ pc) # hanoi(1, A, B, C) counter+=1 # hanoi(m - 1, A, C, B) is completed leng = len(param_stack_recursion2) while param_stack_recursion1: m = m + 1 sa, sb, sc = param_stack_recursion1.pop() # hanoi(m - 1, B, A, C) param_stack_recursion2.insert(leng, [m - 1, sb, sa, sc]) if param_stack_recursion2: _, mb, ma, mc = param_stack_recursion2[-1] print("盤由 " + ma + " 搬到 " + mc) # move A to C counter+=1 break param_stack_recursion1.append([pa, pb, pc]) # hanoi(m - 1, A, C, B) m = m - 1 pa, pb, pc = pa, pc, pb k = input("請輸入整數:") hanoi(int(k), 'A', 'B', 'C') print("共移動了 " + str(counter) + " 次 盤子")
|
|
中華科技大學數位化學習歷程 - 意見反應 |