練習 Python 100 Days(5)

練習 Python 100 Days 前幾天的比較簡單, 就從第五天的練習題開始 水仙花數(Narcissistic number) 用來描述一個 N 位非負數, 其中每個數字的 N 次方和等於該數字本身 代碼: for num in range(1000): squares = len(str(num)) count = 0 count = sum([int(x)**squares for x in str(num)]) if num == count: print(f"The Narcissistic number is : {count}" ) 完美數(Perfect number) 用來描述一個數字, 除了自己以外的所有真因子的總和, 等於它自己, 就是完美數 代碼: for num in range(100): list = [x for x in range(1, num) if num%x==0] if sum != [] and sum(list) == num: print(num) 參考: Python-100-Days - Day5……

Continue reading

實數轉換成整數

前言 ​ 使用 int() 函式做數值轉換, 會遇到小數點以下有值時, 會被無條件捨去的困擾, 從 stackoverflow 看到有兩種解法 >>> num1 = 1.0 >>> int(num1) 1 >>> num2 = 1.5 >>> int(num2) 1 解法一 ​ 使用 is_integer() 函式配合 if 判斷是否為整數, 是才做 int() 轉換 >>> (1.0).is_integer() True >>> (1).is_integer() ### 缺點是已經是整數的變數, 會跳錯 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'int' object has no attribute 'is_integer' >>> (1.5).is_integer() False >>> (0.9999999999 ).is_integer() False >>> data = [1.……

Continue reading

使用 Pandas groupby 和 agg 合併資料

前因 想要把下面 dataframe , 分類後合併在一起 order devie abbr 0 first memory m 1 second cpu c 2 third disk d 3 first cpu c 成為下面的 data format order devie abbr 0 first memory, cpu [m, c] 1 second cpu [c] 2 third disk [d] 先建立兩個 lambda 變數 ​ f1 的功用是將 dataframe 轉換成字串, f2 則將 dataframe 轉換成 list >>>f1 = lambda x: ", ".join(x.dropna()) >>>f1(data.abbr) 'm, c, d, c' >>>f2 = lambda x: [z for y in x for z in y] >>>f2(data.……

Continue reading