Python ISBN program

大兔子大兔子 提交于 2019-12-12 02:29:44

问题


I'm trying to calculate the check digit for an ISBN input on python. so far I have...

    def ISBN():
        numlist = []
        request = raw_input("Please enter the 10 digit number:  ")
        if len(request) == 10:
            **numlist == request
            print numlist**
        if len(request) != 10:
            print "Invalid Input"
            ISBN()

    ISBN()

The bold bit is where im having trouble, I cant seem to split the 10 digit input into individual numbers in the list (numlist) and then multiply the seperated individual numbers by 11 then the next by 10 then the next by 9 etc... For the next part of the program, I will need to add these new multiplied numbers in the list together, then i will use the mod(%) function to get the remainder then subtract the number from 11, any assistance with any of my coding or incorrect statements on how to calculate the ISBN would be greatly appreciated. Thank you.


回答1:


This code should get you on your way:

listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]

Strings are iterable, so if you iterate them, each element is returned as a single-character string.

int builds an int from a (valid) string.

The notation [a*b for a,b in zip(listofnums, multipliers)] is a list comprehension, a convenient syntax for mapping sequences to new lists.

As to the rest, explore them in your repl. Note that reversed returns a generator: if you want to see what is "in" it, you will need to use tuple or list to force its evaluation. This can be dangerous for infinite generators, for obvious reasons.




回答2:


I believe list() is what you are looking for.

numlist=list(request)

Here is how I would write the code. I hope I'm interpreting the code correctly.

def ISBN():
    request = raw_input("Please enter the 10 digit number:  ")
    if len(request) == 10:
        numlist = list(request)
        print numlist
    else:
        print "Invalid Input"

ISBN()



回答3:


import itertools

if sum(x * int(d) for x, d in zip(nums, itertools.count(10, -1))) % 11 != 0:
    print "no good"


来源:https://stackoverflow.com/questions/9707185/python-isbn-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!