2017年9月30日 星期六

Python - Random筆記

import random

幫串列洗牌
a = list(range(1,11))
random.shuffle(a)

隨機產生一個範圍的整數
random.randint(0,10) # 0..9

隨機產生浮點數
random.random()
random.uniform(1, 10) # 1..9


隨機產生字元
random.choice('abcdefg') # b

選取多個字元轉換串列
random.sample('abcdefghij',3) # ['c', 'f', 'a']



Python - Function筆記

函式Function

宣告方式
def hello():
    print ('hello')

hello() # hello


設定引數
def hello(name):
    print('hello, {}'.format(name))

hello('Tom')


引數的預設值,呼叫function未設定引數
def hello(name='default'):
    print('hello, {}'.format(name))

hello()


function return值
def hello():
    return 'hello123'

h = hello()
print(h) # hello123

引數為*args時,為Tuple

引數為**args時,為Dictionary


Python - Flow Control 筆記

控制流程Flow Control為程式語言重要的一環,在很多語言中都看得到控制流程,以下我要介紹python的控制流程

Python的布林值Boolean分別為True & False,boolean開頭都是大寫
True 成立
False 不成立

and:全為真才是真
or:任一為真即為真

> 大於 greater than
3>4 # False
4>3 # True

< 小於 less than
5<7 # True
6<4 # False

== 等於 equal
'3' == '3' # True
1 == 2 # False

!= 不等於 not equal
3 != 4 # True
3!= 3 # False

if判斷式
if a > b :
    print('a>b')
elif b > a :
    print('b>a')
else:
    print('a==b')

迴圈Loops,用於處理(迭代iterate)連續的資料sequence

For Loops

迭代串列
seq = [1, 2, 3, 4, 5]
for item in seq:
    print(item)

迭代字典
seq = {'Tom':'29', 'John':'30', 'Amy':'15'}
for key in seq:
    print(key) # 連續的key
    print(seq[key]) # 利用key找出value

迭代串列內容為Tuple
seq = [(1, 2), (3, 4), (5, 6)]

for (tu1, tu2) in seq: # 括號()可省略
    print (tu2)
    print(tu1)

while loops
while i<5:
    print(i)
    i = i +1

利用range()建立數字序列
range(start, stop, step)
備註:stop前停止
range(10) # 0..9
range(1, 10) # 1..9
range(1, 10 , 2) # 奇數1..9
應用
list(range(0, 7)) # [0 ,1 ,2 ,3 ,4, 5, 6]
list(range(0, 7, 2)) # [0, 2, 4, 6]
for i in range(0, 7):
    print(i) # 0 1 2 3 4 5 6

串列生成式
seq = [1, 2, 3, 4]
a = [num**2 for num in seq] # [1, 4, 9 ,16]

如果使用range的情況
a = [num**2 for num in range(1,5)] # [1, 4, 9 ,16]


Python - Set筆記

集合Set有著不重複的特性

宣告方式
s = set()

加入值
s.add(1)
s.add(2)
s.add(2)
s.add(4)
s.add(3)
s.add(3)
print(s) # set([1, 2, 3, 4])

利用list()轉串列
print(list(s)) # [1, 2, 3, 4]

in():某鍵是否存在,回傳布林值
intersection():取得交集(同"&")
union():取得聯集(同"|")
difference():取得差集(同"-")
symmetric_difference():取得互斥(同"^")
issubset():檢查子集合(同"<=")
issuperset():檢查超集合(同">=")
<:檢查真子集
>:檢查真超集合









Python - Tuple筆記

Tuple與List相似,最大的不同即是Tuple內的值不可以更改,否則會發生錯誤

宣告方式
t = ()
t = (1, 2, 3, 4)

利用索引值取出Tuple內的值
print(t(1)) # 2

利用list()轉換成串列
print(list(t)) # [1, 2, 3, 4]





2017年9月29日 星期五

Python - Dictionary筆記

Python的字典(Dictionary)就是雜湊(Hash),運用方式一模一樣,只是說法的不同。
一個字典Key(鍵) & Value(值)可以是任何型態,字典並沒有順序性

宣告方式
d = {}

key & value
d = {"key1":"value1", "key2":"value2", "key3":"value3"}

利用key取value
print(d["key1"]) # value1

賦予key value,已經存在key的情況下
d["key1"] = "value has been modified"
print(d["key1"]) # value has been modified

加入新的key & value,不存在key的情況下
d["key4"] = "value4"
print(d) # {'key3': 'value3', 'key2': 'value2', 'key1': 'value1', 'key4': 'value4'}

巢狀字典
d = {
"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":{"key4-1":["It","is","a","list"]}
}
print(d["key4"]["key4-1"]) # ["It","is","a","list"]
print(d["key4"]["key4-1"][1]) # is


檢查字典key

if 'key1' in d:
    pass

刪除key

del d['key1']














Python - List筆記

宣告方式
a = []

串列List內容值可接受多種不同的型別
a = [1,2,"3",4.5,['a','b','c','d']]

舉例,除非另外宣告a串列,大部份範例都由以下a串列起始
a = [1,2,3,4,5]

使用len()存取陣列長度
print(len(a)) # 5 

串列可以利用索引值讀取值
print(a[2]) # 3

索引值可以為負值
a[-1] # 等同a[4] display 5

同樣也可以像字串擷取資料
a[2:] # [3, 4, 5]

利用append加入值至串列結尾
a.append(6);
print(a) # [1, 2, 3, 4, 5, 6]

結合不同的串列利用extend(),結合後b會結合在結尾
b = [6, 7, 8]
a.extend(b) 
print(a) # [1, 2, 3, 4, 5, 6, 7, 8]
補充:extend()也等同於+=

利用pop()彈出串列中的值
a.pop()
print(a) # [1, 2, 3, 4] 5被彈出,因為沒有參數預設彈出最後一個值
pop()也可以搭配索引值參數使用
a.pop(0)
print(a) # [2, 3, 4, 5] 1被彈出

利用insert()插入串列,新增在指定索引值裡,其餘的值索引值往後推
a.insert(2,"new")
print(a) # [1, 2, 'new', 3, 4, 5, 6]

利用reverse()顛倒串列
a.reverse()
print(a) # [5, 4, 3, 2, 1]

利用sort()排序串列值,使用sorted()將不會改變內容值而是更改於建立的副本中
b = [3,5,1,3,7,6,4,55,99]
b.sort()
print(b) # [1, 3, 3, 4, 5, 6, 7, 55, 99]

巢狀陣列讀取方式,二維串列為例
c = [['a','b','c'],['A','B','C']]
print(c[0][2]) # c

利用for迭代串列
matrix = [[1,2,3],[4,5,6],[7,8,9]]
first_col = [row[0] for row in matirx]
print(first_col) # [1,4,7]

利用tuple()轉成Tuple
print(tuple(a)) # (1, 2, 3, 4, 5)

利用set()轉成Set
a = [1, 1, 1, 2, 3, 3]
print(set(a)) # set([1, 2, 3])

利用index()尋找索引值
a.index('3') # 2

利用count()找出特定字串元出現次數
a.count('2') # 1








Python - String筆記

字串
a= "abcdefg"
a = 'abcdefg'

字串可直接轉為串列
a[2] # c

擷取索引值2到結尾的字串
a[2:]  # cdefg

擷取索引值2開始到5之前的字串
a[2:5] #cde

擷取跳過1個的字串
a[::2] # aceg

英文大寫
a = a.upper()

英文小寫
a = a.lower()

英文大小寫互換
a = a.swapcase()

開頭大寫
a = a.capitalize()

利用title()讓每個英文單字開頭大寫
a = a.title()

利用split轉換成串列
a = "1,2,3,4,5,6"
x = a.split(",")
print(x) # ['1','2','3','4','5','6']

內插字串
"{},{},{}".format("A","B","C") # A,B,C
"{a},{b},{c}".format(a="1", b="2", c="3") # 123

利用replace()替換字串
a = a.replace(old, new)
a = a.replace(old, new, max)

利用startswith(), endswith()檢查開頭以及結尾的字串元,回傳Boolean
a = 'abcdef'
print(a.startswith("b")) # False
print(a.startswith("a")) # True
print(endswith("e")) # False
print(endswith("f")) # True

利用find(), rfind()找出第一次以及最後一次出現字串元的索引值
a = 'abcdddefghi'
print(a.find('d')) # 3 第一次出現
print(a.rfind('d')) # 5 最後一次出現

利用count()找出特定的字串元出現幾次
a = 'abcdddefghi'
print(a.count('d')) # 3

利用isalnum()檢查是否只有英數
a = 'sdf123423sdfsf'
print(a.isalnum()) # True
a = '111!@#@#'
print(a.isalnum()) # False



Python - Number筆記

整數
a=2

浮點數
a=2.2

加法
a + 1

減法
a - 1

乘法
a * 2

除法
a / 2 

整數除法
a // 2  # 只取整數

取餘數
a % 2

次方
a**2

轉整數
a = 12.345
print (int(a) ) # display 12
print(type(a)) # <type 'int'>

轉浮點數
a = 12
print(float(a)) # diplay 12.0
print(type(a)) # <type 'float'>

轉字串
a = str(2)
print(a) # 2
print(type(a)) # <type 'str'>

Python - Lambda筆記

lambda提供一個匿名函式,可以用完即丟。

舉例個例,我們現在創造一個基數的檢驗器過濾以下串列

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

def even(num):
    return num % 2 == 0

evens = filter(num, mylist)

print(list(evens))

如果我們用lambda的話將會是

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

evens = filter(lambda num:num % 2 == 0 , mylist)

print(list(evens))

用法:
lambda args1, args2, args3... : expression

2017年9月20日 星期三

Java - 內部類別如何使用static 變數

class OutterClass{
    static class InnerClass {
static boolean STATUS = false;
    }
    public void do(){
      InnerClass.STATUS = true;
    }
}

OutterClass oc = new OutterClass();
oc.do();

2017年9月15日 星期五

Quotes

What is best in life?
To crush your enemies.
See them driven before you.
And hear the lamentations of their women.
From Conan the Barbarian



Crom, I have never prayed to you before.
I have no tongue for it. No one, not even you, will remember if we were good men or bad.
Why we fought, or why we died.
All that matters is that two stood against many.
That's what's important!
Valor pleases you, Crom... so grant me one request.
Grant me revenge! And if you do not listen, then to HELL with you!
From Conan the Barbarian



Lo, there do I see my father.
Lo, there do I see My mother, and my sisters, and my brothers.
Lo, there do I see The line of my people
Back to the beginning.
Lo, they do call to me.
They bid me take my place among them.
In the halls of Valhalla
Where the brave May live Forever.
From The 13th Warrior