ISBN final digit finder

前端 未结 2 2077
灰色年华
灰色年华 2020-12-22 10:00

I am working in python 3 and I am making a program that will take in a 10 digit ISBN Number and applying a method to it to find the 11th number.

Here is my current c

2条回答
  •  我在风中等你
    2020-12-22 10:13

    I think this should do what you want.

    def get_isbn_number(isbn):
        digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
        digit_11 = 11 - (sum(digits) % 11)
        if digit_11 == 10:
            digit_11 = 'X'    
        digits.append(digit_11)
        isbn_number = "".join(map(str, digits))
        return isbn_number
    

    EXAMPLE

    >>> print(get_isbn_number('2345432681'))
    22303640281810242428
    >>> print(get_isbn_number('2345432680'))
    2230364028181024240X
    

    Explanation of second line:

    digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
    

    Could be written out like:

    isbn_letters = list(isbn) # turn a string into a list of characters
    isbn_numbers = map(int, isbn_letters) # run the function int() on each of the items in the list
    digits = [] # empty list to hold the digits
    for i, num in enumerate(isbn_numbers): # loop over the numbers - i is a 0 based counter you get for free when using enumerate
        digits.append((11 - i) * num) # If you notice the pattern, if you subtract the counter value (starting at 0) from 11 then you get your desired multiplier
    

    Terms you should look up to understand the one line version of the code:
    map,
    enumerate,
    list conprehension

提交回复
热议问题