如果有人看过我的代码,告诉我哪里做错了,我会非常感激。整个程序用于验证UPC-12和ISBN-10编号。我首先创建了一个模块,然后创建了一个主程序,并导入了我的模块。我们不应该使用"len“(长度)或子字符串。我的主要问题是,当用户在我的主程序中输入一个数字时,无论它是UPC-12还是ISBN-10,它总是返回false,这意味着我的程序会说"invalid“,这是我的模块:
# Gets the digit of the number using the specified position
def get_digit(number, position):
return number / (10**position) % 10
def is_UPC12(number):
sum_odd = 0
sum_even = 0
#loops through the UPC code and checks every odd position and adds the numbers
for position in range(1, 12, 2):
# calls the function
get_digit(number, position)
# gets the value
odd_code = get_digit(number, position)
sum_odd += odd_code
sum_odd *= 3
#loops through the UPC code and checks every even position and adds the numbers
for num in range(2, 12, 2):
get_digit(number, position)
even_code = get_digit(number, position)
sum_even += even_code
total = sum_odd + sum_even
total = total % 10
#subtracts 10 from the last digit of the sum, and if it's equal to the last digit of number then it returns True.
if 10 - total == get_digit(number , 0):
return True
else:
return False
def is_ISBN10(number):
repeat = 1
figure = 0
for position in range(1, 10):
# calls the function
get_digit(number, position)
# gets the value
isbn_code = get_digit(number, position)
figure = number * repeat
repeat += 1
total = figure % 11
if total == get_digit(number , 0):
return True
else:
return False下面是我的主程序,它导入我的模块:
import digitcheck2
def main():
print "CHECK DIGIT VALIDATOR\n"
print "What would you like to validate:\n"
print "1. ISBN-10"
print "2. UPC-12"
print "Q. Quit Program\n"
quit = False
while quit == False:
choice = raw_input("Which one?: ")
if choice == "1":
ISBN_Valid()
elif choice == "2":
UPC_Valid()
elif choice == "Q" or choice == "q":
quit = True
def ISBN_Valid():
num = input("Please enter a ISBN-10 number: ")
if digitcheck2.is_ISBN10(num) == True:
print "Valid ISBN-10 code.\n"
elif digitcheck2.is_ISBN10(num) == False:
print "Invalid ISBN-10 code.\n"
def UPC_Valid():
number = input("Please enter a UPC-12 number: ")
if digitcheck2.is_UPC12(number) == True:
print "Valid UPC-12 code.\n"
elif digitcheck2.is_UPC12(number) == False:
print "Invalid UPC-12 code.\n"
main()发布于 2016-11-23 10:27:37
我看到的第一个问题是get_digit函数:它没有完成它应该做的事情。现在,我将简单地使用str和int创建一个替代版本,而不是修复数学问题,这显然可以进一步优化:
# Gets the digit of the number using the specified position
# position is 1-based
def get_digit(number, position):
return int(str(number)[position-1])这会修复is_UPC12的结果。
至于is_ISBN10,其中有一个可疑的路径,其中没有使用变量isbn_code,以及在此之前对get_digit()的一个几乎无用的调用,所以我们应该重新查看代码。
根据ISBN10,对像abcdefghij这样的数字的计算应该是这样的:
j = ( [a b c d e f g h i] * [1 2 3 4 5 6 7 8 9] ) mod 11因此,我将函数重写为:
def is_ISBN10(number):
z = zip(map(int, str(number)), range(1,10))
total = sum(x * y for x, y in z)
parity = total%11
print parity, get_digit(number, 10)
return parity == get_digit(number, 10)虽然它使用了一些更复杂的python构造,但它应该仍然具有足够的可读性。这将验证UPC10值。
注意,注释中的值130417173对UPC10来说似乎不是,它只有9位数。
https://stackoverflow.com/questions/40754592
复制相似问题