亞東科技大學 電機系 施勢帆老師的教學網站

 找回密碼
 立即註冊
搜索
熱搜: 活動 交友 discuz
查看: 25|回復: 0

偵錯 ISBN 驗證器

[複製鏈接]

77

主題

77

帖子

373

積分

管理員

Rank: 9Rank: 9Rank: 9

積分
373
發表於 6 天前 | 顯示全部樓層 |閱讀模式

def validate_isbn(isbn, length):
    if len(isbn) != length:
        print(f'ISBN-{length} code should be {length} digits long.')
        return

    main_digits = isbn[0:length-1]
    given_check_digit = isbn[length-1]

    try:
        main_digits_list = [int(digit) for digit in main_digits]

    except ValueError:
        print('Invalid character was found.')
        return

    # Calculate the check digit from other digits
    if length == 10:
        expected_check_digit = calculate_check_digit_10(main_digits_list)
    else:
        expected_check_digit = calculate_check_digit_13(main_digits_list)

    # Check if the given check digit matches with the calculated check digit
    if given_check_digit == expected_check_digit:
        print('Valid ISBN Code.')
    else:
        print('Invalid ISBN Code.')


def calculate_check_digit_10(main_digits_list):
    digits_sum = 0

    for index, digit in enumerate(main_digits_list):
        digits_sum += digit * (10 - index)

    result = 11 - digits_sum % 11

    if result == 11:
        expected_check_digit = '0'
    elif result == 10:
        expected_check_digit = 'X'
    else:
        expected_check_digit = str(result)

    return expected_check_digit


def calculate_check_digit_13(main_digits_list):
    digits_sum = 0

    for index, digit in enumerate(main_digits_list):
        if index % 2 == 0:
            digits_sum += digit * 1
        else:
            digits_sum += digit * 3

    result = 10 - digits_sum % 10

    if result == 10:
        expected_check_digit = '0'
    else:
        expected_check_digit = str(result)

    return expected_check_digit


def main():
    user_input = input('Enter ISBN and length: ')

    try:
        values = user_input.split(',')
        isbn = values[0]
        length = int(values[1])

    except IndexError:
        print('Enter comma-separated values.')
        return

    except ValueError:
        print('Length must be a number.')
        return

    if length == 10 or length == 13:
        validate_isbn(isbn, length)
    else:
        print('Length should be 10 or 13.')


# main()


回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

Archiver|手機版|小黑屋|亞東科技大學 電機系 施勢帆老師的教學網站

GMT+8, 2026-11-18 23:35 , Processed in 0.054387 second(s), 20 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回復 返回頂部 返回列表