【发布时间】:2015-03-15 17:14:48
【问题描述】:
def check(barcode):
if not len(barcode) == 13:
return False
digits = list(map(int, barcode))
# 1. Add the values of the digits in the
# even-numbered positions: 2, 4, 6, etc.
even_sum = digits[1] + digits[3] + digits[5] + digits[7] + digits[9] + digits[11]
# 2. Multiply this result by 3.
even_sum_three = even_sum * 3
# 3. Add the values of the digits in the
# odd-numbered positions: 1, 3, 5, etc.
odd_sum = digits[0] + digits[2] + digits[4] + digits[6] + digits[8] + digits[10]
# 4. Sum the results of steps 2 and 3.
total_sum = even_sum_three + odd_sum
# 5. The check character is the smallest number which,
# when added to the result in step 4, produces a multiple of 10.
next_ten = (math.ceil(total_sum / 10)) * 10
check_digit = next_ten - total_sum
# 6. if the check digit and the last digit of the
# barcode are OK return true;
if check_digit == digits[12]:
return True
else:
return False
我有上面的代码。它计算一个 ean 数的校验和。我试图通过使用 Cython 来加速它。此代码在循环中使用。可变条形码是一个字符串。
但我没能提高速度。我试过了:
-
np.array(list(map(int, barcode)))- 这让它稍微慢了一点 -
np.ceil()而不是math.ceil()- 也让它稍微慢了一点 -
cdef bool def check(....- 也没有帮助
我还能做什么?
【问题讨论】:
-
barcode的初始格式是什么? -
@orlp:一个 13 个字符的 UPC。
-
@IgnacioVazquez-Abrams 我的意思是在 Python 中,没有称为
UPC的对象类型 :) 它是字符串,还是? -
@orlp: UPCs 是 13 个数字的序列,由 12 个识别数字和一个校验数字组成。
-
@IgnacioVazquez-Abrams 我在问输入类型是否应为字符串、字符元组等 - 在运行时。我不知道 UPC 是什么。
标签: python performance cython