diff --git a/README.md b/README.md index de346d2..3e095dd 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ 這個 repository 收集了一些我自己感覺比較有趣或實用的問題,每篇都會附上原發問者的問題以及我的回答,問題可能經過潤飾,但我盡量維持原貌,回答的部分也多是個人見解,只是希望做個整理並且與有興趣的人分享. -由於問題滿雜的,我只能憑我的直覺將之分類歸檔,目前一共收錄了 72 個問題,大家有興趣的可以參閱[目錄](contents.md). +由於問題滿雜的,我只能憑我的直覺將之分類歸檔,目前一共收錄了 81 個問題,大家有興趣的可以參閱[目錄](contents.md). 如果你有任何的意見或想要討論,都歡迎你開個 issue 來討論唷! diff --git a/contents.md b/contents.md index d6b2a29..998df8a 100644 --- a/contents.md +++ b/contents.md @@ -3,146 +3,162 @@ ## 內建型態與 collections 容器 * string - * [Python 中字串的 bitwise or 怎麼實現?](questions/string/Python中字串的bitwise or怎麼實現.md) - * [給定一個字串,回傳所有的可能組合](questions/string/給定一個字串,回傳所有的可能組合.md) - * [如何讓列表所有元素首字母變大寫](questions/string/如何讓列表所有元素首字母變大寫.md) - * [轉換一個字串為浮點數會報錯](questions/string/轉換一個字串為浮點數會報錯.md) + * [Python 中字串的 bitwise or 怎麼實現?](questions/string/Python中字串的bitwise%20or怎麼實現.md) + * [給定一個字串,回傳所有的可能組合](questions/string/給定一個字串,回傳所有的可能組合.md) + * [如何讓列表所有元素首字母變大寫](questions/string/如何讓列表所有元素首字母變大寫.md) + * [轉換一個字串為浮點數會報錯](questions/string/轉換一個字串為浮點數會報錯.md) * list - * [遍歷二維串列最外圈](questions/list/遍歷二維串列最外圈.md) - * [list 使用 append 最後為什麼會把前面的元素都修改掉](questions/list/list使用append最後為什麼會把前面的元素都修改掉.md) - * [python 列表取交集](questions/list/python列表取交集.md) + * [遍歷二維串列最外圈](questions/list/遍歷二維串列最外圈.md) + * [list 使用 append 最後為什麼會把前面的元素都修改掉](questions/list/list使用append最後為什麼會把前面的元素都修改掉.md) + * [python 列表取交集](questions/list/python列表取交集.md) + * [python 生成特定列表格式](questions/list/python生成特定列表格式.md) * collections - * [會 php 和 Python 的大神進來幫忙轉換一段代碼](questions/collections/會php和python的大神進來幫忙轉換一段代碼.md) - * [Top K Frequent Elements](questions/collections/Top_K_Frequent_Elements.md) + * [會 php 和 Python 的大神進來幫忙轉換一段代碼](questions/collections/會php和python的大神進來幫忙轉換一段代碼.md) + * [Top K Frequent Elements](questions/collections/Top_K_Frequent_Elements.md) ## 函式 +* star expression + * [關於 python * 和 ** 的問題](questions/star/關於python*和**的問題.md) + +* variable scope(global/local/nonlocal/closure) + * [為什麼這兩段 python lambda 出現不同的結果](questions/scope/為什麼這兩段%20python%20lambda%20出現不同的結果.md) + +## 內建函式 + * len - * [怎麼判斷函數或方法多次使用是否需要定義臨時變量](questions/len/怎麼判斷函數或方法多次使用是否需要定義臨時變量.md) + * [怎麼判斷函數或方法多次使用是否需要定義臨時變量](questions/len/怎麼判斷函數或方法多次使用是否需要定義臨時變量.md) * sort - * [Python排序問題](questions/sort/Python排序問題.md) - * [sorted函數中key參數的作用原理](questions/sort/sorted函數中key參數的作用原理.md) - -* star expression - * [關於 python * 和 ** 的問題](questions/star/關於python*和**的問題.md) + * [Python排序問題](questions/sort/Python排序問題.md) + * [sorted函數中key參數的作用原理](questions/sort/sorted函數中key參數的作用原理.md) + +* eval + * [對 Python 語法字串求值](questions/eval/對Python語法字串求值.md) ## 控制流程與迭代 * if(if/elif/else) - * [if 語句的 and or 運算](questions/if/if 語句的 and or 運算.md) + * [if 語句的 and or 運算](questions/if/if%20語句的%20and%20or%20運算.md) * iteration(iterable/iterater/comprehension/generator/generator expression) - * [如何將列表中的元組整個迭代出](questions/iteration/如何將列表中的元組整個迭代出來.md) - * [一個求質(素)數的編程題](questions/iteration/一個求質(素)數的編程題.md) - * [Python 如何合併 list of lists](questions/iteration/Python 如何合併 list of lists.md)(待補充) - * [如何從一個複雜的結構中優雅的提取出一列數據](questions/iteration/如何從一個複雜的結構中優雅的提取出一列數據.md) - * [如何把 tuple 轉成 dictionary](questions/iteration/如何把tuple轉成dictionary.md) - * [Python 的 list 有沒有類似 js 的 find 方法](questions/iteration/Python的list有沒有類似js的find方法.md) - * [python 中既然生成器表達式比列表解析快, 那為什麼不全部使用生成器表達式](questions/iteration/python中既然生成器表達式比列表解析快, 那為什麼不全部使用生成器表達式.md) + * [如何將列表中的元組整個迭代出](questions/iteration/如何將列表中的元組整個迭代出來.md) + * [一個求質(素)數的編程題](questions/iteration/一個求質(素)數的編程題.md) + * [Python 如何合併 list of lists](questions/iteration/Python%如何合併%20list%20of%20lists.md)(待補充) + * [如何從一個複雜的結構中優雅的提取出一列數據](questions/iteration/如何從一個複雜的結構中優雅的提取出一列數據.md) + * [如何把 tuple 轉成 dictionary](questions/iteration/如何把tuple轉成dictionary.md) + * [Python 的 list 有沒有類似 js 的 find 方法](questions/iteration/Python的list有沒有類似js的find方法.md) + * [python 中既然生成器表達式比列表解析快, 那為什麼不全部使用生成器表達式](questions/iteration/python中既然生成器表達式比列表解析快,%20那為什麼不全部使用生成器表達式.md) * functional programming style(map/filter/reduce) - * [sum 函數中可以使用條件語句嗎?](questions/fp/sum函數中可以使用條件語句嗎.md) + * [sum 函數中可以使用條件語句嗎?](questions/fp/sum函數中可以使用條件語句嗎.md) * error handling(exception) - * [Python 如何優雅的處理大量異常語句](questions/error/Python如何優雅的處理大量異常語句.md) - * [python 如何捕獲中斷](questions/error/python如何捕獲中斷.md) + * [Python 如何優雅的處理大量異常語句](questions/error/Python如何優雅的處理大量異常語句.md) + * [python 如何捕獲中斷](questions/error/python如何捕獲中斷.md) ## 物件導向程式設計 * dunder(magic function) - * [自己寫的數據類型使用print無法輸出每個元素](questions/dunder/自己寫的數據類型使用print無法輸出每個元素.md) + * [自己寫的數據類型使用print無法輸出每個元素](questions/dunder/自己寫的數據類型使用print無法輸出每個元素.md) * object(class/object) - * [Python 3.x 實例方法的`__func__`屬性](questions/object/Python 3.x 實例方法的__func__屬性.md) - * [Python 如何通過類方法創建實例方法](questions/object/Python如何通過類方法創建實例方法.md) - * [Python 的 staticmethod 在什麼情況下用](questions/object/Python的staticmethod在什麼情況下用.md) + * [Python 3.x 實例方法的`__func__`屬性](questions/object/Python%203.x%20實例方法的__func__屬性.md) + * [Python 如何通過類方法創建實例方法](questions/object/Python如何通過類方法創建實例方法.md) + * [Python 的 staticmethod 在什麼情況下用](questions/object/Python的staticmethod在什麼情況下用.md) + * [Python 多重繼承屬性問題](questions/object/Python多重繼承屬性問題.md) ## 檔案與資料處理 * file - * [怎樣合併文檔中有重複部分的行](questions/file/怎樣合併文檔中有重複部分的行.md) - * [Python 處理文本信息](questions/file/Python處理文本信息.md) - * [Python 如何實現並行查找關鍵字所在的行](questions/file/Python如何實現並行查找關鍵字所在的行.md) - * [文本格式轉換代碼優化](questions/file/文本格式轉換代碼優化.md) - * [使用 Python 如何按行數拆分文件](questions/file/使用Python如何按行數拆分文件.md) - * [Python 處理一個求和運算](questions/file/Python處理一個求和運算.md) - * [Python 如何向文件最開始插入一個字串](questions/file/Python如何向文件最開始插入一個字串.md)(待補充) - * [用 Python 實現類似 grep 的功能](questions/file/用Python實現類似grep的功能.md) + * [怎樣合併文檔中有重複部分的行](questions/file/怎樣合併文檔中有重複部分的行.md) + * [Python 處理文本信息](questions/file/Python處理文本信息.md) + * [Python 如何實現並行查找關鍵字所在的行](questions/file/Python如何實現並行查找關鍵字所在的行.md) + * [文本格式轉換代碼優化](questions/file/文本格式轉換代碼優化.md) + * [使用 Python 如何按行數拆分文件](questions/file/使用Python如何按行數拆分文件.md) + * [Python 處理一個求和運算](questions/file/Python處理一個求和運算.md) + * [Python 如何向文件最開始插入一個字串](questions/file/Python如何向文件最開始插入一個字串.md)(待補充) + * [用 Python 實現類似 grep 的功能](questions/file/用Python實現類似grep的功能.md) * json - * [為什麼 json 的 key 只能是 string?](questions/json/為什麼json的key只能是string.md) - * [Python 如何合併批量輸出 json](questions/json/Python如何合併批量輸出json.md) - * [Python 如何讀取 json 中的數據](questions/json/Python如何讀取json中的數據.md) - * [不定深層 Json 剖析](questions/json/不定深層Json剖析.md) + * [為什麼 json 的 key 只能是 string?](questions/json/為什麼json的key只能是string.md) + * [Python 如何合併批量輸出 json](questions/json/Python如何合併批量輸出json.md) + * [Python 如何讀取 json 中的數據](questions/json/Python如何讀取json中的數據.md) + * [不定深層 Json 剖析](questions/json/不定深層Json剖析.md) + * [假定有 json 數據多條記錄,如何根據 KEY 的值返回一條記錄](questions/json/假定有json數據多條記錄,如何根據KEY的值返回一條記錄.md) * cvs - * [csv 模塊生成 CSV 文件問題(0字頭數字缺失與漢字亂碼)](questions/csv/csv模塊生成CSV文件問題(0字頭數字缺失與漢字亂碼).md) - * [操作 csv 文件寫入順序不對](questions/csv/操作csv文件寫入順序不對.md) - * [如何用 python 刪除 csv 文件中的某一列](questions/csv/如何用python刪除csv文件中的某一列.md) + * [csv 模塊生成 CSV 文件問題(0字頭數字缺失與漢字亂碼)](questions/csv/csv模塊生成CSV文件問題(0字頭數字缺失與漢字亂碼).md) + * [操作 csv 文件寫入順序不對](questions/csv/操作csv文件寫入順序不對.md) + * [如何用 python 刪除 csv 文件中的某一列](questions/csv/如何用python刪除csv文件中的某一列.md) ## 模組與套件 * import - * [通過哪個函數能查看 Python 文件中匯入了哪些模組](questions/import/通過哪個函數能查看Python文件中匯入了哪些模組.md) - * [deepcopy 無法 import](questions/import/deepcopy無法import.md) + * [通過哪個函數能查看 Python 文件中匯入了哪些模組](questions/import/通過哪個函數能查看Python文件中匯入了哪些模組.md) + * [deepcopy 無法 import](questions/import/deepcopy無法import.md) * standard library - * [os.mkdir 和 os.makedirs 的區別](questions/standard_lib/os.mkdir和os.makedirs的區別.md) - * [tk 程序中出現問題](questions/standard_lib/tk程序中出現問題.md) - * [計算時間差](questions/standard_lib/計算時間差.md) - * [Python timeit 測量代碼運行時間問題](questions/standard_lib/Python timeit測量代碼運行時間問題.md) - * [Python 日期的遞增問題](questions/standard_lib/Python日期的遞增問題.md) - * [一個需要傳入參數的 python 程序如何封裝成可執行文件](questions/standard_lib/一個需要傳入參數的python程序如何封裝成可執行文件.md) - * [一個結構化顯示文件的腳本,迭代是否有問題](questions/standard_lib/一個結構化顯示文件的腳本,迭代是否有問題.md) - * [如何在 python raw_input 中使用 tab 鍵補全](questions/standard_lib/如何在python raw_input中使用tab鍵補全.md) + * [os.mkdir 和 os.makedirs 的區別](questions/standard_lib/os.mkdir和os.makedirs的區別.md) + * [tk 程序中出現問題](questions/standard_lib/tk程序中出現問題.md) + * [計算時間差](questions/standard_lib/計算時間差.md) + * [Python timeit 測量代碼運行時間問題](questions/standard_lib/Python%20timeit測量代碼運行時間問題.md) + * [Python 日期的遞增問題](questions/standard_lib/Python日期的遞增問題.md) + * [一個需要傳入參數的 python 程序如何封裝成可執行文件](questions/standard_lib/一個需要傳入參數的python程序如何封裝成可執行文件.md) + * [一個結構化顯示文件的腳本,迭代是否有問題](questions/standard_lib/一個結構化顯示文件的腳本,迭代是否有問題.md) + * [如何在 python raw_input 中使用 tab 鍵補全](questions/standard_lib/如何在python%20raw_input中使用tab鍵補全.md) + * [交換兩個 shelve objects](questions/standard_lib/交換兩個shelve%20objects.md) + * [Python 獲取文件路徑及文件目錄(`__file__` 的使用方法)](questions/standard_lib/Python%20獲取文件路徑及文件目錄(__file__%20的使用方法).md) * pip - * [pip 無法在安裝 pyinstaller](questions/pip/pip無法在安裝pyinstaller.md) - * [Python 代碼怎麼打包](questions/pip/python代碼怎麼打包.md) + * [pip 無法在安裝 pyinstaller](questions/pip/pip無法在安裝pyinstaller.md) + * [Python 代碼怎麼打包](questions/pip/python代碼怎麼打包.md) * others - * [中文按照拼音排序](questions/others/中文按照拼音排序.md) + * [中文按照拼音排序](questions/others/中文按照拼音排序.md) ## WEB * django - * [django 如何一個 url 綁定多個視圖](questions/django/django如何一個url綁定多個視圖.md) - * [django 模版中變量引用變量被當作字符串處理而不是變量值](questions/django/django模版中變量引用變量被當作字符串處理而不是變量值.md) - * [網頁根目錄改成子目錄後文件如何調用](questions/django/網頁根目錄改成子目錄後文件如何調用.md) + * [django 如何一個 url 綁定多個視圖](questions/django/django如何一個url綁定多個視圖.md) + * [django 模版中變量引用變量被當作字符串處理而不是變量值](questions/django/django模版中變量引用變量被當作字符串處理而不是變量值.md) + * [網頁根目錄改成子目錄後文件如何調用](questions/django/網頁根目錄改成子目錄後文件如何調用.md) + * [Django CSRF verification failed 問題](questions/django/Django%20CSRF%20verification%20failed%20問題.md) * flask/jinja - * [jinja2 macro caller](questions/jinja/jinja2_macro_caller.md) + * [jinja2 macro caller](questions/jinja/jinja2_macro_caller.md) ## 爬蟲 * beautiful soup - * [刪除 xml 文件的指定標籤](questions/bs/刪除xml文件的指定標籤.md) - * [Python 爬蟲 beautifulsoup string 抓取問題](questions/bs/python爬蟲beautifulsoup string抓取問題.md) + * [刪除 xml 文件的指定標籤](questions/bs/刪除xml文件的指定標籤.md) + * [Python 爬蟲 beautifulsoup string 抓取問題](questions/bs/python爬蟲beautifulsoup%20string抓取問題.md) ## 演算法與科學計算 * algorithm - * [Subset-Sum Problem](questions/algorithm/subset_sum_problem.md) - * [字串 list 排序(七橋問題)](questions/algorithm/字串list排序(七橋問題).md) - * [使用字串為整數編碼](questions/algorithm/使用字串為整數編碼.md) - * [分群問題](questions/algorithm/分群問題.md) - * [找出所有組合-笛卡爾積問題](questions/algorithm/找出所有組合-笛卡爾積問題.md) - * [燈泡開關問題](questions/algorithm/燈泡開關問題.md) + * [Subset-Sum Problem](questions/algorithm/subset_sum_problem.md) + * [字串 list 排序(七橋問題)](questions/algorithm/字串list排序(七橋問題).md) + * [使用字串為整數編碼](questions/algorithm/使用字串為整數編碼.md) + * [分群問題](questions/algorithm/分群問題.md) + * [找出所有組合-笛卡爾積問題](questions/algorithm/找出所有組合-笛卡爾積問題.md) + * [燈泡開關問題](questions/algorithm/燈泡開關問題.md) + * [一個數最後一位是 6,移動到首位是原來數的三倍,求這個數](questions/algorithm/一個數最後一位是6,移動到首位是原來數的三倍,求這個數.md) * math - * [Python怎麼通過input獲取矩陣](questions/math/Python怎麼通過input獲取矩陣.md) + * [Python 怎麼通過 input 獲取矩陣](questions/math/Python怎麼通過input獲取矩陣.md) ## 大數據與機器學習 + * data mining - * [python3中有聚類(主要是k-means)的函數或者模塊嗎](questions/data_mining/python3中有聚類(主要是k-means)的函數或者模塊嗎.md) + * [python3 中有聚類(主要是k-means)的函數或者模塊嗎](questions/data_mining/python3中有聚類(主要是k-means)%20的函數或者模塊嗎.md) ## Python 實作與開發環境 * IDE (集成開發環境) - * [Python 能否在保存程序變量情況下啟動控制台](questions/ide/Python能否在保存程序變量情況下啟動控制台.md) + * [Python 能否在保存程序變量情況下啟動控制台](questions/ide/Python能否在保存程序變量情況下啟動控制台.md) * virtualenv - * [如何在 ubuntu14.04 安裝 python3.5](questions/virtualenv/如何在ubuntu14.04安裝python3.5.md) + * [如何在 ubuntu14.04 安裝 python3.5](questions/virtualenv/如何在ubuntu14.04安裝python3.5.md) diff --git a/draft/finput.py b/draft/finput.py new file mode 100644 index 0000000..19af047 --- /dev/null +++ b/draft/finput.py @@ -0,0 +1,76 @@ +# author: dokelung + +import re +from ast import literal_eval +from functools import partial + + +class InputDoesNotMatchFStr(Exception): pass +class TypeConvertError(Exception): pass +class InputCountNotInRange(Exception): pass + + +FORMAT_SPECIFIER = { + '%a': literal_eval, + '%d': int, + '%f': float, + '%o': partial(int, base=8), + '%s': str, + '%x': partial(int, base=16), +} + + +def finput(prompt='', fstr='%s', expand_fsp=None, + whitespace=False, + escape_parenthesis=True): + """format input + """ + fsp = FORMAT_SPECIFIER + if expand_fsp is not None: + fsp.update(expand_fsp) + if escape_parenthesis: + rstr = fstr.replace('(', '\(').replace(')', '\)') + else: + rstr = fstr + regex = '(.+)' if whitespace else '(\S+)' + for sp, typ in fsp.items(): + rstr = rstr.replace(sp, regex) + types = [] + for idx, c in enumerate(fstr): + pattern = fstr[idx:idx+2] + if pattern in fsp: + types.append(fsp[pattern]) + pure_input = input(prompt) + mobj = re.match(rstr, pure_input) + if mobj: + try: + return tuple(typ(value) for value, typ in zip(mobj.groups(), types)) + except Exception as err: + raise TypeConvertError(err) + else: + msg = 'input does not match format string "{}"' + raise InputDoesNotMatchFStr(msg.format(fstr)) + + +def minput(prompt='', typ=str, sep=None, min=1, max=100000): + """multiple input + """ + pure_input = input(prompt) + try: + if sep is None: + values = tuple(typ(item) for item in pure_input.split()) + else: + values = tuple(typ(item) for item in pure_input.split(sep)) + except Exception as err: + raise TypeConvertError(err) + if len(values) < min or len(values) > max: + msg = 'input count {} is not in range [{}, {}]' + raise InputCountNotInRange(msg.format(len(values), min, max)) + return values + + +if __name__ == '__main__': + #res = finput('>>> ', fstr='%s, *%d, *%f') + #print(res) + res = minput('>>> ', typ=int, min=1, max=3) + print(res) diff --git "a/draft/\351\227\234\346\226\274 class variable.md" "b/draft/\351\227\234\346\226\274 class variable.md" new file mode 100644 index 0000000..f00ccb3 --- /dev/null +++ "b/draft/\351\227\234\346\226\274 class variable.md" @@ -0,0 +1,94 @@ +首先你寫在 class 裡面但不在 method 裡面的 variable 是 class variable + +這個 variable 對於該類別及其子類別的類別和實體而言都只有一份, 看下面這個例子: + +```python +class A: + _dict = {} + def __init__(self): + self._dict.update({'a':'a'}) + +class B(A): + + def __init__(self): + self._dict.update({'b':'b'}) + +if __name__=='__main__': + a = A() + b = B() + print(a._dict) + print(b._dict) + print(A._dict) + print(B._dict) +``` + +``` +{'b': 'b', 'a': 'a'} +{'b': 'b', 'a': 'a'} +{'b': 'b', 'a': 'a'} +{'b': 'b', 'a': 'a'} +``` + +這裡你看到的所有 `_dict` 都參考到同一個物件 + +但是下面這個情況就不太一樣了: + +```python +class A: + _dict = {} + def __init__(self): + self._dict = {} + self._dict.update({'a':'a'}) + +class B(A): + + def __init__(self): + self._dict.update({'b':'b'}) + +class C(A): + + def __init__(self): + super().__init__() + self._dict.update({'c':'c'}) + +if __name__=='__main__': + a = A() + b = B() + c = C() + print(a._dict) + print(b._dict) + print(c._dict) + print(A._dict) + print(B._dict) + print(C._dict) +``` + +``` +{'a': 'a'} +{'b': 'b'} +{'c': 'c', 'a': 'a'} +{'b': 'b'} +{'b': 'b'} +{'b': 'b'} +``` + +咦?! 怎麼變成這樣了呢? 這邊如果搞懂的話就全盤皆通了: + +首先 A 及其子類別都共有一個 class variable, 叫做 `_dict` + +當我們初始化 a 的時候, `self._dict = {}` 會讓 a 裡面新產生一個變數叫做 `_dict`, 因為這次 `self._dict` 出現在等號左邊。注意! 這裡我們已經有兩個不同的東西了, 一個是 class variable `_dict`, 另一個是 instance variable `_dict`, 從此以後, a 裡面拿 `self._dict` 的時候就都是拿到 instance variable 了! + +接著看 b, b 並沒有讓 variable 出現在等號左邊, 所以沒有建立新的變數, 現在 b 中的 `self._dict` 仍然指涉 class variable `_dict` + +c 的情況就比較特別了, 藉由 `super` 他呼叫了 A 的 `__init__`, 上面說過了, 這會讓 c 中新建立一個 instance variable `_dict`, 這個變數因為 `A.__init__` 和 `C.__init__`, 所以會有兩個鍵值對 + + +最後 `A._dict`, `B._dict` 和 `C._dict` 就很容易理解了, 他們都是參考到同一個 class variable, 所以值都一樣。 + +### 小結 + +讓我們來整理一下, 這邊一共會有 3 個 `_dict`: + +1. class variable `_dict` +2. instance variable of a +3. instance variable of c diff --git "a/questions/algorithm/\344\270\200\345\200\213\346\225\270\346\234\200\345\276\214\344\270\200\344\275\215\346\230\2576\357\274\214\347\247\273\345\213\225\345\210\260\351\246\226\344\275\215\346\230\257\345\216\237\344\276\206\346\225\270\347\232\204\344\270\211\345\200\215\357\274\214\346\261\202\351\200\231\345\200\213\346\225\270.md" "b/questions/algorithm/\344\270\200\345\200\213\346\225\270\346\234\200\345\276\214\344\270\200\344\275\215\346\230\2576\357\274\214\347\247\273\345\213\225\345\210\260\351\246\226\344\275\215\346\230\257\345\216\237\344\276\206\346\225\270\347\232\204\344\270\211\345\200\215\357\274\214\346\261\202\351\200\231\345\200\213\346\225\270.md" new file mode 100644 index 0000000..8de074f --- /dev/null +++ "b/questions/algorithm/\344\270\200\345\200\213\346\225\270\346\234\200\345\276\214\344\270\200\344\275\215\346\230\2576\357\274\214\347\247\273\345\213\225\345\210\260\351\246\226\344\275\215\346\230\257\345\216\237\344\276\206\346\225\270\347\232\204\344\270\211\345\200\215\357\274\214\346\261\202\351\200\231\345\200\213\346\225\270.md" @@ -0,0 +1,103 @@ +# 一個數最後一位是6,移動到首位是原來數的三倍,求這個數 + +## 問題 + +題目:一個數最後一位是6,移動到首位是原來數的三倍,求這個數 +要求:速度最優 + +大神們快來踴躍探討~~~ + +問題出自 [segmentfault](https://segmentfault.com/q/1010000006135723/a-1020000006139815), by [prolifes](https://segmentfault.com/u/prolifes) + +## 回答 + +### 各路大神的回答 + +#### [citaret](https://segmentfault.com/u/citaret) 的回答 + +先贴上一版: + +```python +x = 6 +xs = [] +while True: + xs.append(x // 3) + x = x % 3 * 10 + x // 3 + if x == 6: + print ''.join(str(x) for x in xs) + break +``` + +输出: + +``` +2068965517241379310344827586 +``` + +原理是手算,把每次得到的商的末位补到被除数的最后,然后继续除法,直到末位为6,且余数为0停止。 + +#### [hsfzxjy](https://segmentfault.com/u/hsfzxjy) 的回答 + +由於數學公式的使用請大家前往問題原出處查看 [回答](https://segmentfault.com/q/1010000006135723/a-1020000006139815) + +### 我的回答 + +下午看到這題的時候就有了個想法, 手邊沒電腦只好等到現在... + +後來看到 @citaret 的答案就發現剛好是反向的想法, 下面是我的作法: + +```python +x = 6 +last_carry = 0 +result = 6 +radix = 10 + +while True: + c1, x = divmod(x * 3, 10) + c2, x = divmod(x + last_carry, 10) + last_carry = c1 + c2 + + if x==6 and last_carry==0: + return result + + result += (x * radix) + radix *= 10 +``` + +想法就剛好是反過來, 我一步一步地乘上去 + +* 每次把 `x` 乘 3 + * 把個位數加上 `last_carry` 就是下次的 `x` + * 把十位數的進位留下來當作下次的 `last_carry` + * 做到 `x==6` 且無進位的時候 + +用圖來思考長這樣: + +``` +0 <-- last carry + \ +1 8 = 6 X 3 + \ (0 + 8 = 8) +2 4 = 8 X 3 + \ (1 + 4 = 5) +1 5 = 5 X 3 +... +``` + +用 `timeit` 稍微測了一下時間(各運行 1000000 次), 共測三次: + +``` +# first +dokelung: 17.301649590954185 +citaret: 18.24915363173932 + +# second +dokelung: 19.257807812653482 +citaret: 17.994877750985324 + +# third +dokelung: 17.0617663115263 +citaret: 18.355605391785502 +``` + +時間看起來差不多, 不過我自認為代碼沒有很漂亮... diff --git "a/questions/django/Django CSRF verification failed \345\225\217\351\241\214.md" "b/questions/django/Django CSRF verification failed \345\225\217\351\241\214.md" new file mode 100644 index 0000000..f146839 --- /dev/null +++ "b/questions/django/Django CSRF verification failed \345\225\217\351\241\214.md" @@ -0,0 +1,93 @@ +# Django CSRF verification failed 問題 + +## 問題 + +**urls.py** + +```python +from django.conf.urls import url +from django.contrib import admin +from blog import views +urlpatterns = [ + url(r'^admin/', admin.site.urls), + url(r'^$', views.index), + url(r'^abc$',views.handler), +] +``` + +**views.py** + +```python +# -*- coding: utf-8 -*- +from django.shortcuts import render +from django.http import HttpResponse + +# Create your views here. + +def index(request): + return render(request,"index.html") + + +def handler(request): + return HttpResponse("
name:
" + request.POST['username']) +``` + +**index.html** + +```python + + + + +