2017年10月7日 星期六

[Python練習]解方程式 (Python 程式設計入門-金融實務管理案例第二版 5-9)

閏年規則:
  • 西元年份除以4不可整除,為平年。
  • 西元年份除以4可整除,且除以100不可整除,為閏年。
  • 西元年份除以100可整除,且除以400不可整除,為平年
  • 西元年份除以400可整除,為閏年。
==========================================================
year = input("please input a year: ")

try:
    year = int(year)
except ValueError:
    exit('Please a number')
else:
    if year % 4 == 0:
        if year % 100 == 0 and year % 400 != 0:
            exit('not a leap year')
        print('%d is leap year' % (year))
    else:
        print('not a leap year')
==========================================================
執行結果:
please input a year: 1900
not a right year

please input a year: 2096
2096 is leap year

[Python練習]解方程式 (Python 程式設計入門-金融實務管理案例第二版 5-8)

停車費計算
假設某個停車場的費率是停車 2 小時以內,每半小時 30 元,超過 2 小時,但未滿 4 小時的部分,每半小時 40 元,超過 4 小時以上的部分,每半小時 60 元。未滿半小時的部分不計費。

請撰寫程式,輸入起始停車時間和結束停車時間,計算共需繳多少費用。

==================================================================
import datetime
import time

def getMinuteDelta(startTime, endTime):
    if startTime > endTime:
        return 0
    # convert to datetime    y,m,d,H,M,S = startTime[0:6]
    dataTimea=datetime.datetime(y,m,d,H,M,S)
    y,m,d,H,M,S = endTime[0:6]
    dataTimeb=datetime.datetime(y,m,d,H,M,S)

    # compare datetime and convert to minute
    secondDelta = (dataTimeb-dataTimea).seconds
    dayDelta = (dataTimeb - dataTimea).days
    minuteDelta = dayDelta * (24 * 60) + round(secondDelta / 60)
    return minuteDelta

def calculateMoney(time):
    time = divmod(time, 30)
    totalMondy = 0    if time[0] <= 4:
        totalMondy += time[0] * 30    elif time[0] <= 8:
        totalMondy += 4 * 30 + (time[0] - 4) * 40    else:
        totalMondy += 4 * 30 + 4 * 40 + (time[0] - 8) * 60
    return totalMondy

startTime = input('Please input start time (e.g YYYY-MM-DD hh:mm:ss) :')
endTime = input('Please input end time (e.g YYYY-MM-DD hh:mm:ss) : ')
dateFormat = '%Y-%m-%d %H:%M:%S'
try:
    # convert input to time format
    minuteDelta = getMinuteDelta(time.strptime(startTime, dateFormat),
                                 time.strptime(endTime, dateFormat))
except ValueError:
    print("[Error #1] Wrong Format")
else:
    print('total: $%d' %(calculateMoney(minuteDelta)))
==================================================================

執行結果:

Please input start time (e.g YYYY-MM-DD hh:mm:ss) :2017-01-01 10:23:00
Please input end time (e.g YYYY-MM-DD hh:mm:ss) : 2017-01-01 15:20:00
total: $340

2017年10月6日 星期五

[Python練習]解方程式 (Python 程式設計入門-金融實務管理案例第二版 5-7)

計算相遇時間:
假設您步行的速度為每秒 1 公尺,而您的朋友小華不行的速度則為每秒 30 英吋,如果你們兩人在距離 x 公尺的操場對面前進,請撰寫城市計算出多久會相遇?
(1 英吋等於 2.54 公分)

本題作答時須先將不同距離單位轉換成一致性的單位,計算出秒數後,如秒數超過 60 秒,還需轉換成分鐘或小時 (以此類推)。

=================================================================
x = input('Please input the distance(meter): ')
try:
    x = int(x)
except ValueError:
    print('Please input a number!')
else:
    t = x / 1.762   #t + (30 * 2.54 / 100)t = x
    t = divmod(t, 60)
    second = t[1]
    minute = t[0]
    hour = 0    day = 0
    if minute > 60:
        t = divmod(minute, 60)
        hour = t[0]
        minute = t[1]
    if hour > 24:
        t = divmod(hour, 24)
        day = t[0]
        hour = t[1]
    print('兩人在%d天%d小時%d分%d秒會相遇' %(day, hour, minute, second))
=================================================================
執行結果:

Please input the distance(meter): 200000
兩人在1天7小時31分47秒會相遇

[Python練習]解方程式 (Python 程式設計入門-金融實務管理案例第二版 5-6)

假設有 N 元,現在要到市場買 x 條香蕉,y 個橘子,z 個蘋果,x、y、z 皆大於 0,且 x 是 5 的倍數,y 是 3 的倍數,z 是偶數。

已知香蕉 1 條 5 元,橘子 1 個 6 元,蘋果 1 個 10 元,至少要花掉 100 元,請列出所有可能的水果組合。

輸入 N (100 <= N <= 1000)

由小到大一律輸出 x,y,z 所有可能的組合,x,y,z 之間以一個空白字元隔開,且每一種組合結尾必須跳列。如果沒有答案,則輸出 No Solution。

===================================================================
N = input("Please input N: ")
try:
    N = int(N)
except ValueError:
    print("please input a number (100~1000)")
else:
    if N < 100 or N > 1000:
        exit("100 < N < 1000")
    else:
        paraX = 5
        paraY = 3
        paraZ = 2
        result = []
        for x in range(0, N, paraX):
            for y in range(0, N - paraX * x, paraY):
                for z in range(0, N - paraY * y, paraZ):
                    if (5 * x + 6 * y + 10 * z) == N \
                            and x > 0 and y > 0  and z > 0:
                        tmp = [x, y, z]
                        result.append(tmp)
        if len(result) == 0:
            exit('No Solution')
        for r in result:
            print('x=%d y=%d z=%d' %(r[0], r[1], r[2]))
===================================================================
執行結果:
Please input N: 300
x=10 y=15 z=16
x=20 y=30 z=2
x=30 y=15 z=6

Please input N: 102
No Solution

2017年10月4日 星期三

[Python練習] 3x3 矩陣運算 (加法、減法、乘法),不使用 Numpy


inputA = []
inputB = []

try:
    # Conver input "number" string to list
    inputA = list(map(int, input("Input a 3x3 matrix(A): ").split()))
    inputB = list(map(int, input("Input a 3x3 matrix(B): ").split()))
except ValueError:
    print("Error type 1: please input a number matrix")
except:
    print("Error type 2: unknow error")
else:
    # Check if the input matrix fit the criteria of 3x3 matrix
    if len(inputA) != len(inputB) and len(inputA) != 9:
        print('please input 3x3 matrix')
    else:
        matrixA = []
        matrixB = []
        matrixPlus = []
        matrixSub = []
        matrixMulti = []
        matrixDiv = []

        # Convert 1-way list to 2-way list (3x3 matrix)
        for x in range(0,len(inputA),3):
            matrixA.append(inputA[x:x+3])
            matrixB.append(inputB[x:x+3])
            #print(matrixA)

        # Calculate plus and sub
        for x in range(len(matrixA)):
            tmpPlus = []
            tmpSub = []
            for y in range(3):
                tmpPlus.append(matrixA[x][y] + matrixB[x][y])
                tmpSub.append(matrixA[x][y] - matrixB[x][y])
            matrixPlus.append(tmpPlus)
            matrixSub.append(tmpSub)

        # Calcuste multiple
        for k in range(len(matrixA)):
            tmpMulti = []
            for i in range(len(matrixB[0])):
                sum = 0
                for j in range(len(matrixB)):
                    sum += matrixA[k][j] * matrixB[j][i]
                tmpMulti.append(sum)
            matrixMulti.append(tmpMulti)

        print("MatrixA + MatrixB: " + str(matrixPlus))
        print("MatrixA - MatrixB: " + str(matrixSub))
        print("MatrixA * MatrixB: " + str(matrixMulti))

====================================================
執行結果:
Input a 3x3 matrix(A): 8 1 6 3 5 7 4 9 2
Input a 3x3 matrix(B): 1 2 3 4 5 6 7 8 9
MatrixA + MatrixB: [[9, 3, 9], [7, 10, 13], [11, 17, 11]]
MatrixA - MatrixB: [[7, -1, 3], [-1, 0, 1], [-3, 1, -7]]
MatrixA * MatrixB: [[54, 69, 84], [72, 87, 102], [54, 69, 84]]

2017年9月23日 星期六

[Python] 檢查台灣身份證號碼

最近學習 python,實作書本上的題目,其中一個練習是檢查所輸入的身份正證號碼是否正
確。

台灣身份證的編碼規則,請參考該網址說明。

實作概念:
1. 透過 Dictionary 建立身分證第一碼(地區碼)的對應表:對應表內容皆由 List 產生,透過 zip() 將英文和數字編碼合併在一起,而建立出地區碼對應表
2. 偵測明顯的錯誤(如:長度錯誤,第一碼非英文字元...等)
3. 將輸入的身份證內容取出,並根據身份證編碼規則,將輸入內容轉換成 check sum
4. 檢查 check sum 是否符合身分證編碼規則

程式碼:

import string

# create alphabet for 1st char of ID
alphabet = list(string.ascii_uppercase[0:8])
alphabet.extend(list(string.ascii_uppercase[9:]))
code = list(range(10,33))

# create the location mapping code for char of ID
locationCode = dict(zip(alphabet,code))

while(1):
    id = input('Please input your security id: ')
    if id == 'exit':
        break
    elif len(id) != 10 or not(id[0].isalpha()) \
            or not(id[1:].isdigit() or int[id[1] > 2 or id[1] < 1]):
        print('Error: wrong format')
        continue
    # Convert 1st Alphabet to Numeric code
    encodeID = list(str(locationCode[id[0].upper()]))
    encodeID.extend(list(id[1:]))
    print(encodeID)
    checkSum = int(encodeID[0])

    # Calculate the checksum of ID
    para = 9
    for n in encodeID[1:]:
        if para == 0:
            para = 1
        print(n, para)
        checkSum += int(n)*para
        para -= 1

    # Check the checksum
    if checkSum % 10 == 0:
        print("ID is correct")
    else:
        print('Error: ID is not correct')

2016年5月31日 星期二

Get MAC address using C program

static int getmac() {
    struct ifreq ifr;
    struct ifconf ifc;
    char buf[1024];
    int success = 0;

    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock == -1) {
        // handle error 
    }

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;

    if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) {
        // handle error
    }

    struct ifreq* it = ifc.ifc_req;
    const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));

    for (; it != end; ++it) {
        strcpy(ifr.ifr_name, it->ifr_name);
        if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
            if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
                if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
                    success = 1;
                    break;
                }
            }
        }
        else {
            // handle error 
        }
    }
    close(sock);

    unsigned char mac[6];

    if (success) memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
    printf("Get Mac from asLicense : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}