├── README.md
├── contents.md
├── draft
├── finput.py
└── 關於 class variable.md
├── proof
└── proof1.py
├── questions
├── algorithm
│ ├── subset_sum_problem.md
│ ├── 一個數最後一位是6,移動到首位是原來數的三倍,求這個數.md
│ ├── 使用字串為整數編碼.md
│ ├── 分群問題.md
│ ├── 字串list排序(七橋問題).md
│ ├── 找出所有組合-笛卡爾積問題.md
│ └── 燈泡開關問題.md
├── bs
│ ├── python爬蟲beautifulsoup string抓取問題.md
│ └── 刪除xml文件的指定標籤.md
├── collections
│ ├── Top_K_Frequent_Elements.md
│ └── 會php和python的大神進來幫忙轉換一段代碼.md
├── csv
│ ├── csv模塊生成CSV文件問題(0字頭數字缺失與漢字亂碼).md
│ ├── 如何用python刪除csv文件中的某一列.md
│ └── 操作csv文件寫入順序不對.md
├── data_mining
│ └── python3中有聚類(主要是k-means)的函數或者模塊嗎.md
├── django
│ ├── Django CSRF verification failed 問題.md
│ ├── django如何一個url綁定多個視圖.md
│ ├── django模版中變量引用變量被當作字符串處理而不是變量值.md
│ └── 網頁根目錄改成子目錄後文件如何調用.md
├── dunder
│ └── 自己寫的數據類型使用print無法輸出每個元素.md
├── error
│ ├── Python如何優雅的處理大量異常語句.md
│ └── python如何捕獲中斷.md
├── eval
│ └── 對Python語法字串求值.md
├── file
│ ├── Python如何向文件最開始插入一個字串.md
│ ├── Python如何實現並行查找關鍵字所在的行.md
│ ├── Python處理一個求和運算.md
│ ├── Python處理文本信息.md
│ ├── 使用Python如何按行數拆分文件.md
│ ├── 怎樣合併文檔中有重複部分的行.md
│ ├── 文本格式轉換代碼優化.md
│ └── 用Python實現類似grep的功能.md
├── fp
│ └── sum函數中可以使用條件語句嗎.md
├── ide
│ └── Python能否在保存程序變量情況下啟動控制台.md
├── if
│ └── if 語句的 and or 運算.md
├── import
│ ├── deepcopy無法import.md
│ └── 通過哪個函數能查看Python文件中匯入了哪些模組.md
├── iteration
│ ├── Python 如何合併 list of lists.md
│ ├── Python的list有沒有類似js的find方法.md
│ ├── python中既然生成器表達式比列表解析快, 那為什麼不全部使用生成器表達式.md
│ ├── 一個求質(素)數的編程題.md
│ ├── 如何將列表中的元組整個迭代出來.md
│ ├── 如何從一個複雜的結構中優雅的提取出一列數據.md
│ └── 如何把tuple轉成dictionary.md
├── jinja
│ └── jinja2_macro_caller.md
├── json
│ ├── Python如何合併批量輸出json.md
│ ├── Python如何讀取json中的數據.md
│ ├── 不定深層Json剖析.md
│ ├── 假定有json數據多條記錄,如何根據KEY的值返回一條記錄.md
│ └── 為什麼json的key只能是string.md
├── len
│ └── 怎麼判斷函數或方法多次使用是否需要定義臨時變量.md
├── list
│ ├── list使用append最後為什麼會把前面的元素都修改掉.md
│ ├── python列表取交集.md
│ ├── python生成特定列表格式.md
│ └── 遍歷二維串列最外圈.md
├── math
│ └── Python怎麼通過input獲取矩陣.md
├── object
│ ├── Python 3.x 實例方法的__func__屬性.md
│ ├── Python多重繼承屬性問題.md
│ ├── Python如何通過類方法創建實例方法.md
│ └── Python的staticmethod在什麼情況下用.md
├── others
│ └── 中文按照拼音排序.md
├── pip
│ ├── pip無法在安裝pyinstaller.md
│ └── python代碼怎麼打包.md
├── scope
│ └── 為什麼這兩段 python lambda 出現不同的結果.md
├── sort
│ ├── Python排序問題.md
│ └── sorted函數中key參數的作用原理.md
├── standard_lib
│ ├── Python timeit測量代碼運行時間問題.md
│ ├── Python 獲取文件路徑及文件目錄(__file__ 的使用方法).md
│ ├── Python日期的遞增問題.md
│ ├── os.mkdir和os.makedirs的區別.md
│ ├── tk程序中出現問題.md
│ ├── 一個結構化顯示文件的腳本,迭代是否有問題.md
│ ├── 一個需要傳入參數的python程序如何封裝成可執行文件.md
│ ├── 交換兩個shelve objects.md
│ ├── 如何在python raw_input中使用tab鍵補全.md
│ └── 計算時間差.md
├── star
│ └── 關於python*和**的問題.md
├── string
│ ├── Python中字串的bitwise or怎麼實現.md
│ ├── 如何讓列表所有元素首字母變大寫.md
│ ├── 給定一個字串,回傳所有的可能組合.md
│ └── 轉換一個字串為浮點數會報錯.md
├── styles
│ ├── ebook.css
│ └── website.css
└── virtualenv
│ └── 如何在ubuntu14.04安裝python3.5.md
├── templates
└── basic.md
└── test
└── data1
/README.md:
--------------------------------------------------------------------------------
1 | # Python-QA
2 |
3 | 16年5月份左右,閒來無事開始在技術論壇回答問題,回答久了,也就累積了一些東西.
4 |
5 | 這個 repository 收集了一些我自己感覺比較有趣或實用的問題,每篇都會附上原發問者的問題以及我的回答,問題可能經過潤飾,但我盡量維持原貌,回答的部分也多是個人見解,只是希望做個整理並且與有興趣的人分享.
6 |
7 | 由於問題滿雜的,我只能憑我的直覺將之分類歸檔,目前一共收錄了 81 個問題,大家有興趣的可以參閱[目錄](contents.md).
8 |
9 | 如果你有任何的意見或想要討論,都歡迎你開個 issue 來討論唷!
10 |
11 | 如果你覺得寫得不錯或對你有所啟發,請幫我 **Star** 一下,要關注請 **Watch**,也歡迎大家利用各種平台分享,謝謝你們.
12 |
13 | dokelung @ 2016/07/01, Taipei
14 |
--------------------------------------------------------------------------------
/contents.md:
--------------------------------------------------------------------------------
1 | ## Python-QA 目錄
2 |
3 | ## 內建型態與 collections 容器
4 |
5 | * string
6 | * [Python 中字串的 bitwise or 怎麼實現?](questions/string/Python中字串的bitwise%20or怎麼實現.md)
7 | * [給定一個字串,回傳所有的可能組合](questions/string/給定一個字串,回傳所有的可能組合.md)
8 | * [如何讓列表所有元素首字母變大寫](questions/string/如何讓列表所有元素首字母變大寫.md)
9 | * [轉換一個字串為浮點數會報錯](questions/string/轉換一個字串為浮點數會報錯.md)
10 |
11 | * list
12 | * [遍歷二維串列最外圈](questions/list/遍歷二維串列最外圈.md)
13 | * [list 使用 append 最後為什麼會把前面的元素都修改掉](questions/list/list使用append最後為什麼會把前面的元素都修改掉.md)
14 | * [python 列表取交集](questions/list/python列表取交集.md)
15 | * [python 生成特定列表格式](questions/list/python生成特定列表格式.md)
16 |
17 | * collections
18 | * [會 php 和 Python 的大神進來幫忙轉換一段代碼](questions/collections/會php和python的大神進來幫忙轉換一段代碼.md)
19 | * [Top K Frequent Elements](questions/collections/Top_K_Frequent_Elements.md)
20 |
21 | ## 函式
22 |
23 | * star expression
24 | * [關於 python * 和 ** 的問題](questions/star/關於python*和**的問題.md)
25 |
26 | * variable scope(global/local/nonlocal/closure)
27 | * [為什麼這兩段 python lambda 出現不同的結果](questions/scope/為什麼這兩段%20python%20lambda%20出現不同的結果.md)
28 |
29 | ## 內建函式
30 |
31 | * len
32 | * [怎麼判斷函數或方法多次使用是否需要定義臨時變量](questions/len/怎麼判斷函數或方法多次使用是否需要定義臨時變量.md)
33 |
34 | * sort
35 | * [Python排序問題](questions/sort/Python排序問題.md)
36 | * [sorted函數中key參數的作用原理](questions/sort/sorted函數中key參數的作用原理.md)
37 |
38 | * eval
39 | * [對 Python 語法字串求值](questions/eval/對Python語法字串求值.md)
40 |
41 | ## 控制流程與迭代
42 |
43 | * if(if/elif/else)
44 | * [if 語句的 and or 運算](questions/if/if%20語句的%20and%20or%20運算.md)
45 |
46 | * iteration(iterable/iterater/comprehension/generator/generator expression)
47 | * [如何將列表中的元組整個迭代出](questions/iteration/如何將列表中的元組整個迭代出來.md)
48 | * [一個求質(素)數的編程題](questions/iteration/一個求質(素)數的編程題.md)
49 | * [Python 如何合併 list of lists](questions/iteration/Python%如何合併%20list%20of%20lists.md)(待補充)
50 | * [如何從一個複雜的結構中優雅的提取出一列數據](questions/iteration/如何從一個複雜的結構中優雅的提取出一列數據.md)
51 | * [如何把 tuple 轉成 dictionary](questions/iteration/如何把tuple轉成dictionary.md)
52 | * [Python 的 list 有沒有類似 js 的 find 方法](questions/iteration/Python的list有沒有類似js的find方法.md)
53 | * [python 中既然生成器表達式比列表解析快, 那為什麼不全部使用生成器表達式](questions/iteration/python中既然生成器表達式比列表解析快,%20那為什麼不全部使用生成器表達式.md)
54 |
55 | * functional programming style(map/filter/reduce)
56 | * [sum 函數中可以使用條件語句嗎?](questions/fp/sum函數中可以使用條件語句嗎.md)
57 |
58 | * error handling(exception)
59 | * [Python 如何優雅的處理大量異常語句](questions/error/Python如何優雅的處理大量異常語句.md)
60 | * [python 如何捕獲中斷](questions/error/python如何捕獲中斷.md)
61 |
62 | ## 物件導向程式設計
63 |
64 | * dunder(magic function)
65 | * [自己寫的數據類型使用print無法輸出每個元素](questions/dunder/自己寫的數據類型使用print無法輸出每個元素.md)
66 |
67 | * object(class/object)
68 | * [Python 3.x 實例方法的`__func__`屬性](questions/object/Python%203.x%20實例方法的__func__屬性.md)
69 | * [Python 如何通過類方法創建實例方法](questions/object/Python如何通過類方法創建實例方法.md)
70 | * [Python 的 staticmethod 在什麼情況下用](questions/object/Python的staticmethod在什麼情況下用.md)
71 | * [Python 多重繼承屬性問題](questions/object/Python多重繼承屬性問題.md)
72 |
73 | ## 檔案與資料處理
74 |
75 | * file
76 | * [怎樣合併文檔中有重複部分的行](questions/file/怎樣合併文檔中有重複部分的行.md)
77 | * [Python 處理文本信息](questions/file/Python處理文本信息.md)
78 | * [Python 如何實現並行查找關鍵字所在的行](questions/file/Python如何實現並行查找關鍵字所在的行.md)
79 | * [文本格式轉換代碼優化](questions/file/文本格式轉換代碼優化.md)
80 | * [使用 Python 如何按行數拆分文件](questions/file/使用Python如何按行數拆分文件.md)
81 | * [Python 處理一個求和運算](questions/file/Python處理一個求和運算.md)
82 | * [Python 如何向文件最開始插入一個字串](questions/file/Python如何向文件最開始插入一個字串.md)(待補充)
83 | * [用 Python 實現類似 grep 的功能](questions/file/用Python實現類似grep的功能.md)
84 |
85 | * json
86 | * [為什麼 json 的 key 只能是 string?](questions/json/為什麼json的key只能是string.md)
87 | * [Python 如何合併批量輸出 json](questions/json/Python如何合併批量輸出json.md)
88 | * [Python 如何讀取 json 中的數據](questions/json/Python如何讀取json中的數據.md)
89 | * [不定深層 Json 剖析](questions/json/不定深層Json剖析.md)
90 | * [假定有 json 數據多條記錄,如何根據 KEY 的值返回一條記錄](questions/json/假定有json數據多條記錄,如何根據KEY的值返回一條記錄.md)
91 |
92 | * cvs
93 | * [csv 模塊生成 CSV 文件問題(0字頭數字缺失與漢字亂碼)](questions/csv/csv模塊生成CSV文件問題(0字頭數字缺失與漢字亂碼).md)
94 | * [操作 csv 文件寫入順序不對](questions/csv/操作csv文件寫入順序不對.md)
95 | * [如何用 python 刪除 csv 文件中的某一列](questions/csv/如何用python刪除csv文件中的某一列.md)
96 |
97 | ## 模組與套件
98 |
99 | * import
100 | * [通過哪個函數能查看 Python 文件中匯入了哪些模組](questions/import/通過哪個函數能查看Python文件中匯入了哪些模組.md)
101 | * [deepcopy 無法 import](questions/import/deepcopy無法import.md)
102 |
103 | * standard library
104 | * [os.mkdir 和 os.makedirs 的區別](questions/standard_lib/os.mkdir和os.makedirs的區別.md)
105 | * [tk 程序中出現問題](questions/standard_lib/tk程序中出現問題.md)
106 | * [計算時間差](questions/standard_lib/計算時間差.md)
107 | * [Python timeit 測量代碼運行時間問題](questions/standard_lib/Python%20timeit測量代碼運行時間問題.md)
108 | * [Python 日期的遞增問題](questions/standard_lib/Python日期的遞增問題.md)
109 | * [一個需要傳入參數的 python 程序如何封裝成可執行文件](questions/standard_lib/一個需要傳入參數的python程序如何封裝成可執行文件.md)
110 | * [一個結構化顯示文件的腳本,迭代是否有問題](questions/standard_lib/一個結構化顯示文件的腳本,迭代是否有問題.md)
111 | * [如何在 python raw_input 中使用 tab 鍵補全](questions/standard_lib/如何在python%20raw_input中使用tab鍵補全.md)
112 | * [交換兩個 shelve objects](questions/standard_lib/交換兩個shelve%20objects.md)
113 | * [Python 獲取文件路徑及文件目錄(`__file__` 的使用方法)](questions/standard_lib/Python%20獲取文件路徑及文件目錄(__file__%20的使用方法).md)
114 |
115 | * pip
116 | * [pip 無法在安裝 pyinstaller](questions/pip/pip無法在安裝pyinstaller.md)
117 | * [Python 代碼怎麼打包](questions/pip/python代碼怎麼打包.md)
118 |
119 | * others
120 | * [中文按照拼音排序](questions/others/中文按照拼音排序.md)
121 |
122 | ## WEB
123 |
124 | * django
125 | * [django 如何一個 url 綁定多個視圖](questions/django/django如何一個url綁定多個視圖.md)
126 | * [django 模版中變量引用變量被當作字符串處理而不是變量值](questions/django/django模版中變量引用變量被當作字符串處理而不是變量值.md)
127 | * [網頁根目錄改成子目錄後文件如何調用](questions/django/網頁根目錄改成子目錄後文件如何調用.md)
128 | * [Django CSRF verification failed 問題](questions/django/Django%20CSRF%20verification%20failed%20問題.md)
129 |
130 | * flask/jinja
131 | * [jinja2 macro caller](questions/jinja/jinja2_macro_caller.md)
132 |
133 | ## 爬蟲
134 |
135 | * beautiful soup
136 | * [刪除 xml 文件的指定標籤](questions/bs/刪除xml文件的指定標籤.md)
137 | * [Python 爬蟲 beautifulsoup string 抓取問題](questions/bs/python爬蟲beautifulsoup%20string抓取問題.md)
138 |
139 | ## 演算法與科學計算
140 |
141 | * algorithm
142 | * [Subset-Sum Problem](questions/algorithm/subset_sum_problem.md)
143 | * [字串 list 排序(七橋問題)](questions/algorithm/字串list排序(七橋問題).md)
144 | * [使用字串為整數編碼](questions/algorithm/使用字串為整數編碼.md)
145 | * [分群問題](questions/algorithm/分群問題.md)
146 | * [找出所有組合-笛卡爾積問題](questions/algorithm/找出所有組合-笛卡爾積問題.md)
147 | * [燈泡開關問題](questions/algorithm/燈泡開關問題.md)
148 | * [一個數最後一位是 6,移動到首位是原來數的三倍,求這個數](questions/algorithm/一個數最後一位是6,移動到首位是原來數的三倍,求這個數.md)
149 |
150 | * math
151 | * [Python 怎麼通過 input 獲取矩陣](questions/math/Python怎麼通過input獲取矩陣.md)
152 |
153 | ## 大數據與機器學習
154 |
155 | * data mining
156 | * [python3 中有聚類(主要是k-means)的函數或者模塊嗎](questions/data_mining/python3中有聚類(主要是k-means)%20的函數或者模塊嗎.md)
157 |
158 | ## Python 實作與開發環境
159 |
160 | * IDE (集成開發環境)
161 | * [Python 能否在保存程序變量情況下啟動控制台](questions/ide/Python能否在保存程序變量情況下啟動控制台.md)
162 |
163 | * virtualenv
164 | * [如何在 ubuntu14.04 安裝 python3.5](questions/virtualenv/如何在ubuntu14.04安裝python3.5.md)
165 |
--------------------------------------------------------------------------------
/draft/finput.py:
--------------------------------------------------------------------------------
1 | # author: dokelung
2 |
3 | import re
4 | from ast import literal_eval
5 | from functools import partial
6 |
7 |
8 | class InputDoesNotMatchFStr(Exception): pass
9 | class TypeConvertError(Exception): pass
10 | class InputCountNotInRange(Exception): pass
11 |
12 |
13 | FORMAT_SPECIFIER = {
14 | '%a': literal_eval,
15 | '%d': int,
16 | '%f': float,
17 | '%o': partial(int, base=8),
18 | '%s': str,
19 | '%x': partial(int, base=16),
20 | }
21 |
22 |
23 | def finput(prompt='', fstr='%s', expand_fsp=None,
24 | whitespace=False,
25 | escape_parenthesis=True):
26 | """format input
27 | """
28 | fsp = FORMAT_SPECIFIER
29 | if expand_fsp is not None:
30 | fsp.update(expand_fsp)
31 | if escape_parenthesis:
32 | rstr = fstr.replace('(', '\(').replace(')', '\)')
33 | else:
34 | rstr = fstr
35 | regex = '(.+)' if whitespace else '(\S+)'
36 | for sp, typ in fsp.items():
37 | rstr = rstr.replace(sp, regex)
38 | types = []
39 | for idx, c in enumerate(fstr):
40 | pattern = fstr[idx:idx+2]
41 | if pattern in fsp:
42 | types.append(fsp[pattern])
43 | pure_input = input(prompt)
44 | mobj = re.match(rstr, pure_input)
45 | if mobj:
46 | try:
47 | return tuple(typ(value) for value, typ in zip(mobj.groups(), types))
48 | except Exception as err:
49 | raise TypeConvertError(err)
50 | else:
51 | msg = 'input does not match format string "{}"'
52 | raise InputDoesNotMatchFStr(msg.format(fstr))
53 |
54 |
55 | def minput(prompt='', typ=str, sep=None, min=1, max=100000):
56 | """multiple input
57 | """
58 | pure_input = input(prompt)
59 | try:
60 | if sep is None:
61 | values = tuple(typ(item) for item in pure_input.split())
62 | else:
63 | values = tuple(typ(item) for item in pure_input.split(sep))
64 | except Exception as err:
65 | raise TypeConvertError(err)
66 | if len(values) < min or len(values) > max:
67 | msg = 'input count {} is not in range [{}, {}]'
68 | raise InputCountNotInRange(msg.format(len(values), min, max))
69 | return values
70 |
71 |
72 | if __name__ == '__main__':
73 | #res = finput('>>> ', fstr='%s, *%d, *%f')
74 | #print(res)
75 | res = minput('>>> ', typ=int, min=1, max=3)
76 | print(res)
77 |
--------------------------------------------------------------------------------
/draft/關於 class variable.md:
--------------------------------------------------------------------------------
1 | 首先你寫在 class 裡面但不在 method 裡面的 variable 是 class variable
2 |
3 | 這個 variable 對於該類別及其子類別的類別和實體而言都只有一份, 看下面這個例子:
4 |
5 | ```python
6 | class A:
7 | _dict = {}
8 | def __init__(self):
9 | self._dict.update({'a':'a'})
10 |
11 | class B(A):
12 |
13 | def __init__(self):
14 | self._dict.update({'b':'b'})
15 |
16 | if __name__=='__main__':
17 | a = A()
18 | b = B()
19 | print(a._dict)
20 | print(b._dict)
21 | print(A._dict)
22 | print(B._dict)
23 | ```
24 |
25 | ```
26 | {'b': 'b', 'a': 'a'}
27 | {'b': 'b', 'a': 'a'}
28 | {'b': 'b', 'a': 'a'}
29 | {'b': 'b', 'a': 'a'}
30 | ```
31 |
32 | 這裡你看到的所有 `_dict` 都參考到同一個物件
33 |
34 | 但是下面這個情況就不太一樣了:
35 |
36 | ```python
37 | class A:
38 | _dict = {}
39 | def __init__(self):
40 | self._dict = {}
41 | self._dict.update({'a':'a'})
42 |
43 | class B(A):
44 |
45 | def __init__(self):
46 | self._dict.update({'b':'b'})
47 |
48 | class C(A):
49 |
50 | def __init__(self):
51 | super().__init__()
52 | self._dict.update({'c':'c'})
53 |
54 | if __name__=='__main__':
55 | a = A()
56 | b = B()
57 | c = C()
58 | print(a._dict)
59 | print(b._dict)
60 | print(c._dict)
61 | print(A._dict)
62 | print(B._dict)
63 | print(C._dict)
64 | ```
65 |
66 | ```
67 | {'a': 'a'}
68 | {'b': 'b'}
69 | {'c': 'c', 'a': 'a'}
70 | {'b': 'b'}
71 | {'b': 'b'}
72 | {'b': 'b'}
73 | ```
74 |
75 | 咦?! 怎麼變成這樣了呢? 這邊如果搞懂的話就全盤皆通了:
76 |
77 | 首先 A 及其子類別都共有一個 class variable, 叫做 `_dict`
78 |
79 | 當我們初始化 a 的時候, `self._dict = {}` 會讓 a 裡面新產生一個變數叫做 `_dict`, 因為這次 `self._dict` 出現在等號左邊。注意! 這裡我們已經有兩個不同的東西了, 一個是 class variable `_dict`, 另一個是 instance variable `_dict`, 從此以後, a 裡面拿 `self._dict` 的時候就都是拿到 instance variable 了!
80 |
81 | 接著看 b, b 並沒有讓 variable 出現在等號左邊, 所以沒有建立新的變數, 現在 b 中的 `self._dict` 仍然指涉 class variable `_dict`
82 |
83 | c 的情況就比較特別了, 藉由 `super` 他呼叫了 A 的 `__init__`, 上面說過了, 這會讓 c 中新建立一個 instance variable `_dict`, 這個變數因為 `A.__init__` 和 `C.__init__`, 所以會有兩個鍵值對
84 |
85 |
86 | 最後 `A._dict`, `B._dict` 和 `C._dict` 就很容易理解了, 他們都是參考到同一個 class variable, 所以值都一樣。
87 |
88 | ### 小結
89 |
90 | 讓我們來整理一下, 這邊一共會有 3 個 `_dict`:
91 |
92 | 1. class variable `_dict`
93 | 2. instance variable of a
94 | 3. instance variable of c
95 |
--------------------------------------------------------------------------------
/proof/proof1.py:
--------------------------------------------------------------------------------
1 | """
2 | prove this repository is a python project
3 | """
4 |
5 | def prove():
6 | print 'prove!'
7 |
--------------------------------------------------------------------------------
/questions/algorithm/subset_sum_problem.md:
--------------------------------------------------------------------------------
1 | # Subset-Sum Problem
2 |
3 | ## 問題
4 |
5 | 給定一個值, 如100,給定一個 list,從 list 中挑選出 N 個元素,這 N 個元素相加也是 100,得到一種結果就行.
6 |
7 | 舉例: 給定一個 list:
8 |
9 | ```python
10 | lst = [ 99.1 , 92.2 , 60 , 50 ,
11 | 49.5 , 45.7 , 25.1 , 20 ,
12 | 17.4 , 13 , 10 , 7 , 2.1 , 2 , 1 ]
13 | ```
14 |
15 | 找到和為100的數組元素:
16 |
17 | ```
18 | [ 60 , 20 , 10 , 7 , 2 , 1 ]
19 | ```
20 |
21 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005696393/a-1020000005702007), by [輕逐微風](https://segmentfault.com/u/hare)
22 |
23 | ## 回答
24 |
25 | 來個 Python 版的:
26 |
27 | ```python
28 | def subsetsum(elements, target):
29 | if target==0:
30 | return True, []
31 | elif not elements or target < 0:
32 | return False, None
33 |
34 | result, subset = subsetsum(elements[:-1], target-elements[-1])
35 | return (True, subset + [elements[-1]]) if result else subsetsum(elements[:-1], target)
36 | ```
37 |
38 | 思路很簡單,當我要問 `elements` 是否能加出 `target` 時,只有兩種可能:
39 |
40 | 1. 我要使用 `element[-1]` 才能加出 `target` -> 我要能夠使用 `elements[:-1]` 加出 `target-elements[-1]` 才行
41 | 2. 我不需要使用 `element[-1]` 就能加出 `target` -> 我要能夠使用 `elements[:-1]` 加出 `target` 才行
42 |
43 | boundary condition 是:
44 |
45 | 1. 當 `target` 為 `0` 時,代表我什麼都不用就能加出來,所以 `return True, []`
46 | 2. 當 `elements` 為空或是 `target` 為負值時,代表永遠都加不出來了,所以 `return False, None`
47 |
48 | **測試**:
49 |
50 | ```python
51 | elements = [99.1, 92.2, 60, 50, 49.5, 45.7, 25.1, 20, 17.4, 13, 10, 7, 2.1, 2, 1]
52 | target = 100
53 | result, subset = subsetsum(elements, target)
54 | print(result, subset)
55 | ```
56 |
57 | **結果**:
58 |
59 | ```python
60 | True [60, 20, 10, 7, 2, 1]
61 | ```
62 |
63 | ### 衍生問題
64 |
65 | 題外話,看到這個題目覺得超熟悉,如果還要考慮到解的速度等等會更有趣。
66 |
67 | 曾經做過這方面的研究,我提出一個變形的問題,大家可以思考看看:
68 |
69 |
70 | >我們今天給定一個整數(代表負數也 ok )的 多重集 (多重集就是一個集合,但是允許元素重複出現),叫做 ` elements`,在給定另外一個整數的 多重集 叫做 `targets`,試問是否存在若干個 子多重集,每個 子多重集 的元素和恰好有一個在 `targets` 中對應的 target。
71 |
72 |
73 | 定義看不懂沒差,我舉個例子:
74 |
75 | ```
76 | elements = (1,4,6,4,1)
77 | targets = (5,10,1)
78 | ```
79 |
80 | 這個例子是有解的:
81 |
82 | ```
83 | (1,4) -> 5
84 | (4,6) -> 10
85 | (1) -> 1
86 | ```
87 |
88 | 注意,每個在 `elements` 中的元素只能被使用一次!
89 |
--------------------------------------------------------------------------------
/questions/algorithm/一個數最後一位是6,移動到首位是原來數的三倍,求這個數.md:
--------------------------------------------------------------------------------
1 | # 一個數最後一位是6,移動到首位是原來數的三倍,求這個數
2 |
3 | ## 問題
4 |
5 | 題目:一個數最後一位是6,移動到首位是原來數的三倍,求這個數
6 | 要求:速度最優
7 |
8 | 大神們快來踴躍探討~~~
9 |
10 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000006135723/a-1020000006139815), by [prolifes](https://segmentfault.com/u/prolifes)
11 |
12 | ## 回答
13 |
14 | ### 各路大神的回答
15 |
16 | #### [citaret](https://segmentfault.com/u/citaret) 的回答
17 |
18 | 先贴上一版:
19 |
20 | ```python
21 | x = 6
22 | xs = []
23 | while True:
24 | xs.append(x // 3)
25 | x = x % 3 * 10 + x // 3
26 | if x == 6:
27 | print ''.join(str(x) for x in xs)
28 | break
29 | ```
30 |
31 | 输出:
32 |
33 | ```
34 | 2068965517241379310344827586
35 | ```
36 |
37 | 原理是手算,把每次得到的商的末位补到被除数的最后,然后继续除法,直到末位为6,且余数为0停止。
38 |
39 | #### [hsfzxjy](https://segmentfault.com/u/hsfzxjy) 的回答
40 |
41 | 由於數學公式的使用請大家前往問題原出處查看 [回答](https://segmentfault.com/q/1010000006135723/a-1020000006139815)
42 |
43 | ### 我的回答
44 |
45 | 下午看到這題的時候就有了個想法, 手邊沒電腦只好等到現在...
46 |
47 | 後來看到 @citaret 的答案就發現剛好是反向的想法, 下面是我的作法:
48 |
49 | ```python
50 | x = 6
51 | last_carry = 0
52 | result = 6
53 | radix = 10
54 |
55 | while True:
56 | c1, x = divmod(x * 3, 10)
57 | c2, x = divmod(x + last_carry, 10)
58 | last_carry = c1 + c2
59 |
60 | if x==6 and last_carry==0:
61 | return result
62 |
63 | result += (x * radix)
64 | radix *= 10
65 | ```
66 |
67 | 想法就剛好是反過來, 我一步一步地乘上去
68 |
69 | * 每次把 `x` 乘 3
70 | * 把個位數加上 `last_carry` 就是下次的 `x`
71 | * 把十位數的進位留下來當作下次的 `last_carry`
72 | * 做到 `x==6` 且無進位的時候
73 |
74 | 用圖來思考長這樣:
75 |
76 | ```
77 | 0 <-- last carry
78 | \
79 | 1 8 = 6 X 3
80 | \ (0 + 8 = 8)
81 | 2 4 = 8 X 3
82 | \ (1 + 4 = 5)
83 | 1 5 = 5 X 3
84 | ...
85 | ```
86 |
87 | 用 `timeit` 稍微測了一下時間(各運行 1000000 次), 共測三次:
88 |
89 | ```
90 | # first
91 | dokelung: 17.301649590954185
92 | citaret: 18.24915363173932
93 |
94 | # second
95 | dokelung: 19.257807812653482
96 | citaret: 17.994877750985324
97 |
98 | # third
99 | dokelung: 17.0617663115263
100 | citaret: 18.355605391785502
101 | ```
102 |
103 | 時間看起來差不多, 不過我自認為代碼沒有很漂亮...
104 |
--------------------------------------------------------------------------------
/questions/algorithm/使用字串為整數編碼.md:
--------------------------------------------------------------------------------
1 | # 使用字串為整數編碼
2 |
3 | ## 問題
4 |
5 | 網上看到類似的算法,不過實現是C++:
6 |
7 | ```c++
8 | private static void alphaseq0(int n, String alphabet, StringBuffer buf) {
9 | int len = alphabet.length();
10 |
11 | if (n >= len) {
12 | alphaseq0(n/len - 1,alphabet,buf);
13 | n = n % len;
14 | }
15 |
16 | buf.append(alphabet.charAt(n));
17 | }
18 | ```
19 |
20 | 本題的題意是:給定一個 **整數** `n` 和 **字元集** alphabet, return 一個對應的 string
21 |
22 | 而對應的規則如下:
23 |
24 | ```
25 | (假設我們的字元集是英文字母AZ,也就是說這些字元是可以用來代表給定的整數的)
26 |
27 | 1 -> A
28 | 2 -> B
29 | 3 -> C
30 | ...
31 | 26 -> Z
32 | 27 -> AA
33 | ...
34 | 52 -> AZ
35 | ...
36 | m -> ZZA
37 | ...
38 | n -> ZZZ
39 | n+1 -> AAAA
40 | ```
41 |
42 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005932045/a-1020000005933237), by [jiangbingo](https://segmentfault.com/u/jiangbingo)
43 |
44 | ## 回答
45 |
46 | 這題乍看簡單,其實後來仔細研究花了我不少時間(也許是我頭腦簡單...)
47 |
48 | 我馬上想到了 `itertools.product`,我可以很簡單地去生出足夠多的 string,再從中挑選第 `n` 個:
49 |
50 | ```python
51 | from itertools import product
52 |
53 | def get_alphaseqs(n, alphabet):
54 | """ get first n alphaseq """
55 | results = []
56 | for l in range(1, len(alphabet)+1):
57 | results.extend([''.join(p) for p in product(alphabet, repeat=l)])
58 | if len(results) >= n:
59 | return results[:n]
60 | return None
61 | ```
62 |
63 | `alphabet` 的變化數量如果不夠會 `return None`
64 |
65 | 所以如果我想要得到 `n=3000` 對應的 string;
66 |
67 | ```python
68 | alphabet = 'abcdefghijklmnopqrstuvwxyz'
69 | string = get_alphaseqs(3000, alphabet)[-1]
70 | ```
71 |
72 | 但是這樣做的問題是: 非常耗時,理由很簡單,我產生了太多不需要的東西。對照樓主給的 C++ 範例,我應該直接生成對應的 string 就好
73 |
74 | 那該怎麼做呢? 我想起了進位轉換,這個問題不就是進位轉換的問題嗎?
75 |
76 | 比如說我們看一個 10 進位轉 16 進位的例子:
77 |
78 | ```
79 | 10進位 分解 16進位
80 | ---------------------------------------
81 | 1 = 0*(16**1) + 1*(16**0) = 1
82 | 16 = 1*(16**1) + 0*(16**0) = 10
83 | 31 = 1*(16**1) + 15*(16**0) = 1F
84 | ```
85 |
86 | 以 31 為例子,我們先除一次 16 得到餘數 15,就可以查出他的第一位符號 `F`,接著再除第二次得到餘數 `1` 也可以查出他的第二位符號 `1`。
87 |
88 | 我們現在的對應轉換問題不就是: 要求把 10 進位 ( 10 個符號 0-9 ) 轉成 26 進位 (26 個符號 A-Z) 嗎?
89 |
90 | 那還不簡單,仿照進位轉換的作法,我只要不停連除字符集的長度 `len(alphabet)` (`len(alphabet)` 進位) 就可以查詢的到每一位的對應符號了。
91 |
92 | 可惜問題沒有那麼簡單,大家有注意到嗎? 這個對應會從 1 開始而不是 0,少了這個 0 的對應,一切的規則似乎被打亂了許多,對於 26 進位而言,十進位的 `26` 應該是要進位了,但在這裡不是,`26` 對應的是單一的符號 `Z`,我們必須找出規則來處理除 26 餘 0 的狀況。
93 |
94 | 於是我開始觀察規則:
95 |
96 | ```
97 | 十進位整數 1 2 ... 26 27 ... 52
98 | 對應字串 A B ... Z AA ... AZ
99 | 除以 26 之商 0 0 ... 1 1 ... 2
100 | 除以 26 之餘 1 2 ... 0 1 ... 0
101 | ```
102 |
103 | 我們會發現:
104 |
105 | 1. 如果不是整除的話(餘數不為零),那規則跟進位轉換沒兩樣,可以直接用餘數查詢對應的符號,並且用 `商` 作被除數來做下一次的除法
106 | 2. 如果整除(餘數為零),我們則必須取最後一個符號,且下一次的除法要用 `(商-1)` 來當被除數做下一次的除法
107 |
108 | 根據這個規則我寫了兩個版本的 function,一個是如同 C++ 範例碼使用 recursive 的作法:
109 |
110 | ```python
111 | def int2alphaseq(n, alphbet):
112 | """ change int to alphaseq """
113 | buf = ''
114 | if n==0:
115 | return buf
116 | if n >= len(alphbet):
117 | k = n % len(alphbet)
118 | if k==0:
119 | buf = int2alphaseq(n//len(alphbet)-1, alphbet)
120 | else:
121 | buf = int2alphaseq(n//len(alphbet), alphbet)
122 | n = k
123 | return buf + alphbet[n-1]
124 | ```
125 |
126 | 另一個是用 iterate 的方式:
127 |
128 | ```python
129 | def int2alphaseqiter(n, alphbet):
130 | """ change int to alphaseq """
131 | buf = ''
132 | while n >= len(alphabet):
133 | n, k = divmod(n, len(alphabet))
134 | if k==0:
135 | n -= 1
136 | buf = alphabet[k-1] + buf
137 | if n==0:
138 | return buf
139 | else:
140 | return alphabet[n-1] + buf
141 | ```
142 |
143 | 只要比較這三個 function 轉出來的 string 一不一樣就可以確認正確性。
144 |
145 | 如果樓主發現跟原題想要的不一樣或是大家有任何意見,歡迎在評論告訴我!
146 |
--------------------------------------------------------------------------------
/questions/algorithm/分群問題.md:
--------------------------------------------------------------------------------
1 | # 分群問題
2 |
3 | 某一行中的字母,如果有在其他行也出現,則將他們合併為一行。
4 |
5 | 例如:
6 |
7 | ```
8 | A B
9 | C A
10 | D C
11 | E F
12 | N G
13 | C N
14 | ```
15 |
16 | 結果:
17 |
18 |
19 | ```
20 | A B C D N G
21 | E F
22 | ```
23 |
24 | ## 問題
25 |
26 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005979723/a-1020000005980272), by [biopython](https://segmentfault.com/u/biopython)
27 |
28 | ## 回答
29 |
30 | 這種 partition 的問題可以用 graph 來解決, 但我在這裡不想要用 graph, 所以改用兩個 dictionary 來替代:
31 |
32 | ```python
33 | char2id = {}
34 | id2charset = {}
35 |
36 | def getcharset(c):
37 | try:
38 | return id2charset[char2id[c]]
39 | except:
40 | return None
41 |
42 | def newcharset(chars):
43 | newset = set(chars)
44 | return newset
45 |
46 | def merge(charset1, charset2):
47 | if id(charset1)==id(charset2):
48 | return
49 | charset1 |= charset
50 | for c in charset2:
51 | char2id[c] = id(charset1)
52 | id2charset.pop(id(charset2))
53 |
54 | with open('test') as reader:
55 | for line in reader:
56 | chars = line.strip().split()
57 | newset = newcharset(chars)
58 | id2charset[id(newset)] =newset
59 |
60 | for c in chars:
61 | charset = getcharset(c)
62 | if charset:
63 | merge(newset, charset)
64 | else:
65 | char2id[c] = id(newset)
66 |
67 | with open('report', 'w') as writer:
68 | for id, charset in id2charset.items():
69 | print(' '.join(charset), file=writer)
70 | ```
71 |
72 | 上述代碼可以完成工作不過只保證分群的正確而不保證順序。
73 |
74 | 測試資料 `test`:
75 |
76 | ```
77 | A B
78 | C A
79 | D C
80 | E F
81 | N G
82 | C N
83 | X Y
84 | F P
85 | P Q
86 | X Z
87 | ```
88 |
89 | 結果:
90 |
91 | ```
92 | P E Q F
93 | X Y Z
94 | B D C G N A
95 | ```
96 |
97 | 檢查正確性的方法很簡單, 因為這種合併的規則會導致最後每個字母只會在整個文件中出現一次(出現兩次以上代表有該 merge 的沒 merge)
98 |
99 | 下面是簡單地用 `Counter` 寫了一個檢查的 script:
100 |
101 | ```python
102 | from collections import Counter
103 |
104 | with open('report', 'r') as reader:
105 | ct = Counter()
106 | for line in reader:
107 | ct += Counter(line.strip().split())
108 |
109 | for item, count in ct.most_common():
110 | if count <= 1:
111 | break
112 | print(item, count)
113 | ```
114 |
--------------------------------------------------------------------------------
/questions/algorithm/字串list排序(七橋問題).md:
--------------------------------------------------------------------------------
1 | # 字串 list 組排序(七橋問題)
2 |
3 | ## 問題
4 |
5 | 給定字串 list,要求進行判斷是否存在以下序列
6 |
7 | 前一個字串末尾字元等於後一個字串首字元。
8 |
9 | 例如:
10 |
11 | ```python
12 | { "ab" , "de" , "bc" , "cd" } #此字串list滿足條件
13 | { "ab" , "bc" , "cd" , "fg" } #此字串list不滿足條件
14 | ```
15 |
16 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005152540/a-1020000005595508), by [nbandroid](https://segmentfault.com/u/nbandroid)
17 |
18 | ## 回答
19 |
20 | [ted](https://segmentfault.com/u/ted) 大的算法非常完整,就算法的部份可以參考他的說法
21 |
22 | >其實就是七橋問題,把一個字符串視作從首字母到尾字母的有向鏈接,求特定字符串集合能不能一次不重複走完。從圖論的角度來看,由於可能存在不連通的子圖,所以不能簡單地用各個節點的度來判斷,但節點的度可以用來快速排除不符合的集合。
23 | >所以很簡單,如果集合中存在這樣的序列,必然是以下情況之一:
24 | >
25 | >循環。所有節點的出度等於入度;
26 | >
27 | >不循環。除了某兩個節點外,其他所有節點的出度等於入度。
28 | >
29 | >如果符合上面的條件,那麼還要跑一次 dfs 看能不能單路徑遍歷所有邊。
30 | >如果要排序,那就是 dfs 出來的那條路徑。
31 | > by ted
32 |
33 | 以下是我用 Python 實現的一個範例(`algo.py`):
34 |
35 | 首先是一個基礎的 `dfs` function,不需要做任何事前確認就能夠正確地辨識出 string list 是否符合條件:
36 |
37 | ```python
38 | def dfs(prestr, str_lst):
39 | for idx, string in enumerate(str_lst):
40 | if not prestr or string[0] == prestr[-1]:
41 | if len(str_lst)==1:
42 | return [string]
43 | # print(string, str_lst[:idx] + str_lst[idx+1:]) # 反註解掉此行用以觀察搜尋的過程
44 | result = dfs(string, str_lst[:idx] + str_lst[idx+1:])
45 | if result:
46 | return [string] + result
47 | return None
48 | ```
49 |
50 | 但是有了事前檢查可以減少不必要的 `dfs`。
51 |
52 | 用來作提前檢查的 `pre_check`:
53 |
54 | ```python
55 | import collections
56 |
57 | def pre_check(str_lst):
58 |
59 | heads = (string[0] for string in str_lst)
60 | tails = (string[-1] for string in str_lst)
61 | first_head = None
62 | last_tail = None
63 |
64 | head_counter = collections.Counter(heads)
65 | tail_counter = collections.Counter(tails)
66 |
67 | sub_counter = head_counter-tail_counter
68 | if len(sub_counter) > 1:
69 | return False, None, None
70 | elif len(sub_counter)==1:
71 | first_head = list(sub_counter)
72 |
73 | sub_counter = tail_counter-head_counter
74 | if len(sub_counter) > 1:
75 | return False
76 | elif len(sub_counter)==1:
77 | last_tail = list(sub_counter)
78 |
79 | return True, first_head, last_tail
80 | ```
81 |
82 | 有作 `pre_check` 的 完整版 `check`:
83 |
84 | ```python
85 | def check(str_lst):
86 | result, first_head, last_tail = pre_check(str_lst)
87 | if result:
88 | if (first_head is None and last_tail is None) or (first_head and last_tail):
89 | return dfs(None, str_lst)
90 | else:
91 | return None
92 | else:
93 | return None
94 | ```
95 |
96 | 測試結果:
97 |
98 | ```python
99 | >>> from algo import dfs, check
100 | >>> s1 = ["ab", "de", "bc", "cd"]
101 | >>> dfs(None, s1)
102 | ['ab', 'bc', 'cd', 'de']
103 | >>> check(s1)
104 | ['ab', 'bc', 'cd', 'de']
105 | >>> s2 = ["ab","bc","cd","fg"]
106 | >>> dfs(None, s2) # 回傳 None 代表 s2 並不符合條件
107 | >>> check(s2) # 回傳 None 代表 s2 並不符合條件
108 | >>> s3 = ["gh","ab","ef","hi","bc","cd","fg","de"] # 無循環
109 | >>> dfs(None, s3)
110 | ['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi']
111 | >>> check(s3)
112 | ['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi']
113 | >>> s4 = ["gh","ab","ef","ha","bc","cd","fg","de"] # 循環
114 | >>> dfs(None, s4)
115 | ['gh', 'ha', 'ab', 'bc', 'cd', 'de', 'ef', 'fg']
116 | >>> check(s4)
117 | ['gh', 'ha', 'ab', 'bc', 'cd', 'de', 'ef', 'fg']
118 | ```
119 |
--------------------------------------------------------------------------------
/questions/algorithm/找出所有組合-笛卡爾積問題.md:
--------------------------------------------------------------------------------
1 | # 找出所有組合-笛卡爾積問題
2 |
3 | ## 問題
4 |
5 | 結構數據是這樣的:
6 |
7 | 
8 |
9 | 要求按照這樣的公式:
10 |
11 | ```
12 | 時間詞+地方詞+動詞+等級+名詞+價格詞;
13 | ```
14 |
15 | 比如
16 |
17 | ```
18 | 2016年深圳大鵬新區給健康全身檢查要多少錢
19 | ```
20 |
21 | 就是按照這樣的公式組合出來的關鍵詞
22 |
23 | 那麼有什麼辦法用最短的辦法來實現,我下面是我的算法,用 pandas 的算法:
24 |
25 | ```python
26 | for times in df[df["時間詞"].notnull()]["時間詞"]:
27 | for area in df[df["地方詞"].notnull()]["地方詞"]:
28 | for dong in df[df["動詞"].notnull()]["動詞"]:
29 | for leave in df[df["等級"].notnull()]["等級"]:
30 | for name in df[df["名詞"].notnull()]["名詞"]:
31 | for price in df[df["價格詞"].notnull()]["價格詞"]:
32 | data = (times+area+dong+leave+name+price)
33 | ```
34 |
35 | 但是這樣的代碼太不優雅,而且封裝成函數太難~
36 | 我想要的效果是這樣的, 比如我寫一個公式:
37 |
38 | ```python
39 | cols = ["時間詞","地方詞","動詞","等級","名詞","價格詞"]
40 | #或是
41 | cols = ["地方詞","動詞","等級","名詞","價格詞"]
42 | ```
43 |
44 | 然後把這個列表傳入一個函數中,就可以得出我上面的效果~
45 | 這個要如何實現?
46 |
47 | -----
48 |
49 | 補充一下,如果看不懂提問的人可以這樣理解這個題目, 我有 3 個 list:
50 |
51 | ```python
52 | a = ["1","2","3","4","5"]
53 | b = ["a","b","c"]
54 | c = ["A","B"]
55 | ```
56 |
57 | 我要這樣的組合: `a` 中的每個元素和 `b`, `c` 中的每個元素都進行組合
58 | 這個一個很簡單的多重循環就可以解決:
59 |
60 | ```python
61 | for A in a:
62 | for B in b:
63 | for C in c:
64 | print (A+B+C)
65 | ```
66 |
67 | 這當然很簡單,但是假如我有 10000 個這樣的列表要重組?
68 | 難不成要手工複製黏貼每個循環 10000 次?這顯然不太現實
69 |
70 | 在 python 中有沒有比較好的函數或是比較好的方法來實現這個東西?
71 |
72 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005980173/a-1020000005980906), by [jqlts1](https://segmentfault.com/u/jqlts1)
73 |
74 | ## 回答
75 |
76 | 在我回答之前已經有高手給了這樣的答案:
77 |
78 | ```python
79 | import itertools
80 | for x in itertools.product([1,2,3,4],[2,3,4],[1,1,2,2,3,3]):
81 | print x
82 | ```
83 |
84 | 沒錯, `itertools` 裡面的 `product` 就是完成笛卡爾積的神兵利器!
85 |
86 | -----
87 |
88 | 至於我....
89 |
90 | 我來表演 **重複發明輪子**:
91 |
92 | 一個用 iteration 的版本:
93 |
94 | ```python
95 | def product(*iterables):
96 | START = 0
97 | END = 1
98 |
99 | se_idxs = [(0, len(iterable)) for iterable in iterables]
100 | curr_idxs = [0 for iterable in iterables]
101 |
102 | def next():
103 | curr_idxs[-1] += 1
104 | for k in reversed(range(len(iterables))):
105 | if curr_idxs[k]==se_idxs[k][END]:
106 | if k==0:
107 | return False
108 | curr_idxs[k] = 0
109 | curr_idxs[k-1] += 1
110 | else:
111 | break
112 | return True
113 |
114 | while True:
115 | yield [iterable[idx] for idx, iterable in zip(curr_idxs, iterables)]
116 | if not next():
117 | return
118 | ```
119 |
120 | 一個 recursive 的版本:
121 |
122 | ```python
123 | def product_core(result, *iterables):
124 | if len(iterables)==0:
125 | yield result
126 | else:
127 | for item in iterables[0]:
128 | yield from product_core(result+[item], *iterables[1:])
129 |
130 | def product(*iterables):
131 | return product_core([], *iterables)
132 | ```
133 |
134 | 測試:
135 |
136 | ```python
137 | a = [1, 2, 3]
138 | b = [4, 5, 6]
139 | c = [7, 8, 9]
140 |
141 | for p in product(a, b, c):
142 | print(p)
143 | ```
144 |
145 | 結果:
146 |
147 | ```
148 | [1, 4, 7]
149 | [1, 4, 8]
150 | [1, 4, 9]
151 | [1, 5, 7]
152 | [1, 5, 8]
153 | [1, 5, 9]
154 | [1, 6, 7]
155 | [1, 6, 8]
156 | [1, 6, 9]
157 | [2, 4, 7]
158 | [2, 4, 8]
159 | [2, 4, 9]
160 | [2, 5, 7]
161 | [2, 5, 8]
162 | ...
163 | ```
164 |
165 | 人生苦短 別傻傻的自己做重複的事情啊...
166 |
--------------------------------------------------------------------------------
/questions/algorithm/燈泡開關問題.md:
--------------------------------------------------------------------------------
1 | # 燈泡開關問題
2 |
3 | ## 問題
4 |
5 | 現在有 100 個燈泡,每個燈泡都是關著的,第一趟把所有的燈泡燈泡打開,第二趟把偶數位的燈泡製反,第三趟讓第 3, 6, 9.... 的燈泡製反.......第 100 趟讓第 100 個燈泡製反,問經過一百趟以後有多少燈泡亮著。
6 |
7 | 代碼如何實現。
8 |
9 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000006055330), by [菩提旭光](https://segmentfault.com/u/runforlove)
10 |
11 | ## 回答
12 |
13 | 補充一下 @hsfzxjy 所說的
14 |
15 | ```
16 | 燈泡只要有一個因數就會被開關一次
17 | ```
18 |
19 | * 因為進行第 `i` 趟開關的時候, 會把 `i` 的倍數的燈開關
20 | * 也就是說, 因數有 `i` 的燈泡在此趟會被開關
21 |
22 | 從上面可以推出:
23 |
24 | ```
25 | 燈泡有奇數個因數最後的結果會是亮著的 (開關奇數次, 會是亮的)
26 | ```
27 |
28 | 又可以歸納出:
29 |
30 | ```
31 | 完全平方數的燈泡會亮著 (因為只有完全平方數有奇數個相異因數, 其他都會有兩兩成對的相異因數)
32 | ```
33 |
34 | 如果你要完全模擬這個狀況的話, 這邊有 Python 的代碼:
35 |
36 | ```python
37 | lamps = [ False for i in range(100) ]
38 |
39 | # print('starts', lamps)
40 |
41 | for i in range(1, len(lamps)+1):
42 | for idx, lamp in enumerate(lamps):
43 | if (idx + 1) % i == 0:
44 | lamps[idx] = not lamp
45 | # print(i, lamps)
46 |
47 | print(lamps.count(True))
48 | ```
49 |
50 | 但根據上面的結論, 你只要知道燈泡數內有幾個完全平方數就好了:
51 |
52 | ```python
53 | i = 1
54 | while i**2 <= 100:
55 | i += 1
56 |
57 | print(i-1)
58 | ```
59 |
--------------------------------------------------------------------------------
/questions/bs/python爬蟲beautifulsoup string抓取問題.md:
--------------------------------------------------------------------------------
1 | # python 爬蟲 beautifulsoup string 抓取問題
2 |
3 | ## 問題
4 |
5 | ![图片描述][1]
6 |
7 | [1]: https://segmentfault.com/img/bVyY2I
8 |
9 | 我要的是這個藍色部分的內容,但是 beautifulsoup 裡兩個方法,一個 `.strings` 還有一個 `get_text()` 都不行,他們會把下面 `span` 裡的 `string:Good Sister-in-lwa:Forbidden love` 這些都抓取。
10 |
11 | `.string` 直接抓不到,因為這個方法無法判斷該抓取哪個 string。
12 |
13 | 所以我該怎麼解決標籤里內嵌標籤的抓取字符串問題
14 |
15 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005915466/a-1020000005915727), by [yikosudo](https://segmentfault.com/u/yikosudo)
16 |
17 | ## 回答
18 |
19 | @洛克 的想法不錯,把不要的標籤淬出或是移除,再取字串:
20 |
21 | ```python
22 | >>> from bs4 import BeautifulSoup
23 | >>> html = 'I linked to example.com'
24 | >>> soup = BeautifulSoup(html)
25 | >>> a_tag = soup.a
26 | >>> i_tag = soup.i.extract()
27 | >>> a_tag.string
28 | 'I linked to '
29 | ```
30 |
31 | 或是像 @cloverstd 說的:
32 |
33 | ```
34 | >>> from bs4 import BeautifulSoup
35 | >>> html = 'I linked to example.com'
36 | >>> soup = BeautifulSoup(html)
37 | >>> a_tag = soup.a
38 | >>> list(a_tag.strings)
39 | [u'I linked to ', u'example.com']
40 | >>> list(a_tag.strings)[0]
41 | 'I linked to '
42 | >>> a_tag.contents[0]
43 | 'I linked to '
44 | ```
45 |
46 | 總之方法很多,任意組合囉...
47 |
--------------------------------------------------------------------------------
/questions/bs/刪除xml文件的指定標籤.md:
--------------------------------------------------------------------------------
1 | # 刪除xml文件的指定標籤
2 |
3 | ## 問題
4 |
5 | 有個xml文件的格式大致如下:
6 |
7 | ```xml
8 |
9 | 123
10 | abc
11 |
12 |
13 | 126
14 | abc
15 |
16 |
17 | 135
18 | abc
19 |
20 |
21 | 147
22 | abc
23 |
24 | ```
25 |
26 | 然後另外一個 `delete.txt` 保存的是需要刪除的 re 標籤的 id。
27 |
28 | 假設 txt 內容如下:
29 |
30 | ```
31 | 126
32 | 147
33 | ```
34 |
35 | 需要做的就是讀取這個 delete.txt 文件,然後在 xml 中找到這些 id 對應的 ` `標籤將其全部刪除,如上例的結果就是:
36 |
37 | ```xml
38 |
39 | 123
40 | abc
41 |
42 |
43 |
44 | 135
45 | abc
46 |
47 | ```
48 |
49 | 請問是怎麼做的。。另外需要提到的是這個 xml 文件挺大的,有200多M。
50 |
51 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005077756/a-1020000005079269), by [starryer](https://segmentfault.com/u/starryer)
52 |
53 | ## 回答
54 |
55 | 你可以使用 `BeautifulSoup` 套件:
56 |
57 | **安裝**:
58 |
59 | ```sh
60 | $ pip install bs4
61 | ```
62 |
63 | * 如果覺得 `html` 解析器不敷使用,參考[文檔][1]安裝其他適合的解析器。
64 | * 如果想要詳細了解 `BeautifulSoup` 也請參考官方文檔(有中文版本)。
65 |
66 | **測試檔**:
67 |
68 | 以下是我使用的測試文件:
69 |
70 | delete.txt
71 |
72 | ```
73 | 126
74 | 147
75 | ```
76 |
77 | test.xml
78 |
79 | ```xml
80 |
81 | 123
82 | abc
83 |
84 |
85 | 126
86 | abc
87 |
88 |
89 | 135
90 | abc
91 |
92 |
93 | 147
94 | abc
95 |
96 | ```
97 |
98 | **代碼**:
99 |
100 | ```python
101 | from bs4 import BeautifulSoup
102 |
103 | with open('test.xml') as reader:
104 | xml = reader.read()
105 |
106 | deleted_id = []
107 |
108 | with open('delete.txt') as reader:
109 | for line in reader:
110 | line = line.strip()
111 | deleted_id.append(line)
112 |
113 | def has_delete_id(tag):
114 | return tag.name=='re' and tag.id.string in deleted_id
115 |
116 | soup = BeautifulSoup(xml, 'html.parser')
117 |
118 | tags = soup(has_delete_id)
119 | for tag in tags:
120 | tag.decompose()
121 |
122 | print(soup.prettify())
123 | ```
124 |
125 | **程式輸出**:
126 |
127 | ```xml
128 |
129 |
130 | 123
131 |
132 |
133 | abc
134 |
135 |
136 |
137 |
138 | 135
139 |
140 |
141 | abc
142 |
143 |
144 | ```
145 |
146 | **代碼說明**:
147 |
148 | 首先我們從 `Beautiful Soup` 的套件中匯入 `BeautifulSoup` 類
149 |
150 | ```python
151 | from bs4 import BeautifulSoup
152 | ```
153 |
154 | 接著分別從 `delete.txt` 和 `test.xml` 中讀出要刪除的 id 和主要的 xml 內容,下一步是實體化生成一個 `BeautifulSoup` 對象 `soup`, 我們採用 `html.parser` 解析器去解析 `xml`:
155 |
156 | ```python
157 | soup = BeautifulSoup(xml, 'html.parser')
158 | ```
159 |
160 | 在此我們定義了一個用於過濾的 function `has_delete_id`,每一個在 `xml` 中的tag 只要是 `` tag 且含有想要刪除的 `` tag 就會被檢索出來:
161 |
162 | ```python
163 | def has_delete_id(tag):
164 | return tag.name=='re' and tag.id.string in deleted_id
165 | ```
166 |
167 | 接著 `soup(has_delete_id)` 會幫助我們找到欲刪除的 tag,接著走訪搜索出來的這些 tag 並呼叫方法 `decompose()` 來從文件中刪除該標籤。
168 |
169 | 最後 `soup.prettify()`可以幫助我們輸出修改後的文件。
170 |
171 | [1]: https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id9
172 |
173 |
--------------------------------------------------------------------------------
/questions/collections/Top_K_Frequent_Elements.md:
--------------------------------------------------------------------------------
1 | # Top K Frequent Elements
2 |
3 | ## 問題
4 |
5 | ```
6 | [('d', 100), ('c', 99), ('a', 89), ('b', 86)]
7 | ```
8 |
9 | 如何快速得出:
10 |
11 | ```
12 | ['d', 'c', 'a', 'b']
13 | ```
14 |
15 | 感覺好 low, 有什麼好的辦法嗎?
16 | 其實在用 Python 中在刷 leetcode 來學習
17 | [題目](https://leetcode.com/problems/top-k-frequent-elements/)
18 |
19 | ```python
20 | class Solution(object):
21 | def topKFrequent(self, nums, k):
22 | """
23 | :type nums: List[int]
24 | :type k: int
25 | :rtype: List[int]
26 | """
27 | items = {}
28 | for item in nums:
29 | if items.has_key(item):
30 | items[item]+=1
31 | else:
32 | items[item]=1
33 | arr1 = sorted(items.iteritems(), key=lambda asd:asd[1], reverse=True)
34 | arr2 = []
35 | for key in range(len(arr1)):
36 | arr2.append(arr1[key][0])
37 | return arr2[0:k]
38 | ```
39 |
40 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005087747/a-1020000005088335), by [cosde](https://segmentfault.com/u/cosde)
41 |
42 | ## 回答
43 |
44 | 很簡單,使用 list comprehension 即可:
45 |
46 | ```python
47 | arr1 = [('d', 100), ('c', 99), ('a', 89), ('b', 86)]
48 | arr2 = [pair[0] for pair in arr1]
49 | ```
50 |
51 | 看了一下你原本的問題,寫了一個簡潔的版本,可以參考一下:
52 | (適用於 Python2.7+, Python3)
53 |
54 | ```python
55 | from collections import Counter
56 |
57 | def top_k_frequent(lst, k):
58 | return [key for key, count in Counter(lst).most_common(k)]
59 | ```
60 |
61 | **使用**:
62 |
63 | ```python
64 | lst = [1, 1, 1, 2, 3, 4, 4]
65 | print(top_k_frequent(lst, 2))
66 | ```
67 |
68 | **效果**:
69 |
70 | ```
71 | [1, 4]
72 | ```
73 |
74 | **說明**:
75 |
76 | Python2.7+之後的版本,在 `collections` 庫裡有一種類 `Counter` 可以用。
77 | 詳細的操作方法請參考[Counter object][1]
78 |
79 | 利用 `Counter(lst)` 可以輕鬆得到一個 `Counter`實例,裡面已經對 `lst` 中的元素作過統計了。
80 | 之後利用 `most_common(k)` 方法可以輕鬆得到一個排序過的 list of tuple,而且只會剩下前出現頻率前k高的項目,最後用 `list comprehension` 取出元素本身:
81 |
82 | ```python
83 | >>> from collections import Counter
84 | >>> counter = Counter([1, 1, 1, 2, 3, 4, 4])
85 | >>> counter
86 | Counter({1: 3, 4: 2, 2: 1, 3: 1})
87 | >>> most_items = counter.most_common(2)
88 | >>> most_items
89 | [(1, 3), (4, 2)]
90 | >>> [key for key, count in most_items]
91 | [1, 4]
92 | ```
93 |
94 | [1]: https://docs.python.org/2/library/collections.html#counter-objects
95 |
--------------------------------------------------------------------------------
/questions/collections/會php和python的大神進來幫忙轉換一段代碼.md:
--------------------------------------------------------------------------------
1 | # 會 php 和 Python的大神進來幫忙轉換一段代碼
2 |
3 | ## 問題
4 |
5 | 求把這段php代碼轉成python的代碼,謝謝!
6 |
7 |
8 |
9 | ```php
10 | //倒序排序
11 | function my_sort($a,$b)
12 | {
13 | if ($a==$b) return 0;
14 | return ($a<$b)?1:-1;
15 | }
16 |
17 |
18 | $arr = array('aaa'=>5,'bbb'=>3,'ccc'=>4);
19 |
20 | usort($arr,"my_sort");
21 |
22 | echo json_encode($arr);
23 | ```
24 |
25 | 簡單說就是數組倒序排序,然後轉成json格式。
26 |
27 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005106649/a-1020000005107260), by [御風獨行豬](https://segmentfault.com/u/yufengduxingzhu)
28 |
29 | ## 回答
30 |
31 | PHP 中的 associative array 是一種 ordered mapping (有序映射).
32 | 這代表了 Python 中的 dictionary 並非完全相等於 associative array.
33 |
34 | 其次, json 據我所知並不支援 ordered mapping,所以如果你想要完成這項任務可能要:
35 |
36 | 1. 使用 Python 中的有序映射對象: `OrderedDict` (請參考[OrderedDict][1])
37 | 2. 將 `OrderedDict` 轉為 `list` 再轉為 `json`
38 | 3. 到時候要使用該項資料時,必須從 `json` 中 load 進 `list` 再轉回 `OrderedDict`
39 |
40 | ----------
41 |
42 | 以下是 *Python3* 的代碼讓你參考:
43 |
44 | **代碼**:
45 |
46 | ```python
47 | import json
48 | from collections import OrderedDict
49 |
50 | # using OrderedDict
51 | arr = {"aaa":5,"bbb":3,"ccc":4, "ddd":7}
52 | arr = OrderedDict(sorted(arr.items(), key=lambda item: item[1], reverse=True))
53 | # or you can create an OrderedDict directly:
54 | # arr = OrderedDict([('aaa', 5), ('bbb', 3), ('ccc', 4), ('ddd', 7)])
55 | print(arr)
56 |
57 | # list
58 | arr = list(arr.items())
59 | print(arr)
60 |
61 | # json dump
62 | json_arr = json.dumps(arr)
63 | print(json_arr)
64 |
65 | # json load
66 | arr = OrderedDict(json.loads(json_arr))
67 | print(arr)
68 | ```
69 |
70 | **結果**:
71 |
72 | ```python
73 | OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])
74 | [('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)]
75 | [["ddd", 7], ["aaa", 5], ["ccc", 4], ["bbb", 3]]
76 | OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])
77 | ```
78 |
79 | [1]: https://docs.python.org/2/library/collections.html#ordereddict-objects
80 |
--------------------------------------------------------------------------------
/questions/csv/csv模塊生成CSV文件問題(0字頭數字缺失與漢字亂碼).md:
--------------------------------------------------------------------------------
1 | # csv 模塊生成 CSV 文件問題(0字頭數字缺失與漢字亂碼)
2 |
3 | ## 問題
4 |
5 | python CSV模塊寫入CSV文件時,0開頭的數字會丟失
6 |
7 | ```python
8 | # _*_ coding:utf-8 _*_
9 | #win7+python2.7.x
10 | import csv
11 | csvfile = file( 'csvtest.csv' , 'wb' )
12 | writer = csv.writer(csvfile)
13 | writer.writerow([ 'id' , 'url' , 'keywords' ])
14 | data = [
15 | ( '0011' , 'http://www.59store.com/' , '59store.com' ),
16 | ( '0022' , 'http://59data.top/' , '59data.top' ),
17 | ( '0033' , 'http://my.space.zmx/' , '漢子亂碼?' )
18 | ]
19 | writer.writerows(data)
20 | csvfile.close()
21 | ```
22 |
23 | 寫入CSV時會丟失0字頭,漢字亂碼
24 |
25 | 
26 |
27 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005370629/a-1020000005436450), by [messiah163](https://segmentfault.com/u/messiah163)
28 |
29 | ## 回答
30 |
31 | 我測試的結果:
32 |
33 | ```
34 | id,url,keywords
35 | 0011,http://www.59store.com/,59store.com
36 | 0022,http://59data.top/,59data.top
37 | 0033,http://my.space.zmx/,汉子乱码?
38 | ```
39 |
40 | 看起來純文字 file 沒有什麼問題,猜測可能是你**用來開啟 csv 文件的試算表軟體**造成的.(mac 的 `Numbers` 和 `OpenOffice Calc` 都有這個現象)
41 |
42 | 比如說,id 欄位的型態如果設為數字,則前面不必要的 0 可能會自動被忽略. 像這一點可以試試看改成純文字型態再開啟.
43 |
44 | P.S. `Excel` 的部分可以見 玉河CC 大的說明.
45 |
46 | 要更精準更細節地處理 xlsx 文件,可以用 [XlsxWriter][1],他能夠控制資料的型態(data type),甚至樣式(format).
47 |
48 | [1]: http://xlsxwriter.readthedocs.io/index.html
49 |
--------------------------------------------------------------------------------
/questions/csv/如何用python刪除csv文件中的某一列.md:
--------------------------------------------------------------------------------
1 | # 如何用 python 刪除 csv 文件中的某一列
2 |
3 | ## 問題
4 |
5 | 如何用python刪除csv文件中的某一列?
6 |
7 | 比如名為 `a.csv`中的數據:
8 |
9 | ```
10 | index ABC
11 | 0 1 3 5
12 | 1 2 4 6
13 | 2 7 8 9
14 | ```
15 |
16 | 想要刪除第二列( B 列)該如何刪除呢?代碼該如何編寫呢?
17 | 求大神!萬分感謝!!!
18 |
19 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005958613/a-1020000005959134), by [tammy](https://segmentfault.com/u/qqqqqq123)
20 |
21 | ## 回答
22 |
23 | 如果問題很單純,甚至連 `csv` 都可以不使用:
24 |
25 | ```python
26 | with open('old.csv') as reader, open('new.csv', 'w') as writer:
27 | for line in reader:
28 | items = line.strip().split()
29 | print(' '.join(items[:2]+items[3:]), file=writer)
30 | ```
31 |
32 | 寫個 general 的:
33 |
34 | ```python
35 | import csv
36 |
37 | def del_cvs_col(fname, newfname, idxs, delimiter=' '):
38 | with open(fname) as csvin, open(newfname, 'w') as csvout:
39 | reader = csv.reader(csvin, delimiter=delimiter)
40 | writer = csv.writer(csvout, delimiter=delimiter)
41 | rows = (tuple(item for idx, item in enumerate(row) if idx not in idxs) for row in reader)
42 | writer.writerows(rows)
43 |
44 | del_cvs_col('a.csv', 'b.csv', [2])
45 | ```
46 |
47 | `del_cvs_col` 會將 `fname` 轉成 `newfname` 用 `delimiter` 來做分割字元,且會去除掉在 `idxs`中指定的列。
48 |
--------------------------------------------------------------------------------
/questions/csv/操作csv文件寫入順序不對.md:
--------------------------------------------------------------------------------
1 | # 操作 csv 文件寫入順序不對
2 |
3 | ## 問題
4 |
5 | 我是初學者不太懂
6 |
7 | 1. 為什麼在終端顯示是正確的順序到了csv 文件中就是另一回事了呢
8 | 2. 還有就是csv 文件怎麼可以運行之後繼續填寫而不是清空文件呢?
9 |
10 | 
11 |
12 | 
13 |
14 | 代碼:
15 |
16 | ```python
17 | import urllib.request
18 | import re
19 | import bs4
20 | import csv
21 | from bs4 import BeautifulSoup
22 |
23 | url="http://10.104.65.9/home/part/shuiQing.jsp"
24 | data=urllib.request.urlopen(url).read()
25 | data=data.decode('UTF-8')
26 |
27 | soup=BeautifulSoup(data,"html.parser")
28 | foundtxt=soup.find_all('td',height='22')
29 |
30 | rol=[]
31 | index=0
32 |
33 | #with open(r'C:\Users\skyb52\Desktop\12.csv','wb') as csvfile:
34 | with open(r'C:\Users\skyb52\Desktop\12.csv','w',newline='') as csvfile:
35 | spamwriter = csv.writer(csvfile,dialect='excel')
36 | for i in foundtxt:
37 | rol.append(i.string)
38 | index=index+1
39 | if index==3:
40 | spamwriter.writerow({rol[0],rol[1],rol[2]})
41 | print(rol[0],rol[1],rol[2])
42 | rol=[]
43 | index=0
44 | csvfile.close()
45 | ```
46 |
47 | 最後添加上內網網站源代碼:
48 |
49 | ```html
50 |
57 |
58 |
59 |
60 | 站名 |
61 | 水位(m) |
62 | 流量(m3/s) |
63 |
64 |
65 |
66 | 小浪底 |
67 | 134.63 |
68 | 565 |
69 |
70 |
71 | 花园口 |
72 | 89.05 |
73 | 445 |
74 |
75 |
76 | 夹河滩 |
77 | 72.58 |
78 | 400 |
79 |
80 |
81 | 高村 |
82 | 58.98 |
83 | 360 |
84 |
85 |
86 | 孙口 |
87 | 44.29 |
88 | 358 |
89 |
90 |
91 | 艾山 |
92 | 36.82 |
93 | 225 |
94 |
95 |
96 | 泺口 |
97 | 25.7 |
98 | 207 |
99 |
100 |
101 | 利津 |
102 | 9.36 |
103 | 76.5 |
104 |
105 |
106 |
107 |
108 |
109 | ```
110 |
111 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000005621628/a-1020000005624752), by [skyb52](https://segmentfault.com/u/skyb52)
112 |
113 | ## 回答
114 |
115 | 你寫到 csv 的代碼:
116 |
117 | ```python
118 | spamwriter.writerow({rol[0],rol[1],rol[2]})
119 | ```
120 |
121 | 你寫了一個 set 出來,他是無序的,而你 `print` 的時候是有序的:
122 |
123 | ```python
124 | print(rol[0],rol[1],rol[2])
125 | ```
126 |
127 | 結果自然不同
128 |
129 | ----------
130 |
131 | 不清空而是附加新的資料上去的作法,在於使用 `open` 打開文檔時,要使用 `'a'` (append) 模式:
132 |
133 | ```python
134 | with open(r'C:\Users\skyb52\Desktop\12.csv','w',newline='') as csvfile:
135 | ^^^
136 | 寫入模式,會覆蓋掉原本的資料從頭開始寫入
137 | ```
138 |
139 | 改成:
140 |
141 | ```python
142 | with open(r'C:\Users\skyb52\Desktop\12.csv','a',newline='') as csvfile:
143 | ^^^
144 | 附加模式,會從文件最後開始寫入
145 | ```
146 |
--------------------------------------------------------------------------------
/questions/data_mining/python3中有聚類(主要是k-means)的函數或者模塊嗎.md:
--------------------------------------------------------------------------------
1 | # python3 中有聚類(主要是k-means)的函數或者模塊嗎
2 |
3 | ## 問題
4 |
5 | 最經在做用戶畫像,需要對數據進行聚類,發現python貌似沒有現成的聚類函數。不知道是不是我沒有找到,還是真的沒有,如果沒有,大夥有什麼好的軟件推薦去完成聚類分析。
6 |
7 | 謝謝各位了~~
8 |
9 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000006057925/a-1020000006057999), by [EchoJnn](https://segmentfault.com/u/echojnn)
10 |
11 | ## 回答
12 |
13 | > k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster.
14 |
15 | * [sklearn.cluster.KMeans](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html)
16 |
17 | * [scipy-cluster](http://docs.scipy.org/doc/scipy/reference/cluster.html)
18 |
--------------------------------------------------------------------------------
/questions/django/Django CSRF verification failed 問題.md:
--------------------------------------------------------------------------------
1 | # Django CSRF verification failed 問題
2 |
3 | ## 問題
4 |
5 | **urls.py**
6 |
7 | ```python
8 | from django.conf.urls import url
9 | from django.contrib import admin
10 | from blog import views
11 | urlpatterns = [
12 | url(r'^admin/', admin.site.urls),
13 | url(r'^$', views.index),
14 | url(r'^abc$',views.handler),
15 | ]
16 | ```
17 |
18 | **views.py**
19 |
20 | ```python
21 | # -*- coding: utf-8 -*-
22 | from django.shortcuts import render
23 | from django.http import HttpResponse
24 |
25 | # Create your views here.
26 |
27 | def index(request):
28 | return render(request,"index.html")
29 |
30 |
31 | def handler(request):
32 | return HttpResponse("name:
" + request.POST['username'])
33 | ```
34 |
35 | **index.html**
36 |
37 | ```python
38 |
39 |
40 |
41 |
42 | index page
43 |
44 |
45 |
49 |
50 |
51 |
52 | ```
53 |
54 | 我在谷歌瀏覽器下點擊這個提交後出現了:
55 | ![图片描述][1]
56 |
57 | 我又直接打開abc網站出現了:
58 | ![图片描述][2]
59 |
60 | 請問這是什麼問題啊要怎麼解決啊?
61 |
62 |
63 | [1]: https://segmentfault.com/img/bVz3ih
64 | [2]: https://segmentfault.com/img/bVz3iq
65 |
66 | 問題出自 [segmentfault](https://segmentfault.com/q/1010000006170144/a-1020000006171703), by [dzxczxsb](https://segmentfault.com/u/dzxczxsb)
67 |
68 | ## 回答
69 |
70 | 在 Django 中, 使用 post 的時候很可能會出現以下錯誤:
71 |
72 | ```python
73 | Forbidden(403):
74 | CSRF verification failed. Request aborted.
75 | Reason given for failure:
76 | CSRF token missing or incorrect.
77 | ```
78 |
79 | 這是因為 Django 幫我們啟動了 **CSRF攻擊** 的防護,CSRF(cross-site request forgery) 是惡意的跨站請求或偽裝使用者的攻擊,攻擊者會欺騙用戶的瀏覽器去訪問一個認證過的網站並且執行一些惡意的操作。由於用戶的瀏覽器已經被該網站認證過了,所以該網站會放心的讓這些操作被執行(即便這些操作並非該網站要求的或是不是用戶自願的)。
80 |
81 | 所以我們的伺服器需要一些有保護的措施。常見的一種防護手段,就是使用一個伺服器產生的亂數 token,夾帶在送給客戶端的表單中,當客戶端送回表單時,伺服器檢查這個 token 是不是自己發出,便可以防止攻擊。
82 |
83 | 由於在 `settings.py` 檔中的 `MIDDLEWARE_CLASSES` 中有預設的 `'django.middleware.csrf.CsrfViewMiddleware'`,所以 Django 在這裡便會要求 CSRF token 驗證,為了讓我們的網站更安全,我們還是照著遊戲規則一步一步來吧!
84 |
85 | 在html的`