Re: [問題] 新手list問題請教

作者: jasonislin (jason)   2018-09-28 04:01:46
def increment(self, add=1, output=[]):
for index, value in enumerate(self[::-1]):
add += value * 10 ** (index)
output.insert(0, (add // 10 ** index ) % 10)
return output
print(increment([0, 9, 9, 9])
我的結構弄得比較複雜, 希望能再精進, 望版友不吝指正, 謝謝:-) ;
概念為: 將數列視為10為底的指數列, 並依位數加總運算
1. 預設arg: add=1 (whole list increment by 1), output (empty list)
2. 利用enumerate()及slicing[start:end:step]作數列運算-由各個位數加總
for index, value in enumerate(self[::-1]):
>>> 0, 9
1, 9
2, 9
3, 0
依序為(倒數)第0項(start=0), 第0項值
3. 利用list.insert(index=0, x)特性及operator計算各位數的值
4. add值為總合
補充:參考cutekid版友所提供的運算法, 增加sling的結構, 控制output的數列規模,
運算式如下:
def increment(self):
num = int(''.join(str(x) for x in self))
num = num + 1
numList = list(str(num).zfill(len(self)))
return [int(x) for x in numList[len(numList)-len(self):]]
print(increment([0, 0, 9, 9]))
print(increment([9, 9, 9, 9]))
>>>[0, 1, 0, 0]
>>>[0, 0, 0, 0]
※ 引述《rexyeah (ccccccc)》之銘言:
: a = [0, 9, 9, 9]
: def s(n):
: return n+1 if n < 9 else (n+1) % 10
: print map(lambda x: s(x), a)
: ==
: Output
: [1, 0, 0, 0]
: ※ 引述《cutekid (可愛小孩子)》之銘言:
: : def increment(self):
: : num = int(''.join(str(x) for x in self))
: : num = num + 1
: : numList = list(str(num).zfill(len(self)))
: : return [int(x) for x in numList]
: : print(increment([0,9,9,9]))
: : 參考:
: : 1. How to convert list to string [duplicate]
: : https://bit.ly/2xz7uSj
: : 2. Nicest way to pad zeroes to a string
: : https://bit.ly/2IidRxs
: : 3. how do I convert a string to a list
: : https://bit.ly/2OQShTf
作者: stucode   2018-09-28 21:17:00
預設參數的用法是錯的喔。
作者: jasonislin (jason)   2018-09-29 09:24:00
謝謝您的指點,想麻煩您說明我錯誤的部分,以利我改進!
作者: stucode   2018-09-29 10:44:00
output=[] 的部分,這樣寫的話每次 output 都會指向同一物件,導致每次函數結果會串接在一起。如果不知道在說什麼的話,多跑幾次 increment() 看看結果應該就知道了。傳統的作法是,參數預設 output=None,然後在函數裡檢查if output is None: output = []

Links booklink

Contact Us: admin [ a t ] ucptt.com