Skip to main content

2-8 常見程式範例

氣泡排序法(Bubble Sort Algorithm)

array=[5,3,4,6,9,1,7,2,0,8]
def BubbleSort(data):
  n = len(data)
  for i in range(n - 1):
    for j in range(n - 1 - i):
      if data[j] > data[j+1]:
        temp = data[j]
        data[j] = data[j+1]
        data[j+1] = temp
  return data

print(BubbleSort(array))

找出質數

lower = 100
upper = 200
for num in range(lower, upper+1):
  if num > 1:
    for i in range(2, num):
      if num % i == 0:
        break
    else:  #for 搭配else 會在跑完迴圈最後一圈之後執行else裡面的程式
        print(num)

最小公倍數

(Least Common Mutiple, LCM)

def LCM(num1, num2):
if num1 > num2: #找出兩個數之中較大者
greater = num1
else:
greater = num2
while True:
if (greater % num1 == 0 ) and (greater % num2 == 0): #都能被兩個數整除
break
greater += 1
return greater

n1 = int(input("請輸入第一個數字:"))
n2 = int(input("請輸入第二個數字:"))

print("最小公倍數 = " , LCM(n1, n2))
 

最大公因數

(Greatest Common Divisor,GCD) 或 (Highest Common Factor, HCF)

def GCD(num1, num2):
  if num1 > num2 :
    smaller = num2
  else:
    smaller = num1
  for i in range(1, smaller + 1):
    if (num1 % i == 0) and (num2 % i == 0):   #i都能被兩個數整除
      factor = i
  return factor

n1 = int(input("請輸入第一個數字:"))
n2 = int(input("請輸入第二個數字:"))

print("最大公因數 = ", GCD(n1, n2))

數字反向

n = int(input("請輸入一個數字:"))
def rev_num(num):
  rev = 0
  while num > 0:
    reminder = num % 10
    rev = (rev * 10) + reminder
    num = num // 10
  return rev

print("數字反向後=", rev_num(n)))

字串反向

s = input("請輸入字串:")

def rev_str(string):
  x = ""
  for i in string:
    x = i + x
  return x

print(rev_str(s))