我使用Python 3.5,這是我處理目前代碼:Python如何優雅地處理不同數據結構的用法?
def is_odd_number(n):
"""states if n is an odd number"""
return n % 2 == 1
def collatz_next(n):
"""returns the successor to n in Collatz sequence"""
return 3*n + 1 if is_odd_number(n) else n//2
def collatz_seq_sum(seq):
"""returns the sum of all elements to a given Collatz sequence"""
return sum(seq)
def collatz_seq(n):
"""returns the Collatz sequence to n"""
l = []
l.append(n)
current = n
while current != 1:
next_one = collatz_next(current)
l.append(next_one)
current = next_one
return l
def collatz_seqs(lower_limit=1, upper_limit=10):
"""returns Collatz sequences from lower_limit to upper_limit"""
return {i: collatz_seq(i) for i in range(lower_limit, upper_limit+1)}
我認爲這類型list
是最好的一個在Collatz序列的時候。這就是爲什麼collatz_seq
返回一個列表。然而,我發現觀察連續處理多個參數n
時這個特定序列是如何發展是很有趣的。這就是爲什麼我創建了collatz_seqs
。
我不喜歡collatz_seq_sum
有一個非常簡單的原因:它只有在參數seq
的類型爲list
時才能正常工作。在我看來,collatz_seq_sum
不是確保提供適當的實際參數的責任,在這種情況下,list
由自然數組成。在我看來,致電collatz_seq_sum
必須確保它提供了一個正確的參數。
我想要collatz_sum_seq
可以使用單個和多個序列。 collatz_seq
返回list
和collatz_seqs
返回dict
。因此我的問題是:確保collatz_seq_sum
始終爲其參數seq
獲取正確數據類型的優雅方法是什麼?關於collatz_seq_sum
的正確工作,我可以做些什麼?collatz_seq_sum
關心其參數seq
的數據類型?我的第一個想法是更改collatz_seq
以使其返回dict
而不是list
並更改collatz_seq_sum
以處理dict
。但是,我不喜歡這種方法,因爲我不想在處理單個序列時使用dict
。
您有任何解決方案嗎?非常感謝你提前。
[mypy](https://github.com/python/mypy)靜態類型檢查庫提供了[裝飾器](https://jeffknupp.com/blog/2013/11/29/improve-your- python-decorators-explained /)命名爲「重載」,它似乎允許你想要的那種多態:http://mypy.readthedocs.io/en/latest/function_overloading.html。看起來很有希望給我。 –
會[functools.singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch)有幫助嗎? – wwii