2025年5月23日 星期五

python timedelta

 import datetime

y,m,d = map(int,input().split())

d1 =datetime.date(y, m, d)

d2 = d1 + datetime.timedelta(days=280)

print(d2.year,d2.month,d2.day)

中文數字

 r = '零一二三四五六七八九'

a = ['萬','千','百','十','萬','千','百','十','']

rn = '0123456789'


n = int(input())

d = [r[rn.find(str(i))] for i in str(n)]

d = ''.join(d)


s = ''

i,k = len(d)-1,len(a)-1 

while i>=0:

s =  d[i] + a[k] + s

i = i -1

k = k - 1


s = s.replace('零十','零')

s = s.replace('零百','零')

s = s.replace('零千','零')

s = s.replace('零萬','零')

while s.find('零零')>0:s = s.replace('零零','零')

if s=='零':

print(s,end='')

elif s[-1]=='零':

print(s[:-1],end='')

else:

print(s,end='')

2025年5月22日 星期四

小於N的質數個數

 #小於N的質數個數

while True:

try:

n = int(input())

d = list(range(n))

d[1]=0

for i in range(2,int(n**0.5)+1):

  for j in range(i**2,n,i):

    d[j]=0

d1 = [ i for i in d if i!=0]

print(len(d1))

except:

break


2025年5月21日 星期三

merge sort

 def mgsort(d):

  if len(d)<=1:return d

  n = len(d)//2

  left = mgsort(d[:n])

  right = mgsort(d[n:])

  return merge(left,right)


def merge(left,right):

  i,j = 0,0

  result = []

  while i<len(left) and j<len(right):

    if left[i]<right[j]:

      result.append(left[i])

      i+=1

    else:

      result.append(right[j])

      j+=1

  result.extend(left[i:])

  result.extend(right[j:])

  return result

  


d = [int(i) for i in input().split()]

n = len(d)

print(mgsort(d))


data:

1 2 10 9 8 3 5 4 7 6


Output:


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2025年5月17日 星期六

象棋比大小

 r = '將帥士仕象相車俥馬傌包炮卒兵'


while True:

try:

d = [i for i in input().split()]

isDateRight = True

for i in d[:5]:

if i in '帥仕相俥傌炮兵':

isDateRight = False

break

if not isDateRight:

d =d[5:] + d[:5]

d = [r[::-1].find(i) for i in d]

d = [i if i%2==0 else i-1 for i in d ]

d1 = d[:5]

d2 = d[5:]

d1.sort()

d1.reverse()

d2.sort()

d2.reverse()


msg = '紅黑平手'

for i in range(5):

if d1[i]>d2[i]:

msg = '黑方勝出'

break

elif d1[i]<d2[i]:

msg = '紅方勝出'

break

print(msg)

except:

break

data:

象 包 將 士 士 兵 相 相 帥 帥

帥 相 帥 帥 兵 包 將 將 卒 卒 


2025年5月16日 星期五

search sample

 d = [3,5,10,1,7,9,8,6,4,2]

print(d.index(9))


d = 'abcdefg'

print(d.find('e'))

print(d.index('e'))


d = 'tomorrow will be better'

f = 'r'

for i in range(len(d)):

  if d[i] == f:print(i,':',d[i])

sort sample

 arr = [3,5,10,1,7,9,8,6,4,2]

def qsort(arr):

  if len(arr)<=1:return arr

  pv = arr[0]

  lar = [i for i in arr if i<pv]

  mar = [i for i in arr if i==pv]

  rar = [i for i in arr if i>pv]

  return qsort(lar)+mar+qsort(rar)


def ssort(arr):

  if len(arr)<=1:return arr

  minv = min(arr)

  arr.remove(minv)

  return [minv] + ssort(arr)

 

def isort(arr):

  arr1 = []

  for i in arr:

    arrs = [j for j in arr1 if j <i]

    arrb = [j for j in arr1 if j >i]

    arr1 = arrs + [i] +arrb 

  return arr1


def bsort(arr):

  l = len(arr)

  for i in range(l-1):

    for j in range(l-1):

      if arr[j]>arr[j+1]:

        arr[j],arr[j+1]=arr[j+1],arr[j]

  return arr


print(qsort(arr))

print(ssort(arr[::]))

print(isort(arr))

print(bsort(arr))

打磚塊左右對打版


 


import pygame
import sys
import random
pygame.init()

#  玩家設定 0:玩家右   2:玩家左   9:開始未指定玩家
onplay = 9

# 畫面設定
WIDTH, HEIGHT = 1920, 1080
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 100, 255)
COLORS = [(255, 100, 100), (255, 200, 0), (0, 200, 100), (100, 100, 255), (200, 0, 200)]
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("打磚塊遊戲")


# 玩家方塊
player_width = 20
player_height = 100
player_x = WIDTH - 75
player_y = HEIGHT // 2 - player_height // 2
player_speed = 16
player2_width = 20
player2_height = 100
player2_x = 75
player2_y = HEIGHT // 2 - player_height // 2
player2_speed = 16

# 球
ball_radius = 10
ball_x = WIDTH // 2+random.randint(-200, 200)
ball_y = HEIGHT // 2
ball_x_speed = 18+ random.randint(-6, 6)
ball_y_speed = -12+ random.randint(-5, 5)

# 磚塊設定(5列×10行)
brick_rows = 20
brick_cols = 1
brick_width = 20
brick_height = HEIGHT // brick_rows
bricks = []
for row in range(brick_rows):
    for col in range(brick_cols):
        x = col * brick_width+WIDTH//2-50
        y = row * brick_height  # 從 y=40 開始畫
        rect = pygame.Rect(x, y, brick_width - 2, brick_height - 2)
        color = COLORS[row % len(COLORS)]
        bricks.append({'rect': rect, 'color': color, 'alive': True})

for row in range(brick_rows):
    for col in range(brick_cols):
        x = col * brick_width+WIDTH//2-50-200
        y = row * brick_height  # 從 y=40 開始畫
        rect = pygame.Rect(x, y, brick_width - 2, brick_height - 2)
        color = COLORS[row % len(COLORS)]
        bricks.append({'rect': rect, 'color': color, 'alive': True})

for row in range(brick_rows):
    for col in range(brick_cols):
        x = col * brick_width+WIDTH//2-50+200
        y = row * brick_height  # 從 y=40 開始畫
        rect = pygame.Rect(x, y, brick_width - 2, brick_height - 2)
        color = COLORS[row % len(COLORS)]
        bricks.append({'rect': rect, 'color': color, 'alive': True})

# 分數
score = 0
score2 = 0
font = pygame.font.SysFont(None, 36)
clock = pygame.time.Clock()
running = True
while running:
    clock.tick(60*1.0)

    # 事件處理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 玩家左右控制
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        player_y -= player_speed
    if keys[pygame.K_DOWN]:
        player_y += player_speed
  
    if keys[pygame.K_q]:
        player2_y -= player2_speed
    if keys[pygame.K_z]:
        player2_y += player2_speed
    player_y = max(0, min(WIDTH - player_height, player_y))
    player2_y = max(0, min(WIDTH - player2_height, player2_y))
    player_y = ball_y - 50
    player2_y = ball_y - 50

    # 球移動
    ball_x += ball_x_speed
    ball_y += ball_y_speed

    # 左右牆反彈
    if ball_x - ball_radius <= 0 or ball_x + ball_radius >= WIDTH:
        ball_x_speed = -ball_x_speed

    # 上下邊界反彈
    if ball_y - ball_radius <= 0:
        ball_y_speed = abs(ball_y_speed)
    if ball_y > HEIGHT:
        ball_y_speed = -ball_y_speed

    # 掉到底部,遊戲重置
    if ball_y > WIDTH:
        ball_x = WIDTH // 2
        ball_y = HEIGHT // 2
        ball_x_speed = -4
        ball_y_speed = 4
        score = 0
        for b in bricks:
            b['alive'] = True

    # 撞玩家方塊
    player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
    player2_rect = pygame.Rect(player2_x, player2_y, player2_width, player2_height)
    # if player_rect.collidepoint(ball_x, ball_y + ball_radius) and ball_y_speed > 0:
    #     ball_y_speed = -ball_y_speed
    if player_rect.collidepoint(ball_x, ball_y + ball_radius) and ball_x_speed > 0:
        ball_x_speed = -(ball_x_speed+ random.randint(-4, 4))
        ball_y_speed = (ball_y_speed+ random.randint(-4, 4))
        onplay = 0
    if player2_rect.collidepoint(ball_x, ball_y + ball_radius) and ball_x_speed < 0:
        ball_x_speed = -(ball_x_speed+ random.randint(-4, 4))
        ball_y_speed = (ball_y_speed+ random.randint(-4, 4))
        onplay = 2
    # 撞磚塊
    for b in bricks:
        if b['alive'] and b['rect'].collidepoint(ball_x, ball_y):
            b['alive'] = False
            ball_x_speed = -ball_x_speed
            if onplay == 0:score += 10
            if onplay == 2:score2 += 10
            break

    # 畫面更新
    screen.fill(WHITE)

    # 畫磚塊
    for b in bricks:
        if b['alive']:
            pygame.draw.rect(screen, b['color'], b['rect'])

    # 畫玩家與球
    pygame.draw.rect(screen, RED, player_rect)
    pygame.draw.rect(screen, BLUE, player2_rect)
    pygame.draw.circle(screen, BLUE, (int(ball_x), int(ball_y)), ball_radius)

    # 分數顯示
    score_text = font.render(f"Score: {score}", True, (0, 0, 0))
    score_text2 = font.render(f"Score: {score2}", True, (0, 0, 0))
    screen.blit(score_text, (WIDTH-150, 10))
    screen.blit(score_text2, (10, 10))
    pygame.display.flip()
pygame.quit()
sys.exit()

2025年5月15日 星期四

selection sort recursive edition

 d = [6,7,8,9,1,2,3,4,5]


def selsort(d):

  if len(d)==0:return []

  minV = min(d)

  d.remove(minV)

  return [minV] + selsort(d)

print(selsort(d))


# Output:


# [1, 2, 3, 4, 5, 6, 7, 8, 9]

打磚塊 II



# -*- coding: utf-8 -*-

import pygame

import sys

import random

pygame.init()


# 畫面設定

WIDTH, HEIGHT = 1400, 600

WHITE = (255, 255, 255)

RED = (255, 0, 0)

BLUE = (0, 100, 255)

YELLOW = (255, 255, 0)

PURPLE1 = (153, 0, 153)

COLORS = [(255, 100, 100), (255, 200, 0), (0, 200, 100), (100, 100, 255), (200, 0, 200)]

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("打磚塊遊戲")

# 玩家方塊

player_width = 100

player_height = 20

player_x = WIDTH // 2 - player_width // 2

player_y = HEIGHT - 50

player_speed = 8

player2_width = 100

player2_height = 20

player2_x = WIDTH // 2 - player_width // 2

player2_y =  50

player2_speed = 8


# 球


ball_radius = 10


ball_x = WIDTH // 2


ball_y = HEIGHT // 2 - 100 *random.randint(-1,1)


ball_x_speed = 24


ball_y_speed = -12




# 磚塊設定(5列×10行)


brick_rows = 3


brick_cols = 30


brick_width = WIDTH // brick_cols


brick_height = 25


bricks = []




for row in range(brick_rows):


    for col in range(brick_cols):


        x = col * brick_width


        y = row * brick_height + HEIGHT//2 - 25  # 從 y=40 開始畫


        rect = pygame.Rect(x, y, brick_width - 2, brick_height - 2)


        color = COLORS[row % len(COLORS)]


        bricks.append({'rect': rect, 'color': color, 'alive': True})




# 分數


score = 0


font = pygame.font.SysFont(None, 36)




clock = pygame.time.Clock()


running = True


while running:


    clock.tick(60)




    # 事件處理


    for event in pygame.event.get():


        if event.type == pygame.QUIT:


            running = False




    # 玩家左右控制


    keys = pygame.key.get_pressed()


    if keys[pygame.K_LEFT]:


        player_x -= player_speed


    if keys[pygame.K_RIGHT]:


        player_x += player_speed


    player_x = max(0, min(WIDTH - player_width, player_x))

    player_x =  ball_x -50

    player2_x =  ball_x -50



    # 球移動


    ball_x += ball_x_speed


    ball_y += ball_y_speed




    # 左右牆反彈


    if ball_x - ball_radius <= 0 or ball_x + ball_radius >= WIDTH:


        ball_x_speed = -ball_x_speed




    # 上下邊界反彈


    if ball_y - ball_radius <= 0:


        ball_y_speed = -ball_y_speed




    # 掉到底部,遊戲重置


    if ball_y > HEIGHT:


        ball_x = WIDTH // 2


        ball_y = HEIGHT // 2


        ball_x_speed = 4


        ball_y_speed = -4


        score = 0


        for b in bricks:


            b['alive'] = True




    # 撞玩家方塊


    player_rect = pygame.Rect(player_x, player_y, player_width, player_height)

    player2_rect = pygame.Rect(player2_x, player2_y, player2_width, player2_height)


    if player_rect.collidepoint(ball_x, ball_y + ball_radius) and ball_y_speed > 0:


        ball_y_speed = -ball_y_speed

    if player2_rect.collidepoint(ball_x, ball_y + ball_radius) and ball_y_speed < 0:


        ball_y_speed = -ball_y_speed




    # 撞磚塊


    for b in bricks:


        if b['alive'] and b['rect'].collidepoint(ball_x, ball_y):


            b['alive'] = False


            ball_y_speed = -ball_y_speed


            score += 10


            break




    # 畫面更新


    screen.fill(WHITE)




    # 畫磚塊


    for b in bricks:


        if b['alive']:


            pygame.draw.rect(screen, b['color'], b['rect'])




    # 畫玩家與球


    pygame.draw.rect(screen, RED, player_rect)

    pygame.draw.rect(screen, PURPLE1, player2_rect)


    pygame.draw.circle(screen, BLUE, (int(ball_x), int(ball_y)), ball_radius)




    # 分數顯示


    score_text = font.render(f"Score: {score}", True, (0, 0, 0))


    screen.blit(score_text, (10, 10))




    pygame.display.flip()




pygame.quit()


sys.exit()


#計算a/b,無條件捨去到小數點以下第25位

 #計算a/b,無條件捨去到小數點以下第25位


from decimal import Decimal

while True:

try:

a,b = map(int,input().split())

r = Decimal(a)/Decimal(b)

rr = f'{r:.26f}'

print(rr[:-1])

except:

break

2025年5月13日 星期二

text.encode

 #_*_coding=big5_*_


while True:

try:

text = input()

hex_output = ''.join([f'{byte:02x}' for byte in text.encode('big5')])

hex_output = hex_output.upper()

print(hex_output)

except:

break

2025年5月12日 星期一

打字練習程式:分段學習結構

 

單元 目標 重點學習
第1單元 建立 GUI 視窗與顯示句子 tkinter 基本介面、文字顯示
第2單元 建立輸入框並接收輸入 Entry 輸入框與事件綁定
第3單元 計算正確率與耗時 time.time() 與比對邏輯
第4單元 多題練習與換題功能 random.choice()、變數更新
第5單元 完整統計、重新開始功能 題數統計、平均計算、重啟流程
`

打字練習程式

 import tkinter as tk

import random

import time


# 建立句子庫

sentences = [

    "The quick brown fox jumps over the lazy dog.",

    "Python is a powerful programming language.",

    "Practice makes perfect.",

    "Typing is a useful skill.",

    "Artificial intelligence is changing the world."

]


# 全域變數

target_sentence = random.choice(sentences)

start_time = 0

question_count = 0

total_time = 0

total_accuracy = 0

results = []  # 儲存每題耗時與正確率


def start_typing():

    global start_time

    entry.delete(0, tk.END)

    entry.focus()

    start_time = time.time()

    result_label.config(text="")


def check_typing(event=None):

    global start_time, question_count, total_time, total_accuracy, results


    end_time = time.time()

    user_input = entry.get()

    elapsed_time = round(end_time - start_time, 2)


    correct = sum(1 for a, b in zip(target_sentence, user_input) if a == b)

    accuracy = round(correct / len(target_sentence) * 100, 2)


    # 統計資料儲存

    question_count += 1

    total_time += elapsed_time

    total_accuracy += accuracy

    results.append((question_count, elapsed_time, accuracy))


    if question_count == 5:

        show_summary()

    else:

        next_question()


def next_question():

    global target_sentence

    target_sentence = random.choice(sentences)  # ✅ 真正換句子

    sentence_label.config(text=target_sentence)

    entry.delete(0, tk.END)

    entry.focus()


def show_summary():

    avg_accuracy = round(total_accuracy / 5, 2)

    result_text = "📊 練習結束!以下是你的統計資料:\n\n"

    for num, t, acc in results:

        result_text += f"第 {num} 題:耗時 {t} 秒,正確率 {acc}%\n"

    result_text += f"\n✅ 總耗時:{round(total_time, 2)} 秒"

    result_text += f"\n✅ 平均正確率:{avg_accuracy}%"


    result_label.config(text=result_text)

    entry.config(state='disabled')  # 鎖住輸入框

    sentence_label.config(text="練習結束,請重新啟動程式再來一次")


# 建立主視窗

window = tk.Tk()

window.title("打字練習程式")

window.geometry("800x500")


# 「開始」按鈕放右上

start_button = tk.Button(window, text="開始", command=start_typing)

start_button.place(x=730, y=10)


# 題目區

tk.Label(window, text="請輸入以下句子:", font=("Arial", 16)).pack(pady=20)

sentence_label = tk.Label(window, text=target_sentence, font=("Arial", 12), fg="blue", wraplength=750)

sentence_label.pack()


# 輸入框

entry = tk.Entry(window, font=("Arial", 12), width=80)

entry.place(x=20, y=320)

entry.bind("<Return>", check_typing)


# 顯示結果與統計

result_label = tk.Label(window, text="", font=("Arial", 14), justify="left")

result_label.pack(pady=10)


# 啟動主程式

window.mainloop()

2025年5月9日 星期五

insert sort python edition

 d = list(range(110,100,-1))+list(range(1,11))

print(d)

t = d[0:]


for i in t:

  d = [j for j in d if j<i] + [i] + [j for j in d if j>i]

print(d)


Output:


[110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]

2025年5月8日 星期四

求質數 II

 primes = []  # 建立一個空列表,用來儲存質數


for p in range(2, 101):  # 檢查從 2 到 100 的每一個數字

    is_prime = True  # 假設目前的數字 p 是質數


    for i in range(2, int(p**0.5) + 1):  # 從 2 檢查到 √p

        if p % i == 0:  # 如果 p 被整除,表示不是質數

            is_prime = False

            break  # 提前跳出迴圈,沒必要再檢查下去


    if is_prime:

        primes.append(p)  # 如果是質數,加入列表


print(primes)  # 印出所有找到的質數


求質數

print( [ p for p in range(2,100+1) if all(p%i!=0 for i in range(2,int(p**0.5)+1)) ])


Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Python 3.x 的內建標準庫

 Python 3.x 的內建標準庫(Standard Library)是一套隨 Python 安裝時就已包含的模組,不需額外安裝就可直接使用。這些模組涵蓋:

  • 數學與統計
  • 檔案處理
  • 作業系統互動
  • 正規表示法
  • 資料壓縮
  • 網路處理
  • 程式設計工具(如時間、日期、迴圈控制)
  • 單元測試
  • 資料結構輔助模組(如 collections

以下是常見 Python 3.x 標準庫分類與模組代表:

📊 數學與統計

模組功能簡述
math提供數學函數(如 sin, sqrt)
statistics平均數、中位數、標準差等統計
random隨機數與抽樣工具

📁 檔案與資料處理

模組功能簡述
os作業系統操作(檔案、資料夾)
shutil高階檔案操作(複製、搬移)
csv讀寫 CSV 檔案
json讀寫 JSON 格式

🧮 資料結構與演算法輔助

模組功能簡述
collections額外資料型別如 deque, Counter
heapq最小堆排序工具
bisect二分搜尋
array效率較高的陣列(固定型別)

🕒 時間與日期

模組功能簡述
time處理時間戳記、延遲等
datetime處理日期與時間
calendar月曆、閏年等工具

📧 網路與 Web

模組功能簡述
urllib網頁請求與網址處理
httpHTTP 協定處理
socket低階網路連線工具

🔍 正規表示式與字串處理

模組功能簡述
re正規表示式處理
string字元集、格式工具
textwrap文字換行與排版處理

🔒 安全與編碼

模組功能簡述
hashlib加密(MD5、SHA 等)
base64編碼轉換

🧪 測試與除錯

模組功能簡述
unittest單元測試框架
traceback錯誤堆疊追蹤
pdb互動式除錯器

🧰 其他常用工具

模組功能簡述
itertools高效迴圈工具組
functools函數輔助工具(如 LRU cache)
typing型別提示(type hint)
dataclasses自動產生 class 的工具
enum列舉型別