# Python Repositories :::info ## Table of Contents [TOC] --- 專案連結: [Github](https://github.com/iamsydney/Python-Repo) ::: ## 競程熱門題目 ### 費波那契數 - **說明**: 費波那契數(義大利語:Successione di Fibonacci),又譯為菲波拿契數、菲波那西數、斐氏數、黃金分割數。所形成的數列稱為費波那契數列(義大利語:Successione di Fibonacci),又譯為菲波拿契數列、菲波那西數列、斐氏數列、黃金分割數列。這個數列是由義大利數學家費波那契在他的《算盤書》中提出。 在數學上,費波那契數是以遞迴的方法來定義: ``` F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2 ( n >= 2 ) ``` - **程式碼**: ```python= a = [1, 1] def fab(n): if n == 0: return 0 if len(a) <= n: a.append(fab(n-1)+fab(n-2)) a.sort() return a[len(a)-1] return a[n] while(True): i = int(input("Your Fibonacci number(-1 to break)\n> ")) if i == -1: print("Good Bye :D") break print(fab(i)) ``` <br> ### 最大公因數 - **說明** 最大公因數(英語:highest common factor,hcf)也稱最大公約數(英語:greatest common divisor,gcd)是數學詞彙,指能夠整除多個整數的最大正整數。而多個整數不能都為零。例如8和12的最大公因數為4。 整數序列a的最大公因數可以記為`( a1, a2, ..., an )`或 `gcd( a1, a2, ..., an )` - **程式碼**: ```python= p = int(input("Input the FIRST number:\n> ")) q = int(input("Input the SECOND number:\n> ")) def GCD(a, b): tmp = a % b if not tmp: if b == 1: return f"GCD({a}, {b}) = PRIME." return f"GCD({p}, {q}) = {b}" else: return GCD(b, tmp) print(GCD(p, q)) ``` <br> ### 阿姆斯特朗數 - **說明**: 在數論中,水仙花數(Narcissistic number),也被稱為超完全數字不變數(pluperfect digital invariant, PPDI)、自戀數、自冪數、阿姆斯壯數或阿姆斯特朗數(Armstrong number),用來描述一個N位非負整數,其各位數字的N次方和等於該數本身。 - **程式碼**: ```python= n, m = map(int,input('Input a range to check armstrong number?\n> ').split()) lis = [] for i in range(n, m+1): total = 0 for x in str(i): total += int(x) ** len(str(i)) if total == i: lis.append(int(i)) # 空集合(X if not len(lis): print('There are no armstrong number between this range "(', end = '') # print armstrong list in range else: print('These number are armstrong number between this range\n> ', end = '') for i in lis: print(i, end = '') if i is not lis[-1]: print(', ', end = '') print() ``` <br> ### 美麗數 - **說明**: 當質因數乘積與原數值相等時,則此數稱之為美麗數;反之,則稱之為醜數。 - **程式碼**: ```python= import math num = int(input('Is this number beautiful?\n> ')) total = 1 for x in range(2, int(math.sqrt(num))+2): if not num % x: total *= x if total == num: print(f'{num} is beautiful.') else: print(f'{num} is ugly.') ``` <br> ### 排序與搜尋 - **說明**: 最簡單取發展極為廣泛的問題。排序演算法可用在處理文字資料以及產生人類可讀的輸出結果;而搜尋演算法則可方便找尋出所需要的結果。 - **程式碼**: ```python= # global val={} # sort func_ def sort(): for x in range(int(len(val))-1): for y in range(x+1,int(len(val))): # print(y) if val[x]>val[y]: tmp=val[x] val[x]=val[y] val[y]=tmp print(val) #search func_ def search(g, l, r): mid=int((l+r)/2) if l>r: print('err0r') return elif val[mid] is g: print(f'index:{mid}') return elif val[mid]<g: search(g, mid+1, r) else: search(g, l, mid-1) # main n=int(input('input how many numbers in the array?\n> ')) print('input') for i in range(n): val[i]=int(input(f'{i+1}. ')) sort() m=int(input('input how many numbers need to search?\n> ')) print('input') for i in range(m): tmp=int(input(f'{m}. ')) search(tmp, 0, int(len(val))-1) ``` <br> ### 質數 - **說明**: 質數(Prime number),又稱素數,指在大於1的自然數中,除了1和該數自身外,無法被其他自然數整除的數(也可定義為只有1與該數本身兩個正因數的數)。 是密碼學主要研究的題目,目前較無實際解法能夠輕鬆解決質數相關問題,只能利用相對窮舉或建立質數表的方式解決。 - **程式碼**: ```python= import math inp = int(input('Is this prime?\n> ')) isPrime=True for i in range(2, int(math.sqrt(inp))+1): if inp % i == 0: isPrime=False break print(f'{inp} == prime is {isPrime}') ``` <br> ### 階乘 - **說明**: 在數學中,正整數的階乘(英語:Factorial)是所有小於等於該數的正整數的積,計為`n!` 階乘應用在許多數學領域中,最常應用在組合學、代數學和數學分析中。在組合學中,階乘代表的意義為`n`個相異物件任意排列的數量;`n`的階乘又可以稱為n的排列數。 - **程式碼**: ```python= a = [1] def stage(n): if n == 0: return 1 if len(a) <= n: a.append(n*stage(n-1)) a.sort() return a[len(a)-1] return a[n] while(True): i = int(input("Your stage number(-1 to break)\n> ")) if i == -1: print("Good Bye :D") break print(stage(i)) ``` <br> ## 小專案 ### qrcode產生器 - **程式碼**: ```python= from qrcode import QRCode from qrcode.constants import ERROR_CORRECT_L from qrcode.image.styledpil import StyledPilImage from qrcode.image.styles.moduledrawers import RoundedModuleDrawer from qrcode.image.styles.colormasks import SolidFillColorMask from datetime import datetime import cv2 def hex2rgb(code): code = code.lstrip("#") return tuple(int(code[i:i+2], 16) for i in (0, 2, 4)) dt = datetime.now().strftime("%Y%m%d %H-%M-%S") qr = QRCode( version=1, error_correction=ERROR_CORRECT_L, box_size=10, border=4 ) input_data = input("Input the url...\n> ") backgrd_code = hex2rgb(input("Input the backgrd RGB...\n> ")) code_code = hex2rgb(input("Input the code RGB...\n> ")) # print(f"backgrd_code:{backgrd_code}, code_code:{code_code}") qr.add_data(input_data) qr.make(fit=True) img = qr.make_image(image_factory=StyledPilImage, color_mask = SolidFillColorMask(backgrd_code, code_code), module_drawer = RoundedModuleDrawer()) img.save(f"{dt}_output.png") print("img saved.") img = cv2.imread(f"{dt}_output.png") cv2.imshow(f"{dt}_output", img) ``` <br> ### 猜數字遊戲 - **程式碼**: 一般版: ```python= from random import random, randrange from math import sqrt def guess(): # 目標數字 global goal, inp, times goal = int(random()*randrange(2, 10)**randrange(2, 10)) # 輸入上標值 top = int(input("請輸入上限值")) # 調整目標數字 while goal > top: goal = int(goal%top) **2 # 起始值設置 inp = -1 times = 1 # 猜數字 while times <= int(sqrt(top)): inp = input("Guess a number") if inp == goal: break print(f"Ur Wrong! you have {int(sqrt(top)) - times} time(s) left :)") times += 1 guess() # 判斷 if inp == goal: print(f"Congraduation ! The number is {goal}.") print(f"You make a good job making {times} times to get the number.") else: print(f"The number is {goal}. Try it again :)") guess() ``` 優化版: ```python= from random import random, randrange, randint from math import log from asyncio import run # 隨機生成上限值目標書字 async def gen_goal(): global top, goal top = int(10**random()+randint(randrange(100, 500), randrange(1000, 1500))%1000) goal = int(10**random()+randint(randrange(100, 500), randrange(1000, 1500))) while goal > top: goal = int(goal%top) # 數字猜測判斷與回應 async def guess(): global times, inp, max_times, l_range, r_range if l_range > inp or r_range < inp: return 400 if inp == goal: return 200 elif inp > goal: r_range = inp print(f"The goal is lower than {inp}...") print(f"You have {max_times - times} times left.") return 404 elif inp < goal: l_range = inp print(f"The goal is higher than {inp}...") print(f"You have {max_times - times} times left.") return 404 # 主程式 if __name__ == "__main__": run(gen_goal()) global times, inp, max_times, l_range, r_range, waste l_range = 1 r_range = top times = 1 waste = 0 max_times = int(log(top, 2))+1 print(f"You have {max_times} times to reach the goal number :D") # 次數內重複猜測&判斷 while times <= max_times: inp = int(input(f"Guess a number between {l_range} ~ {r_range}\n> ")) response = run(guess()) if response == 200: print(f"Congraduation ! The goal number is {goal}.") print(f"You make a good job making {times} times to get the number.") print(f"(include {waste} waste times)") quit() elif response == 400: waste += 1 print(f"You waste one chance to reach the goal :(") print(f"You have {max_times - times} times left.") times +=1 print(f"Ohhh... The goal is {goal}.") print(f"You spend {times-1} times to guess the number. Try it again.") print(f"(include {waste} waste times)") ``` <br> ### 溫度轉換器 - **程式碼**: ```python= temperature= input(('Input the temperature (included °C or °F or K)\n> ')) temperature= temperature.split(' ') temperature[1]= temperature[1].lower() if temperature[1] == '°c': # print('C') temperature.insert(2, round(int(temperature[0]))) elif temperature[1] == '°k': # print('F') temperature.insert(2, round((int(temperature[0])-32)*5/9)) elif temperature[1] == 'k': # print('K') temperature.insert(2, round(int(temperature[0])-273.15)) else: print('3rr0r') temperature.insert(3, round(temperature[2]*9/5+32)) temperature.insert(4, round(temperature[2]+273.15)) ``` <br>