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]]