Python使用for each loops,因此迭代數字將需要您先產生一個數字序列。 Python使用range()
type此:
sum = 0
for i in range(len(factors)):
pass
注意sum
分配0
明確,分開。
通常但是,你只是在對象環路直接,而不是生成指數:
sum = 0
for element in factors:
pass
但是,如果你正在總結的因素,只使用sum()
function:
total = sum(factors)
請注意,我避免在那裏使用名稱sum
以避免屏蔽內置功能。
要從字節序列相乘字節,只是zip()
字節和因素一起:
sum = 0
for byte, factor in zip(string, factors):
sum += byte * factor
可與sum()
被摺疊和發電機表達式:
total = sum(byte * factor for byte, factor in zip(string, factors))
這僅適用於如果string
是bytes
object,而不是Unicode str
string object; bytes
對象實際上是0-255範圍內的整數序列。
如果你想解釋字符數字,使用Unicode字符串,並使用int()
每個轉換爲整數:後者的
total = sum(int(digit) * factor for digit, factor in zip(string, factors))
演示與您提供的樣本輸入:
>>> sec_number = '0411994545'
>>> factors = [4, 3, 2, 7, 6, 5, 4, 3, 2, 1]
>>> sum(int(digit) * factor for digit, factor in zip(string, factors))
164
>>> total = sum(int(digit) * factor for digit, factor in zip(string, factors))
>>> total % 11 == 0
False
請注意,==
測試已生成布爾值;不需要在Python中使用條件表達式來產生布爾結果。
你會用'i'和'sum'做什麼? – 2014-12-06 21:35:02
查看上面更新的代碼。謝謝。 – 7c9d6b001a87e497d6b96fbd4c6fdf 2014-12-06 21:36:46
你可以顯示你的字符串將如何看起來像? – Hackaholic 2014-12-06 21:39:22